From rodelrod at hotmail.com Wed Jun 9 09:14:18 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Wed, 9 Jun 2004 15:14:18 +0200 Subject: installing cx_Oracle References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> Message-ID: <38yg2sq5y9id.24dpo4ccp9hr.dlg@40tude.net> On Tue, 08 Jun 2004 12:42:00 +0200, David Fraser wrote: > Aha! But you can... there are at least two DB API wrappers for ADO: > http://pyado.sourceforge.net/ > http://adodbapi.sourceforge.net/ Yes! I imagined such a wrapper might exist and found adodbapi. It seems quite satisfactory. I'll have a look at pyado too. Thanks again, David. Rodrigo From __peter__ at web.de Sat Jun 26 05:07:08 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Jun 2004 11:07:08 +0200 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: Doug Holton wrote: > Is there any metaclass trick or something similar to allow anonymous > code blocks? > > I'd like to be able to let users do something like this fictitious > example: b = Button() > b.OnClick =: > print "you clicked me" > > But that would require adding a special "=:" operator to bind a code > block to a function. > Is there any PEP for something like that? I see 310 might allow: > b=Button() > with b.OnClick: > print "you clicked me" > > I know I can already do it like these examples: > def OnClick(self,event): > print "you clicked me" > b.OnClick = OnClick > or > b = Button(OnClick=OnClick) > or subclassing Button. Maybe you can use something as simple as a naming convention, i. e. automatically associate a function b1OnClick() with a button b1: import types class Widget: pass class Button(Widget): def __init__(self, name): self.name = name def makeMethod(widget, methodname, function): setattr(widget, methodname, lambda: function(widget)) def collectMethods(): ns = globals() widgets = [] functions = [] for n, i in ns.items(): if isinstance(i, Widget): widgets.append((n, i)) elif isinstance(i, types.FunctionType): functions.append((n, i)) for fn, f in functions: for wn, w in widgets: if fn.startswith(wn): makeMethod(w, fn[len(wn):], f) break #begin client code b1 = Button("one") b2 = Button("two") b3 = Button("three") def b1OnClick(self): print "you clicked button 1" def b2OnClick(self): print "you clicked button %s" % self.name b3OnClick = b2OnClick #end client code collectMethods() b1.OnClick() b2.OnClick() b3.OnClick() From twl at osafoundation.org Fri Jun 25 16:47:59 2004 From: twl at osafoundation.org (Ted Leung) Date: Fri, 25 Jun 2004 13:47:59 -0700 Subject: OSAF announces open source Chandler subproject - PyLucene Message-ID: We invite you to take a look at the new OSAF project at http://pylucene.osafoundation.org PyLucene is a Python wrapper around the Lucene indexing and search engine. It was developed by Andi Vajda at OSAF for use in Chandler. PyLucene is a way of letting Python use Lucene to do full text indexing. There has been a lot of interest and feedback from the Python developer community that it would be nice to be able to get this functionality without having to deal with all of the Chandler source tree. This interest lead naturally to the idea of a separate project. During the weekly OSAF IRC Office Hour on June 23, 2003 there was a discussion with Andi, the original developer of PyLucene about its origins, scope, and current status. You can review this conversation on the IRC log (from 11:00 to noon). ---- Ted Leung Open Source Applications Foundation (OSAF) PGP Fingerprint: 1003 7870 251F FA71 A59A CEE3 BEBA 2B87 F5FC 4B42 From BELLEMAIL-SA at exponent.com Sat Jun 19 00:01:56 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Fri, 18 Jun 2004 21:01:56 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EEE@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = vwehtja at jumpy.it Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 237 Scanning time = 06/18/2004 21:01:56 Engine/Pattern = 7.000-1004/909 Action taken on message: The message body contained HTML_Netsky.P virus. ScanMail deleted the message body. The attachment message.scr matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From dominic.fox at square3.net Tue Jun 8 09:49:06 2004 From: dominic.fox at square3.net (Dominic Fox) Date: Tue, 8 Jun 2004 14:49:06 +0100 Subject: Callbacks to generators In-Reply-To: <_Zhxc.27159$sS2.784227@news20.bellglobal.com> Message-ID: It would be nice if something like this *could* work - you could instantly and effortlessly transform a SAX parser into a .Net-style XmlReader. Alas, it cannot... "yield" in a function causes the function to return a generator object to the caller - in this case, the caller of on_token, not the caller of process_iter. The inner function "on_token" in "process_iter" returns a generator when it is called by "process", and "process" promptly throws this generator away. The value returned by "process_iter" is just the return value from "process". It might be possible to do something with call/cc, but of course Python doesn't have that. Dominic -----Original Message----- From: Humpty Dumpty [mailto:oliver.schoenborn at utoronto.ca] Sent: 08 June 2004 13:07 To: python-list at python.org Subject: Re: Callbacks to generators > def process(text, on_token): > ... > > For each token that "process" finds in "text", it creates a token object, > "token", and calls "on_token(token)". > > Now, suppose I wanted to create a generator based on this function. I tried > to do the following: > > def process_iter(text): > def on_token(token): > yield token > process(text, on_token) > > However, rather than create a generator as I had hoped, this function > doesn't return anything. I guess it creates a bunch of singleton generators, > one per token, and throws them away. In any case, is there a way to do what > I am trying to do here without resorting to threads? Something weird here. I hven't used generators much, but seems to me that: 1) you maybe don't need them: def process_iter(text): def on_token(token): return token process(text, on_token) 2) you need some sort of while loop so the fnction doesn't return after the first yield: def process_iter(text): def on_token(token): while 1: yield token process(text, on_token) I'm curious to understand if neither of those are true, why... Oliver From calfdog at yahoo.com Wed Jun 2 18:19:15 2004 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 2 Jun 2004 15:19:15 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> Message-ID: r.gable at mchsi.com (Ralph A. Gable) wrote in message news:<22b7fd40.0405231744.50d125f1 at posting.google.com>... > I'm a newbie at this but I need to control MSIE6 using Python. I have > read the O'Reilly win32 python books and got some hints. But I need to > Navigate to a site (which I know how to do) and then I need to get at > the source code for that site inside Python (as when one used the > View|Source drop down window). Can anyone point me to some URLs that > would help out? Or just tell me how to do it? I would be very > grateful. TRY THIS!!!! from win32com.client import DispatchEx import time def wait(ie): # very important!!! you have to wait for each page to load "Given an IE object, wait until the object is ready for input." while ie.Busy: time.sleep(0.1) doc = ie.Document while doc.ReadyState != 'complete': time.sleep(0.1) return doc def ClickLink(ie, mylink): #hrefs = [] for link in ie.Document.links: if link is None: break # needed for browser bug if link.innerText == mylink: link.Click() # Here is what you need ie = DispatchEx('InternetExplorer.Application') ie.Visible = 1 ie.Navigate ('www.python.org') # Some extra wait(ie)# Very important you must wait for document to finish loading ClickLink(ie,'Search') #later #RLM From grante at visi.com Tue Jun 29 15:22:52 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jun 2004 19:22:52 GMT Subject: setting icon using py2exe? Message-ID: I'm trying in vain to set the icon for the executable generated by py2exe. According to various sources there are two answers: 1) Do it on the command line: python setup.py py2exe --icon foo.ico That generates a usage error: error: --icon not recognized 2) According to http://starship.python.net/crew/theller/moin.cgi/CustomIcons you can set the icon_resources in the setup.py like this: # setup.py from distutils.core import setup import py2exe setup(windows=[{"script":"vfcupdate.py","icon_resources":[(1,"rivatek.ico")]}]) That doesn't work either: running py2exe [...] copying C:\Python23\Lib\site-packages\wx\wxmsw251h_html_vc.dll -> C:\cygwin\home\admin\othertools\dist copying C:\Python23\Lib\site-packages\wx\wxbase251h_vc.dll -> C:\cygwin\home\admin\othertools\dist copying C:\PYTHON23\w9xpopen.exe -> C:\cygwin\home\admin\othertools\dist copying C:\WINDOWS\SYSTEM\python23.dll -> C:\cygwin\home\admin\othertools\dist copying C:\Python23\Lib\site-packages\py2exe\run_w.exe -> C:\cygwin\home\admin\othertools\dist\vfcupdate.exe Traceback (most recent call last): File "setup.py", line 5, in ? setup(windows=[{"script":"vfcupdate.py","icon_resources":[(1,"rivatek.ico")]}]) File "C:\PYTHON23\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\PYTHON23\lib\distutils\dist.py", line 907, in run_commands self.run_command(cmd) File "C:\PYTHON23\lib\distutils\dist.py", line 927, in run_command cmd_obj.run() File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 197, in run self.create_binaries(py_files, extensions, dlls) File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 395, in create_binaries arcname, target.script) File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 577, in build_executable add_icon(unicode(exe_path), unicode(ico_filename), ico_id) RuntimeError: MapExistingFile: The handle is invalid. Has anybody really been able to set the icon for the executable generated by py2exe? -- Grant Edwards grante Yow! Now I'm concentrating at on a specific tank battle visi.com toward the end of World War II! From db3l at fitlinxx.com Mon Jun 7 17:52:02 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jun 2004 17:52:02 -0400 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> <40c0b153$1_1@127.0.0.1> Message-ID: "beliavsky at aol.com" writes: > I am no C++ expert, to put it mildly, but couldn't some of your > problems have been solved by using C++ instead of C? C++ has data > structures like vectors, lists, and maps, with many algorithms in > the STL to work with them. Using references to pass arguments, one > can avoid low-level pointers in many cases. C++ strings are easier > to use the C char's. There are templated classes to replicate some > of the functionality of Python's Numeric/Numarray or Fortran 90/95 > arrays. C is more of a low-level systems language than an > application programming language -- comparing it to Python seems > unfair to me, when the choice of C++ exists. I don't know if it's just me, but a funny thing I've found is that after using Python almost extensively for the past 4-5 years, I find it much easier to grasp and appreciate the C++ STL than I did prior to Python. Of course, to be fair back before Python when I was using C++ more significantly, I hadn't really been out of the C world for too long, and I recall compiler template support being more hit and miss so trusting the STL (if it was even available) was tricky, but I think Python helped get my mindset more acclimated to the higher level data constructs, making it more natural to use their C++ counterparts when working nowadays with C++, things which I tended not to utilize as effectively in the past. With that said, doing similar work in C++ versus Python even today feels like I'm working in a tar pit while working on the C++ side. Oh, I like the performance and part of me still can't help but enjoy the feeling of working closer to the metal, but egads, the extra typing (particularly with the STL), the fighting with the compiler's type checking, those horrible template error messages. Heck, basic iteration, or even the hoops to jump through to bind instance members for callbacks. The STL is a valuable set of generic containers and algorithms that I wouldn't want to do without in C++, but similiar to the original poster's point, I still feel burdened down with details when working with them compared to equivalent Python code, even when the code is algorithmically and data structurally similar. Of course, the end performance advantage of the C++ version over the Python version makes up for that in some specific cases, but not enough for me to ever want to go back to C++ as a language of first choice for most of my target development, even with the STL, strings and other templated classes. -- David From eurleif at ecritters.biz Fri Jun 18 20:55:02 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 18 Jun 2004 20:55:02 -0400 Subject: Templating engine? In-Reply-To: <35m6d0dejkk88urvkvvfs4fslk9e8900vm@4ax.com> References: <2jh2glF10adr2U1@uni-berlin.de> <35m6d0dejkk88urvkvvfs4fslk9e8900vm@4ax.com> Message-ID: <2jhh7pF11m1q4U1@uni-berlin.de> Rene Pijlman wrote: > I've used Cheetah with mod_python and it worked fine: > http://www.cheetahtemplate.org/ Looks interesting, but the last update was over six months ago. Any idea what might be going on with it? From pwatson at redlinepy.com Wed Jun 23 17:36:19 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 23 Jun 2004 16:36:19 -0500 Subject: Writing binary to stdout References: <2jrglkF153jroU1@uni-berlin.de> <2jsm1iF7ott5U4@uni-berlin.de> Message-ID: <2jubemF14b1jjU1@uni-berlin.de> "Christopher T King" wrote in message news:Pine.LNX.4.44.0406231449410.22670-100000 at ccc8.wpi.edu... > > On Wed, 23 Jun 2004, Reinhold Birkenfeld wrote: > > > Paul Watson wrote: > > > How can I write lines to stdout on a Windows machine without having '\n' > > > expanded to '\r\n'. > > > > > > I need to do this on Python 2.1 and 2.3+. > > > > > > I see the msvcrt.setmode function. Is this my only path? Is it valid to > > > change the mode of stdout? The file.newlines is not writable. > > > > What about opening the file in binary mode? This should give you control > > over the line endings. > > Believe it or not, open('CON:','wb') actually works under WinXP. It's > amazing that this relic from DOS is still around. Though unportable (the > Unix equivalent is open('/dev/stdout','wb')) and ugly, it'll get the job done. > > Optimally, you'd want to use something like C's freopen to re-open > sys.stdout in binary mode, but I can't find anything like it under the os > module. Does Python not have this ability? This will be a command to run a python script from inside another tool. It -must- write to stdout. Also, Cygwin is on the machine. Even when I try to use low-level I/O it does CRLF interpretation. What am I doing wrong? pwatson [ watsonp:/cygdrive/c/src/projects/pwatson/bin ] 22 $ cat ./wb.py #! /usr/bin/env python import sys import os try: import msvcrt f = os.open(1, 'wb') except: f = sys.stdout f.write("now\n") f.close() sys.exit(0) pwatson [ watsonp:/cygdrive/c/src/projects/pwatson/bin ] 23 $ ./wb.py >jjj pwatson [ watsonp:/cygdrive/c/src/projects/pwatson/bin ] 24 $ od -c jjj 000000 6e 6f 77 0d 0a n o w \r \n 000005 From alvinb7616 at aol.com Fri Jun 18 08:02:34 2004 From: alvinb7616 at aol.com (alvinb7616 at aol.com) Date: Fri, 18 Jun 2004 17:02:34 +0500 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: 9u049u89gh89fsdpokofkdpbm3?4i -------------- next part -------------- A non-text attachment was scrubbed... Name: id04009.pif Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From hgk at et.uni-magdeburg.de Tue Jun 15 03:36:34 2004 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Tue, 15 Jun 2004 09:36:34 +0200 Subject: inspect: get the calling command In-Reply-To: References: Message-ID: Inyeol Lee wrote: > It's an old bug. See Python bug [607092] at Sourceforge. > > Inyeol > Thanks for pointing me there. Resolution for this bug is 'Wont Fix'. So, did you have any idea how to work around that 'feature'. What I wanted to have is some kind of autosave functionality. I have a class doing some measurements which might take some days of time. At certain points, I want to pickle the class instance (this is working) to a file. If the measurement fails, e.g. due to a power main failure, I can recover from the pickle file. Now, I want also to save the command that issued the measurement in order to recover automatically with the right command. BTW, are you sure that my problem is really due to that bug. I'm asking because one comment stated: '...You should also check out current CVS, seeing as there are no SET_LINENO instructions any more...' Hans Georg From db3l at fitlinxx.com Mon Jun 7 17:09:55 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jun 2004 17:09:55 -0400 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: grahamd at dscpl.com.au (Graham Dumpleton) writes: > Now as to other template systems that are event driven system friendly, > the only one I know of for Python is Nevow, but that is bound up with > Twisted and thus couldn't be used with any other system. For my mind, > from the little I have looked at the Nevow examples, I am also not keen > on its magic system for callbacks dependent on naming. This sorts of > binds it quite tightly to a particular way of building your classes which I > would rather avoid. Note that even if the template system isn't directly event driven friendly, it can generally be used just fine with Twisted since you can acquire your data prior to rendering the template. For example, we are currently using ZPT with Twisted. We pre-compile the templates for pages when the web objects (which are basic twisted.web Resource objects) are built to establish the web site. Then, when asked to render a page, we can take our time working up the necessary context data (since the Twisted Resource object can return a pending indicator and the object can then use the normal Twisted deferred processing to complete the rendering). It's only once the data is fully realized that we ask ZPT to use the compiled template to construct the HTML. That operation is synchronous but there's no business logic running at that point, and no timing dependency between the original request and the final rendering. HTMLTemplate could be inserted into the same mix as long as we held off asking HTMLTemplate to render the DOM into HTML until we had all the necessary data acquired to answer the various callbacks immediately. That's probably the biggest advantage of Woven/Nevow in a Twisted context with respect to a more MVC model - they integrate cleanly into Twisted's event driven fabric with deferreds even during individual element callbacks so you don't have to prepare all the data in advance but can be driven from the template rendering process. -- David From danb_83 at yahoo.com Tue Jun 15 21:31:34 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Jun 2004 18:31:34 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> <494182a9.0406141915.7061d0f6@posting.google.com> Message-ID: balaji at email.arizona.edu (Balaji) wrote in message news:<494182a9.0406141915.7061d0f6 at posting.google.com>... > Hello Everybody... > > [against Python's automatic reflection of comparison operators] > > By modelling I mean, the user wants to preserve the order in which he > typed the expression. Why not preserve the original text of the expression? What exactly are you trying to do? From davidf at sjsoft.com Tue Jun 8 06:42:00 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 08 Jun 2004 12:42:00 +0200 Subject: installing cx_Oracle In-Reply-To: <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> Message-ID: Rodrigo Daunaravicius wrote: > On Fri, 04 Jun 2004 22:11:06 +0200, David Fraser wrote: > > >>If you really need to get it working with 8.0.x libraries, you could try >>converting the call to OCIInitialize() and OCIEnvInit() calls. >>You'll need to replace OCITerminate with OCIHandleFree. >>In my experience these are the two main changes between 8.0.x and 8.1 >>You might find some help from the cx_Oracle authors, but the oracle docs >>are fairly good. > > > Thanks, David. I successfully replaced the OCIEnvCreate() call, but still > had problems with OCILobCreateTemporary(), OCILobFreeTemporary(), > OCIUserCallbackRegister(), OCIUserCallbackGet(), OCI_UCBTYPE_ENTRY, > OCI_UCBTYPE_EXIT and OCI_UCBTYPE_REPLACE. This amount of patchwork from my > inexperienced hands would be asking for trouble, even if I could get it > compiled. Oh well, it was worth a try... > An 8i installation, as Aurelio suggested, is unfortunately not an option. > I'm now looking into ADO. I think it can fit the bill for my current > project, though I'd prefer to use the python DB API 2.0. Aha! But you can... there are at least two DB API wrappers for ADO: http://pyado.sourceforge.net/ http://adodbapi.sourceforge.net/ So your code remains DB-API compatible, and portable to other drivers, but gets to use ADO and support any database supported by that... David From sven.knop at versant.de Tue Jun 15 06:25:25 2004 From: sven.knop at versant.de (Sven Erik Knop) Date: Tue, 15 Jun 2004 11:25:25 +0100 Subject: Idle 2.3.4 won't start on Windows Message-ID: <40cece97$0$6320$65c69314@mercury.nildram.net> Hi probably an old problem, but maybe you can help me: Just installed Python 2.3.4 on Windows XP SP1, and although the interpreter runs fine, IDLE will not start. Any ideas how to solve this? Cheers Sven Erik From thehaas at binary.net Tue Jun 1 07:26:07 2004 From: thehaas at binary.net (thehaas at binary.net) Date: Tue, 01 Jun 2004 11:26:07 GMT Subject: Am I asking too much from datetime? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm trying to use the datetime module. The following seems to work any day except the first day of the month: >>> import datetime >>> today = datetime.date.today() >>> print today 2004-06-01 >>> yesterday = datetime.date(today.year, today.month, today.day-1) Traceback (most recent call last): File "", line 1, in ? ValueError: day is out of range for month In other languages (specifically Java, but I'm sure these are others), this would come out as "2004-05-31". Is this is a bug, or outside of the functionality of datetime? - -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAvGe4aP33v4T41CURAkQGAKChO0yxPDxHwXHTsNOb0eO92zECGgCdHKZ2 Irj6f33KpdXvwxsIhkM+Bo8= =IRWr -----END PGP SIGNATURE----- From johnseal at indy.net Sun Jun 20 18:36:43 2004 From: johnseal at indy.net (John Seal) Date: Sun, 20 Jun 2004 22:36:43 GMT Subject: Attention, hyperlinkers: inference of active text References: <10d6bln988rmne6@corp.supernews.com> Message-ID: In article <10d6bln988rmne6 at corp.supernews.com>, claird at lairds.com (Cameron Laird) wrote: > End-users "get it", and are happy I render > "http://www.ams.org" as a hyperlink. Most of them eventually > notice the implications for punctuation, that is, that they're > happier when they write So who is constructing these sentences, you or the end-users? > Look at http://bamboo.org ! > than > Look at http://bamboo.org! Any idea *why* are they happier with the first than the second? > The design breaks down more annoyingly by the time we get to > the "file" scheme, though. What design, and in what way is it breaking down? > I am confident that requiring > It is on my drive as file:\Program%20Files\Perl\odysseus.exe > is NOT practical with my clients. Any idea why not? The lack of terminal punctuation? From siona at chiark.greenend.org.uk Wed Jun 30 06:20:09 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jun 2004 11:20:09 +0100 (BST) Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: <1bs*2tkoq@news.chiark.greenend.org.uk> Mike C. Fletcher wrote: > PostgreSQL is freely available >for Windows platforms (I use it every day). It can be quite readily >installed as part of the CYGWIN environment, [ ... ] Which means that either you have to persuade your target audience to install Cygwin, or pay the licence to distribute the Cygwin DLL if you want to bundle PostgreSQL with your product (as you would be free to do with PostgreSQL on other platforms). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From mithrandi at mithrandi.za.net Mon Jun 28 13:51:08 2004 From: mithrandi at mithrandi.za.net (Tristan Seligmann) Date: Mon, 28 Jun 2004 19:51:08 +0200 Subject: a timer for benchmarking In-Reply-To: <87pt7ka0ss.fsf@uwo.ca> References: <87pt7ka0ss.fsf@uwo.ca> Message-ID: <20040628175108.GA9364@mithrandi.za.net> On Sun, Jun 27, 2004 at 22:12:03 -0400, Dan Christensen wrote: > Pretty good resolution! And unaffected by changes to the human form > of the system clock. If Python can find out the clock speed, then It IS, however, affected by changes to the CPU clock speed. Such changes are quite frequent due to various power saving strategies on laptops, etc. -- mithrandi, i Ainil en-Balandor, a faer Ambar -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From htx1 at gmx.de Wed Jun 2 04:23:40 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Wed, 02 Jun 2004 10:23:40 +0200 Subject: Converting Hex to decimal In-Reply-To: <70efe2ee.0406020009.1e1000d6@posting.google.com> References: <70efe2ee.0406020009.1e1000d6@posting.google.com> Message-ID: dean wrote: > The file is binary. Using the standard hpux or linux hexdump (xxd or > xd) this is the output that is obtained: > > 0000000: 5c1a 0100 0100 ff35 0399 7272 9903 0002 \......5..rr.... > 0000010: 010e 0300 050a 0214 ffff ffff 5cd4 2e01 ............\... > 0000020: fbb9 5900 b400 0000 0020 2000 b502 5423 ..Y...... ...T# > 0000030: 3a71 2e11 00ff ffff ffff ffff ffff ffff :q.............. > 0000040: ffff ffff ff00 ff07 0209 3519 4fff ffff ..........5.O... > 0000050: ffff ffff ffff ffff ffff ffff ffff ffff ................ > 0000060: ffff ffff ffff ffff ffff ffff ffff ffff ................ > 0000070: ffff ffff ffff ffff ffff ffff ffff ffff ................ > 0000080: ffff ffff ffff ff00 5435 3617 040a d207 ........T56..... > 0000090: 3e05 3717 040a d207 0000 0000 2c01 6000 >.7.........,.`. > 00000a0: 0141 01a8 0005 030b 0300 00ff ffff ffff .A.............. > 00000b0: ffff ffff ffff ffff ffff ff00 0000 0000 ................ > 00000c0: 0300 0000 5435 3617 040a d207 0b00 0000 ....T56......... > 00000d0: 0000 0000 fcb9 5900 b400 0000 0020 2000 ......Y...... . > 00000e0: b602 5423 3b71 2e11 00ff ffff ffff ffff ..T#;q.......... > 00000f0: ffff ffff ffff ffff ff00 2094 3965 0702 .......... .9e.. > 0000100: 0935 194f ffff ffff ffff ff07 0209 3519 .5.O..........5. > 0000110: 4fff ffff ffff ffff ffff ffff ffff ffff O............... > 0000120: ffff ffff ffff ffff ffff ffff ffff ffff ................ > 0000130: ffff ffff ffff ffff ffff ff00 1536 3617 .............66. > > Each hex character is 8 bits. I would like to convert one byte at the > time and pipe the converted data into a new file. Ok, you've got the hexdump and, as far as I understand, you want the binary data back, byte by byte. import binascii def makeBinary (f): for line in f: words = line.split () [1:9] for word in words: yield binascii.unhexlify (word [:2]) yield binascii.unhexlify (word [2:]) Then use the generator this way: for byte in makeBinary (open ("hexdumpfile", "r")): [...] I did not test it, but at least it is an outline of the way it can be done. Greetings, Holger From winexpert at hotmail.com Wed Jun 2 09:37:25 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 02 Jun 2004 13:37:25 +0000 Subject: Is this just for readability to the developer? python Message-ID: Thanks for the help. It makes it easier that its automated.... David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: "Miki Tebeka" >To: David Stockwell >CC: python-list at python.org >Subject: Re: Is this just for readability to the developer? python >Date: Wed, 2 Jun 2004 16:25:19 +0200 > >Hello David, > > > initModule( "$Revision: 3.1 $".split(" ")[1] ) > > ... > > In this example, it looks like only the '3.1' is actually passed to the > > function. Which leads me to speculate that the rest of it is just there >to > > make it easier for the developer when looking at source code to see what > > version of the module is being used. > > > > The only thing I think i notice is its also passing a list of one >element? > > > > Is this a typical way to do this in python? >The $Revision: ...$ is expaned by CVS/Subversion/... when you check in a >file (These are called "RCS keywords", see >http://computing.ee.ethz.ch/sepp/cvs-1.11.5-ds/cvsbook/main_162.html#SEC192). >This way the revision is actually maintined by the source control system. > >Bye. >-- >------------------------------------------------------------------------- >Miki Tebeka >The only difference between children and adults is the price of the toys. _________________________________________________________________ MSN 9 Dial-up Internet Access fights spam and pop-ups ? now 3 months FREE! http://join.msn.click-url.com/go/onm00200361ave/direct/01/ From maschio_77 at hotmail.com Thu Jun 24 17:49:35 2004 From: maschio_77 at hotmail.com (Federico) Date: Thu, 24 Jun 2004 23:49:35 +0200 Subject: Pil and freeze Message-ID: I used freeze.py with a script that import Pil, the script works well bat the executable I have send this error: im=PIL.Image.open(qs['im'][0]) File "D:\PYTHON~1.4\lib\site-packages\PIL\Image.py", line 1571, in open raise IOError("cannot identify image file") IOError: cannot identify image file How can I solve it? Thanks From fumanchu at amor.org Thu Jun 10 11:27:17 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 10 Jun 2004 08:27:17 -0700 Subject: does python have useless destructors? Message-ID: Duncan Booth wrote: > Apparently the next release of Microsoft's C++ for managed > environments > will handle the issue in quite a nice way. They will let you declare > managed heap based objects as though they are on the stack, > and if the > object supports their dispose pattern the compiler > automatically inserts > the required try..finally block. Python might need an extra > keyword, but > perhaps it could benefit from something similar. > > e.g. > > def f(filename): > dispose infile, outfile > > infile = file(filename, "r") > outfile = file(filename+".out", "w") > outfile.write(infile.read()) > > would be equivalent to something like: > > def f(filename): > try: > infile = file(filename, "r") > outfile = file(filename+".out", "w") > outfile.write(infile.read()) > finally: > _inexception = sys.exc_info()[0] is not None > for _temp in ['outfile', 'infile']: > if _temp in locals(): > try: > locals()[_temp].__dispose__() > except: > pass > if not _inexception and sys.exc_info()[0] is not None: > raise > > Obviously the keyword might be something other than dispose, > and the method > called to dispose of the object might have a different name. > Plus I'm not > sure I got the logic right on what the equivalent code should > be (which I > think is an argument *for* a scheme such as this). It should > be ignoring > variables which aren't yet set, and preserving the original > exception if > there is one, but if any __dispose__ throws an exception that > should be > propogated while not preventing all other __dispose__ methods > also being > called. AFAICT, you don't need to reraise the exception. Example: >>> try: ... f ... finally: ... print 'finally' ... finally Traceback (most recent call last): File "", line 2, in ? NameError: name 'f' is not defined But I could be wrong--perhaps you've got a requirement I can't see on first glance. Given that, perhaps we can simplify your example to: def f(filename): try: infile = file(filename, "r") outfile = file(filename+".out", "w") outfile.write(infile.read()) finally: for _temp in ['outfile', 'infile']: if _temp in locals(): try: locals()[_temp].__dispose__() except: pass ...which could be rewritten as (totally untested)... def dispose(localdict, argnames): for name in argnames: obj = localdict.get(name) if obj: try: dispfunc = obj.__dispose__ except AttributeError: pass else: dispfunc() def f(filename): try: infile = file(filename, "r") outfile = file(filename+".out", "w") outfile.write(infile.read()) finally: dispose(locals(), 'infile', 'outfile') Write dispose once and drop it somewhere accessible in my site...a rather convenient idiom. Thanks! I think I'll pursue it. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mwh at python.net Thu Jun 17 07:07:42 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jun 2004 11:07:42 GMT Subject: Bug in psyco ? References: <40d09f77$1@rutgers.edu> Message-ID: "George Sakkis" writes: > >>> import inspect > >>> inspect.stack() > [(, '', 1, '?', None, None)] > >>> import psyco > >>> inspect.stack() > Traceback (most recent call last): > File "", line 1, in ? > File "/tmp/python.4228/usr/lib/python2.3/inspect.py", line 795, in stack > return getouterframes(sys._getframe(1), context) > File "/tmp/python.4228/usr/lib/python2.3/inspect.py", line 776, in > getouterframes > framelist.append((frame,) + getframeinfo(frame, context)) > File "/tmp/python.4228/usr/lib/python2.3/inspect.py", line 744, in > getframeinfo > raise TypeError('arg is not a frame or traceback object') > TypeError: arg is not a frame or traceback object Mentioning this on the psyco-devel list has a rather higher probability of attracting a useful response... I'm not sure there's anything that can really be done in this situation, though, except making inspect less anal. Cheers, mwh -- You have run into the classic Dmachine problem: your machine has become occupied by a malevolent spirit. Replacing hardware or software will not fix this - you need an exorcist. -- Tim Bradshaw, comp.lang.lisp From squirrel at WPI.EDU Wed Jun 30 16:29:23 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 30 Jun 2004 16:29:23 -0400 Subject: zip asterisk syntax In-Reply-To: References: Message-ID: garett wrote: > Hello, I have been reading text processing in python and in the appendix > the author describes: > >>> sides = [(3, 4), (7, 11), (35, 8)] > >>> zip(*zip(*sides)) > > what is this asterisk-list syntax called? Any suggestions for finding more > information about it? Thanks. -Garett It's called the "extended function call" syntax. Basically what it does is take the items of a list and use them as arguments to a function. Let's take the example above: >>> sides = [(3, 4), (7, 11), (35, 8)] >>> zip(*zip(*sides)) is the same as: >>> zip(*zip((3,4),(7,11),(35,8))) zip() mangles its arguments in such a way that the above call is equivalent to this: >>> zip(*[(3,7,35),(4,11,8)]) which is the same as: >>> zip((3,7,35),(4,11,8)) which evaluates to [(3,4),(7,11),(35,8)]. Back on topic, the dictionary equivalent of * is **; that is, ** takes the key-value pairs from a dictionary and uses them as arguments to a function. * and ** must appear after other arguments to the function, and you may only have at most one each of * and **. There's another context other than function calls in which * and ** can be used, and that's function definitions: >> def(a,b=5,*c,**d): pass will pack any extra arguments (beyond a and b) into list c and dictionary d. For (very) detailed information, see http://docs.python.org/ref/calls.html and http://docs.python.org/ref/function.html. From jfouhy at paradise.net.nz Mon Jun 21 19:18:14 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 21 Jun 2004 16:18:14 -0700 Subject: Tkinter, scale widget, and mouse clicks Message-ID: So I've got a horizontal scale widget in my GUI. When I click the mouse in the area to the right of the GUI, the scale advances by 1. 13 +-------------------------+ |<| [===] X |>| +-------------------------+ || \/ 14 +-------------------------+ |<| [===] |>| +-------------------------+ I want to change this, so it jumps by a larger amount (and likewise if I click to the left of the slider). Any clues? (setting 'bigincrement' only works for CTRL-left / CTRL-right when the widget has keyboard focus) -- John. From inyeol.lee at siimage.com Mon Jun 14 12:22:53 2004 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Mon, 14 Jun 2004 09:22:53 -0700 Subject: inspect: get the calling command In-Reply-To: References: Message-ID: <20040614162253.GO18163@siliconimage.com> It's an old bug. See Python bug [607092] at Sourceforge. Inyeol From danb_83 at yahoo.com Sat Jun 19 02:08:27 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jun 2004 23:08:27 -0700 Subject: Game - Map data structures References: Message-ID: Innocence wrote in message news:... > Hi > > I've been considering how to optimize map data structures for a tile > based Python game. However, since I'm a Python newbie I lack > experience with Pythons 'exotic' data types like lists and tuples, and > thus I'm unsure whether such types could solve my problem. > > My basic thought is this: If my world map consists of 80% water and > 20% land, then why reserve full data-structures for all the water > tiles? > > I'm looking for a way to do the following: > > My World Map object should likely be a standard (x,y) array of Tiles > (unless there's a better way?) > Each Tile has a boolean/one-bit value: 0 or False for Water, 1 or True > for Land. A better way is to have the class hierarchy like class Tile(object): def __init__(self, ...): # data that any Tile can contain self.armies = ... ... class WaterTile(Tile): pass class LandTile(Tile): def __init__(self, ...): Tile.__init__(self, ...) # data specific to land tiles self.building = ... From rtw at freenet.co.uk Sat Jun 19 08:49:25 2004 From: rtw at freenet.co.uk (Rob Williscroft) Date: 19 Jun 2004 12:49:25 GMT Subject: mutable default parameter problem [Prothon] References: <8ef9bea6.0406180809.10053ba6@posting.google.com> Message-ID: Hung Jung Lu wrote in news:8ef9bea6.0406180809.10053ba6 at posting.google.com in comp.lang.python: > Rob Williscroft wrote: >> >> But python has static variables. >> >> def another( x ): >> y = getattr( another, 'static', 10 ) >> another.static = x >> return y >> >> print another(1), another(2), another(4) > > What about the following case: > > def f(): > f.static = getattr(f, 'static', 0) > f.static += 1 > return f.static > > print f(), f(), f() # prints 1 2 3 Yep this would be the way I would instinctivly write it. However Andrea suggested: def f(): if not hasattr( f, 'static', 0 ): f.static = 0 f.static += 1 return f.static Which my primitive timing tests show to be faster. > > As opposed to C++, you now have a line of code that is always executed > in subsequent calls, for no good reason. This is worse than: Well C++ has `if ( __compiler_generated_bool__ )` that will always be executed ( except in the case of POD's (char, int, double etc) ). > > def f(static=[0]): > static[0] += 1 > return static[0] I don't know but surely the interpreter is doing some kind of extra if/attribute lookup in there, its just faster than the other versions. I've timed both, and this was by far the fastest. I don't think the problems is the `if` though. I don't know but I suspect this version finds the local/paramiter 'static' with __slots__ like performance, all other version's suffer from attribute lookup problems. > > in the sense that you have a wasteful call ("getattr") that doesn't do > anything productive in subsequent calls. (You could change that to > f.static = getattr(f, 'static', 0) + 1, but the "getattr" is surely > inefficient compared to f.static += 1, and internally likely incurs > some conditional statement at some level.) > > Maybe one can do instead: > > def f(): > global f > def f(): > f.static += 1 > return f.static > f.static = 0 # initialization > return f() > > print f(), f(), f() # prints 1 2 3 > > The advantage is there is no more wasteful statements in subsequent > calls. No "if" conditional statement. Intresting, but it looses (in my timing tests) to the f(static=[0]) version, static[0] must be faster than f.static I guess. > The above is of course a toy > example to illustrate the case of a function that needs to perform > something special the first time it is called. (I am well aware of the > outside assignment like: > > def f(): > f.static += 1 > return f.static > f.static = 0 > > mentioned in this thread, but I am talking about something more > general. Notice that in the latter case, f.static=0 is done before f() > is called, which may not be what one wants. E.g.: if f() is never > called, this assignment is wasteful. Not a problem in this case, for > if complicated initialization is needed, like requiring a timestamp, > it may not be a good idea.) Indeed, the fast version is: _f_static = 0 def f(): global _f_static _f_static += 1 return _f_static This is directly equivalent to static int f_static = 0; int f() { return ++f_static; } C++ name hiding is with the static keyword, python name hiding is with a leading underscore. > > In code refactoring, the equivalent is to replace conditional > statements by polymorphism. In terms of codeblocks, what I mean is > dynamic hook-on and hook-off of codeblocks. If the underlying language > is powerful enough, one should be able to achieve runtime > restructuring of code, without performance impact for subsequent > calls. > Nice. static int f_static; static int f_init(); static int f_run(); int (*f)() = f_init(); static int f_init() { f_static = /* dynamic value */ 0; f = f_run; return f(); } static int f_run() { return ++f_static; } In C++ the (performance) cost is visible and only f() and its callers pay for it, in Python the the (performance) cost is invisible and everybody pays for it. In C++ I write: int f() { static int var = 0; return ++var; } And I let the compiler worry about the best way to implement it, in Python I write: class f( object ): def __init__( self ): self.var = 0; def run( self ): self.var += 1 return self.var Though in a simple case (as all the examples have been) I might write: def f(): if not hasattr( f, 'static' ): f.static = 0 f.static += 1 return f.static Clarity (my clairty of purpose, as a programmer) wins in both languages. I won't be writing: def f(static=[0]): #etc It simply isn't clear. Rob. -- http://www.victim-prime.dsl.pipex.com/ From tjreedy at udel.edu Tue Jun 8 08:22:32 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 08:22:32 -0400 Subject: Catching a traceback References: <10cae3gsob80jb2@corp.supernews.com> Message-ID: > def write( self, text ): > self.text += text With strings, += n times takes O(n**2) time, whereas n appends and join is O(n). While ok to use when one knows for sure that n will be small, this strike me as a bad pattern to post publicly, without comment, where new Pythoneers might get the wrong idea (as evidenced by some past postings ;-). For tracebacks, n is usually definitely small but the occasional n up to maybe 50 might not be considered so. Terry J. Reedy From rigga at hasnomail.com Mon Jun 28 15:10:08 2004 From: rigga at hasnomail.com (Rigga) Date: Mon, 28 Jun 2004 19:10:08 GMT Subject: Help formatting a mysql query string References: <40DD7414.6080406@holdenweb.com> Message-ID: Pierre-Fr?d?ric Caillaud wrote: > > The PHP way is awful (you have to escape your strings and > if you forget, you have a vulnerability).. > > Is you want to have dynamic fields you can do : > > cursor.execute( "INSERT INTO mytable SET %s=%s", (fieldname, value) ) > > or you could also do this : > > query = "INSERT INTO mytable SET %s=%%s" % fieldname > cursor.execute( query, (value,) ) > > The last one is preferred if > - your SQL library precompiles and reuses queries (I don't know if it > does) > - You use executemany to insert several lines. > > HOWEVER > The last variant has a security vulnerability : fieldname is not quoted. > > Solution : > On entering your script, test : > if fieldname not in ('field1', 'field2'): > raise ValueError, "Invalid field name" > > >> Thanks for the help, sorry I posted this twice, my news reader was not >> showing the original post so i resubmitted it. I normally work with php >> thats why I was trying to build it as a string. I now see how I can load >> the data values from my variables, however is the same possible for the >> fields? I know you say its best to specify the column names etc however >> my >> script is parsing a web page and getting the field headings (which will >> stay the same), data and table name so I wanted to make the script handle >> all this rather than having to have a seperate cursor.execute() for each >> table I want to update - does this make sense? >> >> Regards >> >> Rigga Thank you for explaining this so clearly it helps me a great deal. All the best R From benn at cenix-bioscience.com Tue Jun 29 03:47:10 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 29 Jun 2004 09:47:10 +0200 Subject: What is the meaning of static and class methods ? Message-ID: <40E11E7E.5090903@cenix-bioscience.com> Michele Simionato wrote: > "fowlertrainer at anonym.hu" wrote in message > news:... > > >> >> I want to anyone please send an example of class/static methods that >> HAVE MEANING. >> A real example, to I understand, why we need that methods in python. >> >> Thanx for it: >> FT >> > > > I may sound heretic, but I never thought their introduction as builtins > was a particularly clever idea. Python lived pretty well without them > for years and could continue living without them. > > Hello, While I agree that they are syntatic sugar, I believe that they make the design clearer and simpler. Suppose I design an abstract class of which there are several subclasses which provide concrete implementation. I can have a method is the abstract class such as getImplementation(self, pstrImplementationName), this method can then return the concrete implementation as asked for - a basic design pattern. Although it is true that I could put this in module that holds the class, the question you should really ask yourself is - does it _belong_ there. In my opinion, it does not - it is a method which belongs to the abstract class not the enclosing module which doesn't know . The next question is, why not make an abstract instance and use that - this I think is wrong for two reasons - one it is a waste of an object creation (although I admit this doesn't really matter, it is just ugly - I am not a fan of doing something like dir("") to get the interface of str, you should use dir(str)). The other reason is that it is an abstract class - not designed to be instantiated. However, I do get the point that this is just syntatical sugar but it does make much more sense to me when both I'm doing my UML diagrams and in my head. One word of caution though, this is the first language I've just which is not purely based on classes (such as Java, Eiffel and C#) - so I'm coming from an OO point of view and not a Python-specific point of view. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From mwh at python.net Fri Jun 18 06:18:06 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jun 2004 10:18:06 GMT Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> Message-ID: David MacQuigg writes: > On Thu, 17 Jun 2004 11:05:58 GMT, Michael Hudson > wrote: > > >michele.simionato at poste.it (Michele Simionato) writes: > > > >> David MacQuigg wrote in message news:... > >> > I have what looks like a bug trying to generate new style classes with > >> > a factory function. > >> > > >> > class Animal(object): pass > >> > class Mammal(Animal): pass > >> > > >> > def newAnimal(bases=(Animal,), dict={}): > >> > class C(object): pass > >> > C.__bases__ = bases > >> > dict['_count'] = 0 > >> > C.__dict__ = dict > >> > return C > >> > > >> > Canine = newAnimal((Mammal,)) > >> > TypeError: __bases__ assignment: 'Mammal' deallocator differs from > >> > 'object' > >> > > >> > If I remove the 'object' from the class C(object) statement, then I > >> > get a different, equally puzzling error message: > >> > > >> > TypeError: __bases__ items must be classes > >> > > >> > The function works only if I remove 'object' from all base classes. > >> > > >> > -- Dave > >> > >> This is not a bug. The developers removed the possibility to change > >> the bases of a new-style class. > > > >Bad news for you: I put it back in for 2.3. > > > >If you read the error message, you'll notice that it's phrased to > >suggest that assignment to __bases__ is *sometimes* possible :-) > > > >David's assignment probably should work -- there's a bug on sf about > >this -- but there are definitely situations where assignment to bases > >*shouldn't* be allowed -- e.g. when the so-called 'solid base' changes > >-- but noone's put in the thinking time to make this precise in code. > >Being over-restrictive seems the better course. > > This may be just a documentation problem then. The error message is > definitely misleading. Well, possibly. It's generally assumed that you know what you're doing if you want to muck with things on this level. Clarifying patches welcome :-) > >However, newAnimal could be written like this: > > > >def newAnimal(bases=(Animal,), ns=None): > > if ns is None: > > ns = {} > > ns['_count'] = 0 > > return type('C', bases, ns) > > > >which > > > >a) doesn't use the name of a builtin as a variable > >b) doesn't suffer the 'mutable default arguments' problem > >c) is rather less insane > >d) actually works :-) (probably, haven't tested it) > > It works great. The only thing I would change is the return line, > making that > > globals()[name] = type('C', bases, ns) Ugh! > so we don't have to type the name twice when creating a new class. > I've also added an __init__ function. Using the factory is now very > easy: > > >>> newAnimal('Dog',(Mammal,)) > >>> dog1 = Dog() > Hello from __init__ in Dog > >>> Dog._count > 1 > > The main limitation I see in using a factory function like this, > instead of a metaclass, ^^^^^^^^^^^^^^^^^^^^^^ What a what? I _really_ don't think you mean metaclass here. > is that I can't customize the new animal as easily, because I don't > have an indented block like in a class definition. I've got to call > the newAnimal function, then add a bunch of attributes one at a > time, with fully-qualified names. > > Dog.temperature = 102 > Dog.pulse = 82 > Dog.respiration = 36 Well, there are ways around that, too, eg: def newAnimal(bases=(Animal,), **kw): kw['_count'] = 0 return type('C', bases, kw) Dog = newAnimal('Dog', (Mammal,), temperature=102, respiration=36) > If I'm adding methods, it gets even messier, because I've got to > define functions at the module level, then assign them to attributes > of Dog, then maybe delete all the excess names from the module > namespace. Well, not necessarily. Use the third parameter to the call to type(). > I have one last question. In reviewing all the ways to solve the > problem of creating specialized classes, I see there is a function > new.classobj(name, bases, dict) which appears to do the same thing as > type(name, bases, dict). new.classobj() is a holdover from the days of old-style classes, though I see it creates new-style classes if passed new-style bases... > What is the purpose of classobj()? The name is a little more > self-explanatory than 'type', but using it requires a module import. Historical cruft, more-or-less. Cheers, mwh -- ARTHUR: Why should a rock hum? FORD: Maybe it feels good about being a rock. -- The Hitch-Hikers Guide to the Galaxy, Episode 8 From dwelch91 at comcast.net Sat Jun 5 12:33:12 2004 From: dwelch91 at comcast.net (djw) Date: Sat, 05 Jun 2004 16:33:12 GMT Subject: write a bitmap using python In-Reply-To: References: Message-ID: lyuan wrote: > Hi, > How can I write a bitmap using python? I have some integer data and > want to generate a bitmap graph for visualization. Any suggestion will > be appreciated. > Sorry if this is an FAQ, BTW, where can I find the FAQ of this list? > > thanks > Lihua If you application involves a UI like Qt/PyQt, then there are ample classes to perform this operation (QPixmap, QImage, etc). Otherwise, look at PIL. -D From fperez528 at yahoo.com Sat Jun 12 10:35:32 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 12 Jun 2004 08:35:32 -0600 Subject: Newbie array question References: <2d7af4f8.0406112032.4cb4438a@posting.google.com> Message-ID: Neale wrote: > My first task with Python is to scan multiple small text files and > "batch together" those records with a "5" or "6" in column 2, and then > save as a new file. The records are 256 characters. I know it sounds > like a homework problem, but it's not. > > My math brain wants to dump all the records into a big 2-D array and > sort on the second column. Then "compress out" all the records whose > second character isn't "5" or "6". Easy to say. > > Is this the right strategy for using Python? Does it even have a > "compress out" function? There's obviously a million ways to do this, but I (math person also) would do it with Numeric (http://www.pfdubois.com/numpy). It will efficiently do the filtering, and if you are interested in numerical work in python, you might as well get started with the proper tool right away. If you are not interested in numerical libraries for the future, then Numeric may be overkill and a simple line-oriented loop will do just fine. Note however that the Numeric code will likely be much faster for large datasets (assuming you don't start swapping) as all loops are done internally by fast C code. Cheers, f From jeremy+plusnews at jeremysanders.net Wed Jun 23 04:55:15 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 23 Jun 2004 09:55:15 +0100 Subject: FFT with Python References: Message-ID: On Tue, 22 Jun 2004 21:05:33 +0000, Jarek Zgoda wrote: > Satish Chimakurthi pisze: > >> Did anyone compute FFT - Fast Fourier Trans using Python ? I am >> looking for a simple Python package which can do spectral analysis for >> me. Can someone help me get such a package ? > > Numeric has it. Of course you probably want to use numarray instead, which is newer and has further development. Jeremy From dooms at info.LESS.ucl.SPAM.ac.be Sat Jun 12 07:59:02 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Sat, 12 Jun 2004 13:59:02 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: <2iui4lFr1nafU1@uni-berlin.de> References: <2is27mFqeen8U1@uni-berlin.de> <2iui4lFr1nafU1@uni-berlin.de> Message-ID: <40caf01b$0$41764$5fc3050@dreader2.news.tiscali.nl> Claudio Grondi wrote: > If I understand right all your responses > there is no way to get the decimal form > of the prime within let me say minutes? > Any other ideas how to get it similar fast > as the hexadecimal form? > If speed is the matter, go for C: with the GNU MP library use void mpz_pow_ui (mpz_t rop, mpz_t base, unsigned long int exp) and char * mpz_get_str (char *str, int base, mpz_t op) I did a small contest about the decimal repr of 2**1000000 a a couple years ago. A few languages were compared on a time-to-result basis. Python won with 7 minutes (10 sec devel, 6:50 comput.) and C + GMP was second: 15 min devel(including reading the doc) + a few sec of comput. I bet you can expect a 30-100 fold speedup using C + GMP compared to python -c 'print 2**24036583 - 1' If you try this approach I'd like to know which results you get. -- Gr?goire Dooms From jorgencederberg at hotmail.com Tue Jun 29 07:07:20 2004 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Tue, 29 Jun 2004 13:07:20 +0200 Subject: Get Rid Of Tkinter Canvas Border In-Reply-To: <78c1b378.0406290150.64d4561e@posting.google.com> References: <78c1b378.0406290150.64d4561e@posting.google.com> Message-ID: Martin wrote: > I'm using Python 2.3.3 on Win XP Pro. My program places a Canvas > object on a parent Frame. The backgound color of both is set to > 'white' and both have borderwidth set to zero. The Canvas is smaller > than the Frame it is inside of. > > For some reason there is always tiny (one pixel?) grey border drawn > around the boundaries of the Canvas object. I tried setting relief to > both SOLID and FLAT on the Canvas object, but that does not get rid of > the thin grey border. > > I suspect this is a bug, but even so, anybody know of a workaround? > Surely I'm not the first preson to encounter this issue. I found one > old newsgroup reference cica March 2001, but there was only one > message and no one responded... > set highlightthickness to 0 (zero) Tkinter resources: http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html http://www.pythonware.com/library/tkinter/introduction/index.htm Regards Jorgen From ab_som at vsnl.net Tue Jun 15 07:08:44 2004 From: ab_som at vsnl.net (Abhijit Soman) Date: Tue, 15 Jun 2004 16:38:44 +0530 Subject: Curses module on windows Message-ID: <2j82q8FujmukU1@uni-berlin.de> Where can i find curses module for windows? I have pdcurses library on windows. But python binary doesnot include curses module. Thanks, Abhijit From alex-news-deleteme at comcast.net Tue Jun 29 14:34:47 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 29 Jun 2004 18:34:47 GMT Subject: embedded python? References: Message-ID: > You can't necessarily have confidence in someone else's build either, > unless it's very widely used, and used in the same way yours will be > used. Otherwise you are likely to use functionality that others do > not, and you may still encounter problems. Good point. > > An unexplored suggestion was to use Jython and target an embedded chip > > designed to accelerate Java bytecode. I know little about Jython or Java > > chips, so I can't yet make any sense of this idea. > > My only comment on that is that mixing many different technologies > together will increase the complexity exponentially. I'd try to > avoid it, at the least for the prototype. Note also that I'm a very I wasn't terribly fond of it either and had not invested any time exploring it. Still I was curious on this newsgroups experience. >Note also that I'm a very > YAGNI(*) sort now I'm just the lazy sort, which seems to lead to the same result. Thanks again, Alex "Peter Hansen" wrote in message news:ju6dnXqsIr6lL3zdRVn-hQ at powergate.ca... > Alexander May wrote: > > > One of my concerns is the lack of confidence I'd have in the build. Any > > hard to diagnose error that arose could potentially be a logic error or an > > interpreter bug (or a hardware bug). On a six thousand node distributed > > system, I want to be quite sure of the foundation, and minimize possible > > sources of error. I've never compiled python before. Is the test suite > > comprehensive enough to justify a high level of confidence in a new build? > > You can't necessarily have confidence in someone else's build either, > unless it's very widely used, and used in the same way yours will be > used. Otherwise you are likely to use functionality that others do > not, and you may still encounter problems. > > The test suite is extensive. Personally, I would have pretty high > confidence in any working port, after some basic testing with sample > code that reflects the sort of thing my application needs to do. > > I am, however, pretty used to tracking down compiler bugs and such, > so I'm a little blase about that sort of thing. > > > An unexplored suggestion was to use Jython and target an embedded chip > > designed to accelerate Java bytecode. I know little about Jython or Java > > chips, so I can't yet make any sense of this idea. > > My only comment on that is that mixing many different technologies > together will increase the complexity exponentially. I'd try to > avoid it, at the least for the prototype. Note also that I'm a very > YAGNI(*) sort now, what with Extreme Programming ideas having seeped > into my head so far. I tend to believe I'll find ways around any > issues that arise, and generally do... > > -Peter From fowlertrainer at anonym.hu Wed Jun 23 05:28:03 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Wed, 23 Jun 2004 11:28:03 +0200 Subject: How to do special encode in string ? Message-ID: <40D94D23.6070900@anonym.hu> Hi ! I'm hungarian, we use special characters like: ? - a' ? -o" etc. I want to encode this characters to in config file I see these characters as \nnn format. And I want to decode it automatically with python. How to I do it without write complex converter tool ? Thanx for it: FT Example: Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" From fishboy at redpeanut.com Wed Jun 9 20:03:15 2004 From: fishboy at redpeanut.com (David Fisher) Date: Thu, 10 Jun 2004 00:03:15 GMT Subject: My simple script parse output screen and to a new file! References: Message-ID: <84k6ygmg30.fsf@redpeanut.com> chuck amadi writes: > fp = open("/home/chuck/pythonScript/testbox") > mbox = mailbox.UnixMailbox(fp, email.message_from_file) > for mail in mbox: > print mail['Subject'] > print mail.get_content_type()#text/plain > print mail.get_payload() If your going to use the UnixMailbox in two different loops, you'll need to reinitalize it. Just call: fp = open("/home/chuck/pythonScript/testbox") mbox = mailbox.UnixMailbox(fp, email.message_from_file) again before you use 'mbox' again. Otherwise the file pointer is still pointing at the end of the file which is why you get nothing the second time. Or alternately, just to be more confusing :), use: for mail in mailbox.UnixMailbox(open("/home/chuck/pythonScript/testbox"), \ email.message_from_file): print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() Which does it all in one stroke. Oh, minor nitpick. open(filename) is depredicated I believe. The new prefered (for now :P) usage is file(filename). Which makes sense since it returns a file object not an 'open' object ><{{{*> From ripolles at LALALAaditel.org Sun Jun 13 20:05:28 2004 From: ripolles at LALALAaditel.org (Eru) Date: Mon, 14 Jun 2004 00:05:28 +0000 (UTC) Subject: Finding "hidden" syntax errors References: Message-ID: eltronic at juno.com escribio: > > On Fri, 11 Jun 2004 13:03:38 -0500 "Larry Bates writes: >> It doesn't happen often, but once in a while I will >> introduce a syntax error into a Python program I'm >> working on (in IDLE) and doing File-Check responds >> with the expected "Failed to check, syntax error - >> invalid syntax". The problem is where the cursor >> stops is perfectly legal syntax. I then begin >> going through the laborious job of cutting out >> pieces of the code until I find what is wrong. > > [ some advice about error checking -- snipped ] Another problem that arises from time to time which produces the effect described by the OP is an "unclosed parens", that is, a parens that was open and never closed (or a square bracket). As Python considers an unclosed parens as an implicit continuation of the statement in the following line, the error is often "detected" in some place PAST the actual error. Something similar happens with "unclosed strings", but any editor with a decent syntax highlighting makes you notice this almost instantly. My advice is to explore your editor and learn if there is some way to get "help" with your parents. Emacs does this veri well AFAIK, and in Vim you can :set showmatch to get Vim show you some highlights about parens; you can also press % when you are on a parens to move to the corresponding (opening/closing) one. My .02 :) -- Daniel Ripolles ( Eru ) Make Source, Not War for(0..pop){for($c=$_%2;$_>>=1;){$c=$_%2 .$c}print"$c\n"} From http Wed Jun 23 12:32:32 2004 From: http (Paul Rubin) Date: 23 Jun 2004 09:32:32 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> <7x7jty7rk1.fsf@ruckus.brouhaha.com> Message-ID: <7xbrja5j6n.fsf@ruckus.brouhaha.com> Peter Hansen writes: > Both are good ideas, but I made an assumption that I was starting > with a simple 22MB string, and the cost of converting that to 32-bit > (presumably using array.array still?) would have to be taken into > account, for fairness. I also assume Kamilche wasn't talking > about using the builtin rot13, since he claimed to have written > this himself... There's no special conversion needed, just use array.array('L', whatever) instead of array.array('B', whatever), if I remember right. From tim at lesher.ws Thu Jun 24 10:56:27 2004 From: tim at lesher.ws (Tim Lesher) Date: 24 Jun 2004 07:56:27 -0700 Subject: How do I run routines where timing is critical? References: Message-ID: "S. David Rose" wrote in message news:... > But, what I'd like to do is have a loop > which does not need to 'sleep' but can rather evaluate where I am in the > second and then have that logic trigger the event. Sounds like you're writing your own scheduler. You might want to look into the 'sched' module. -- Tim Lesher tim at lesher.ws From grante at visi.com Wed Jun 16 09:58:44 2004 From: grante at visi.com (Grant Edwards) Date: 16 Jun 2004 13:58:44 GMT Subject: how to become a really good Python programmer? References: Message-ID: On 2004-06-16, Miki Tebeka wrote: > Apart from other recommendations you'll get I suggest you > learn other programming languages. This will enable you to > view problems in a different light. > > I recommend at least one lisp dialect (scheme is perfect for > learning) and one prolog dialects. Both have free interpreters > available (I recommend mzscheme and SWI prolog). Have a look at Smalltalk as well if you've got the time. It's close enough to Python to be comfortable, but different enough to provide some insights. -- Grant Edwards grante Yow! Now KEN and BARBIE at are PERMANENTLY ADDICTED to visi.com MIND-ALTERING DRUGS... From tzot at sil-tec.gr Tue Jun 1 10:25:44 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 01 Jun 2004 17:25:44 +0300 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: On Tue, 1 Jun 2004 13:30:10 +0100, rumours say that "Richard Brodie" might have written: >"A.M. Kuchling" wrote in message news:a8udncumWbla7iHdRVn-uw at speakeasy.net... >> Timo Virkkala wrote: >> > When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! >> I suspect the letters are simply random. The usual way to complete the >> sentence would be "only outlaws will have cryptography", but that doesn't >> match the word lengths. >There is also a lot of keyboard locality: adjacent letters, nothing from the >bottom row, etc. Yes, that is the most obvious hint: it's the author's cat walking on the keyboard and wailing after the PSU killed the ori From anthony at interlink.com.au Mon Jun 21 12:55:38 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 22 Jun 2004 02:55:38 +1000 Subject: PyQT, automatically creating GUI for configuration options In-Reply-To: <40d2e3de@news.mt.net.mk> References: <40d2e3de@news.mt.net.mk> Message-ID: <40D7130A.7080708@interlink.com.au> ?????? ??????????? wrote: > Hi, > I'm making a small PyQT app, and it will also have a config file (any type > is ok) for several options. > > I would also like to add a gui for changing the config options but I don't > want to make design the GUI. I'd be satisfied if the GUI is automatically > generated from the config file (or config file specification). > > Is there some sollution for this? Shtoom (shtoom.divmod.org) has code that does exactly this, for Qt and Tk so far - I hope to have a Gtk version in the not-too-distant future. It also uses the same code to handle ConfigParser .ini files and command line arguments. -- Anthony Baxter It's never too late to have a happy childhood. From rschroev_nospam_ml at fastmail.fm Sun Jun 6 09:23:46 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 06 Jun 2004 13:23:46 GMT Subject: debug print shortcut? In-Reply-To: References: Message-ID: John Mudd wrote: > When debugging python, I add print statements such as these. > > print 'i=%s' % `i` > print 'foo()=%s' % `foo()` > print 'a,b,c=%s' % `a,b,c` > > I just want to dump the value of a variable or expression. But I > don't like having to type the expression twice, everytime. I can > solve this in 'C' with a preprocessor macro. Can it be solved in > python? def printdebug(s): print '%s = %s' % (s, `eval(s)`) -- "Codito ergo sum" Roel Schroeven From donn at u.washington.edu Tue Jun 29 14:59:58 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 29 Jun 2004 11:59:58 -0700 Subject: poplib for multihomed machines References: <9418be08.0406280751.6cc50097@posting.google.com> <9418be08.0406291005.34d4277b@posting.google.com> Message-ID: In article <9418be08.0406291005.34d4277b at posting.google.com>, elbertlev at hotmail.com (Elbert Lev) wrote: > Donn Cave wrote in message > news:... > > In article <9418be08.0406280751.6cc50097 at posting.google.com>, > > elbertlev at hotmail.com (Elbert Lev) wrote: ... > > > The problem with POP3 class is: it connects during __init__ and it is > > > "hard coded". I do not see any way to change this behavior with no > > > rewrite of POP3 class. > > > > > > Do you? > > > > Well, no. It should probably use an open() method like imaplib's. > > > > Donn Cave, donn at u.washington.edu > > > This is a major design error. NO-NO is C++. Constructor is supposed > only initialise members and take no actions. Unfortunatelly this > paradigm is violated in many Python classes. Well, C++ is NO-NO for sure, but for the rest I think in the Python world it's better to stick to what works and what doesn't. The standard core library classes often seem to me to be designed in fairly conscious recognition of the fact that they're lightweight. If you need to make minor, or major, changes to support your application, I think that happens fairly often, and it isn't a big problem. If a new release of poplib introduces a feature you want, it's easy to copy it into your version. I know that sounds awful, but we're software engineers, right? Not theoreticians, not priests of some software cult. We should know the difference between a real problem and a theoretical problem. The whole thing is only 335 lines in 2.2. Meanwhile, for the casual application that's really served by these classes, convenience is king. You will find __init__ functions taking "actions" because that relieves the user of a need to know extra steps. If there's a practical need to decouple POP3 instantiation from the network connection, then I'm sure its author will be interested (though of course by now there will be some backwards compatibility issues.) If the practical issues can be resolved by factoring the network connection out into a separate function, then that's a practical solution, don't you think? Donn Cave, donn at u.washington.edu From elbertlev at hotmail.com Mon Jun 21 10:18:24 2004 From: elbertlev at hotmail.com (Lev Elblert) Date: 21 Jun 2004 07:18:24 -0700 Subject: shared file access in python References: <9418be08.0406180620.3e64be96@posting.google.com> Message-ID: <9418be08.0406210618.492f40d4@posting.google.com> Andrew MacIntyre wrote in message news:... > On Sat, 18 Jun 2004, Lev Elblert wrote: > > > Does Python allow to open files in shared mode like fsopen or _open > > do? If not how to make it happen? > > Assuming you're on a Win32 platform, I think the msvcrt module has what > you're looking for. The standard file object supports only the standard C > library file stream API. Thanks all! 1. os.open flags parameter tells creation disposition (read-only, executable(unix)) etc, not shared. 2. msvcrt.lib does have a lot of functions, but not msvcrt module in Python. (correct me if I'm wrong) 3. I created and extension: /*=====================*/ #include "Python.h" #include static PyObject * Dofsopen(PyObject *self, PyObject *args) { char *FileName = NULL; char *Mode = NULL; char * Share = NULL; int ShareFlag = _SH_DENYNO; FILE *f; PyObject *FileObject; if (!PyArg_ParseTuple(args, "sss", &FileName, &Mode, &Share)) return NULL; if (strcmp(Share, "") == 0) // allow all ShareFlag = _SH_DENYNO; else if (strcmp(Share, "r") == 0) // deny read ShareFlag = _SH_DENYRD; else if (strcmp(Share, "w") == 0) // deny write ShareFlag = _SH_DENYWR; else if (strcmp(Share, "rw") == 0) // deny read/write ShareFlag = _SH_DENYRW; f = _fsopen(FileName, Mode, ShareFlag); if (!f) { PyErr_SetFromErrno(PyExc_Exception); return NULL; } FileObject = PyFile_FromFile(f, FileName, Mode, fclose); return FileObject; } static PyMethodDef fsopen_methods[] = { {"fsopen", Dofsopen, METH_VARARGS, "fsopen() doc string"}, {NULL, NULL} }; void initfsopen(void) { Py_InitModule("fsopen", fsopen_methods); } /*=====================*/ This extension returnns a Python file object or rases an exception. Also MS docs say, that fsopen is ANSI C function. I do not have access to unix machine, so can't check it. Thanks again. From paddy3118 at netscape.net Sun Jun 6 09:09:05 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Sun, 06 Jun 2004 14:09:05 +0100 Subject: debug print shortcut? In-Reply-To: References: Message-ID: John Mudd wrote: > When debugging python, I add print statements such as these. > > print 'i=%s' % `i` > print 'foo()=%s' % `foo()` > print 'a,b,c=%s' % `a,b,c` > > I just want to dump the value of a variable or expression. But I > don't like having to type the expression twice, everytime. I can > solve this in 'C' with a preprocessor macro. Can it be solved in > python? > > John I found this: >>> def dump(s, glob, loc): ... print "%s = %s\n" % (s, eval(s,glob,loc) ) ... >>> a=55 >>> dump("a",globals(),locals()) a = 55 >>> Cheers, Pad. From aweil at mail.ru Mon Jun 28 00:05:50 2004 From: aweil at mail.ru (alejandro david weil) Date: Mon, 28 Jun 2004 01:05:50 -0300 Subject: Can you make this faster? In-Reply-To: References: <889cbba0.0406271022.fd1f9ac@posting.google.com> <7x3c4gob23.fsf@ruckus.brouhaha.com> Message-ID: <200406280105.26784.aweil@mail.ru> On Sun June 27 2004 21:18, Christopher T King wrote: > If neither of the above apply to you, or give you the speedup you need, > try using the Psyco JIT compiler to compile the function. After installing > Psyco, all you need to do is to 'import psyco' and 'psyco.bind(fmtstring)' > at the top of the file your function resides in. I had never tried psyco, so I did it: Some more stats (arguments given: [ 'hola','que','tal',324,454,False] ) no psyco | psyco original code 4.664s | 2.132s modified ver 2.222s | 0.840s print 4.66 / 0.84 -> 5.54.. Not yet 7x faster :-( but 5.5 is very good i think. modified version: slen = [] for i in xrange(256): slen.append(str(i)+'s' typedic = { types.IntType: 'i', types.LongType: 'q', types.BooleanType: 'c', types.FloatType:'d'} def myfmtstring(args): global typedic, slen flen = slen ftypedic = typedic f2 = '<' st = types.StringType for arg in args: t = type(arg) if t == st: l = len(arg) if l<256: f2+=flen[l] else: f2+=str(l)+'s' else: try: f2+=ftypedic[t] except: raise Exception("Can't pack argument of type %s!" % t) return f2+'\0' Saludos, alejandro -- + There is no dark side of the moon really. Matter of fact it's all dark. From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Fri Jun 25 18:32:29 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Sat, 26 Jun 2004 00:32:29 +0200 Subject: Python Magazine exists! (was: Python intro questions) References: Message-ID: Re Ok ! Thanks by advance. Michel Claveau From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 06:46:33 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 12:46:33 +0200 Subject: string concatenation In-Reply-To: References: <2ka410F1960igU1@uni-berlin.de> <2ka7gmF18amsqU1@uni-berlin.de> Message-ID: <2kaasvF1989jnU2@uni-berlin.de> Peter Otten wrote: > Reinhold Birkenfeld wrote: > >> Maybe I'm not a real man, but the solution I like most (for code that > > Of course not, because real men never show doubt :-) > (If hard pressed, I'll admit I'm no more "real" than you in that respect) > >> extensively concatenates strings in this way) is >> >> join = lambda x: "".join(x) > > Vicious lambda - tricks you into believing that you need it. Yes, you're right. How could I... >>>> join = " ".join >>>> join(["all", "of", "us"]) > 'all of us' >>>> > > Now that's an idiom we both like, I suppose. Affirmative. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From harry.g.george at boeing.com Wed Jun 23 10:04:41 2004 From: harry.g.george at boeing.com (Harry George) Date: Wed, 23 Jun 2004 14:04:41 GMT Subject: How to call Java from Python? References: <2jrnfdF1592c4U1@uni-berlin.de> Message-ID: Steve Menard writes: > Dave Kuhlman wrote: > > Is JPE (the Python Java Extension) being used widely/actively? > > I tried to build it (with Python 2.3.4, j2se 1.4 on Debian > > GNU/Linux) and had quite a bit of trouble. And, then, the samples > > did not run. > > Is there another way to call Java code from Python? > > The JPE project does not seem too active lately, or is it? > > I need it to run in the Python environment, not the Java > > environment. I want to be able to call Java methods from Python. > > I don't believe that can be done with Jython, can it? Aren't I > > right that Jython runs in the Java environment and on Java VM? > > For example, from within the Quixote Web framework, I want to be > > able to create Java objects and call their methods. > > Thanks in advance for pointers. > > Dave > > > > Seems like my project my project got started at the right time :) > > Take a look at JPype http://jpype.sourceforge.net > > it aims to do what JPE did (but work). > > It is still early in development, and working on win32 exclusively for > now (the linux port should consist only of a few lines of code, but I > do not have a linux meachine readily available). If you have a little > C coding knowledge, you might even contribute it :) > > What's more, your's truly is doing his best to answer question and fix > problems as they arise. > > I hope this helps, > > Steve Menard > 0. Yep, a lot of us need something like this. 1. You could add a link to JPE on the JPype website. Also, it may have reusable code, idioms, patterns, etc. Broken or not, it was apparently further along than JPype when it stopped. 2. I'm willing to help, but will have to do it off-hours, at home. Specifically, the Linux (*NIX) port. 3. I get the impression that the win32-centric part is in javaenv.hpp, with its use of HINSTANCE. Anything else come to mind? 4. If there are multiple people willing to help, are you setup to project manage the effort? E.g.: a) extending the developer's guide documentation as we learn more b) regression tests c) prioritizing and coordinating work teams -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From __peter__ at web.de Mon Jun 28 06:09:33 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jun 2004 12:09:33 +0200 Subject: string concatenation References: <2ka410F1960igU1@uni-berlin.de> <2ka7gmF18amsqU1@uni-berlin.de> Message-ID: Reinhold Birkenfeld wrote: > Maybe I'm not a real man, but the solution I like most (for code that Of course not, because real men never show doubt :-) (If hard pressed, I'll admit I'm no more "real" than you in that respect) > extensively concatenates strings in this way) is > > join = lambda x: "".join(x) Vicious lambda - tricks you into believing that you need it. >>> join = " ".join >>> join(["all", "of", "us"]) 'all of us' >>> Now that's an idiom we both like, I suppose. Peter From Mike at DeleteThis.Geary.com Sat Jun 19 12:56:46 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 19 Jun 2004 09:56:46 -0700 Subject: Another MSIE Python Question References: <22b7fd40.0406190617.a33514@posting.google.com> Message-ID: <10d8s2egemjphd6@corp.supernews.com> Ralph A. Gable wrote: > I am opening MSIE6 with this code: > > ie=Dispatch('InternetExplorer.Application.1') > ie.Navigate(url) > while ie.Busy: > time.sleep(0.1) > ied=ie.Document > while ied.ReadyState != 'complete': > time.sleep(0.1) > > ieh=ied.documentElement.outerHTML > > > When opening Word or Excel, and using Dispatch('Word.Application') or > Dispatch('Excel.Application'), the app comes up and is available and can be > brought up on the screen by setting .Visible = 1. When using the above code, > IE will not come up. I have to open IE by clicking on its icon and then the > above code will work. If I don't do that I get a stack dump and my python > program crashes. My working code is similar to yours, but I use 'InternetExplorer.Application' instead of 'InternetExplorer.Application.1' in the Dispatch call. I wonder if that could make the difference. -Mike From mcfletch at rogers.com Mon Jun 28 21:42:02 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 28 Jun 2004 21:42:02 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: <20040628231429.GA9049@titan.progiciels-bpi.ca> References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> Message-ID: <40E0C8EA.20305@rogers.com> Fran?ois Pinard wrote: >[Mike C. Fletcher] > > > >>And developers; stop GPLing libraries which are essentially >>commodities. The GPL is effective when you are dealing with code >>which is so compelling and unique that it is easier to buy into >>the FSF's manifesto than to switch or write a substitute. [...] >>GPL is a PITA when working on commercial products and often forces >>reimplementation... when it's commodity code that's just entirely >>wasted effort. >> >> > >GPL is a likely PITA for whoever does not like it. If one doesn't like >the GPL, then one should be congruent enough to merely not use GPL'ed >code, instead of spending sweat and blood, trying to bend it. > Which was the thrust of my suggestion elsewhere in the message. Free not just users, but developers as well. But the implication of what you just advocated is that the community (which consists of both libre and non-libre developers) *must* develop two different versions of the software. In other words, they *must* duplicate the effort of development. >The >original plan of the GPL is to have so much good and attractive code >flying around, which is GPL'ed, than people will give in free software >instead of doing it all over again. That plan went pretty well so far. > > To some extent, sure, and for some project areas. But there are lots of cases where people look at the GPL requirements and say "no, I have to re-implement that"... it's that waste that bothers me. Particularly as a BSD-style developer of libraries, I find it annoying to have to re-implement trivial GPL libraries just to avoid infecting my users for a few hours of convenience on my part. I don't argue against GPLing KDE, GCC, or the Linux Kernel, but GPLing an ever-so-slightly-better PostgreSQL client library... I mean, really, why? Developers aren't going to look at that and decide to convert, they'll just go with one of the non-GPL-encumbered libraries and split the pool of developers in half, slowing humanity's progress by just that much in order to impose a particular philosophical position on others. This is what I mean by a "commodity" library. >Libraries are commodities, but so is a lot of non-library software. >Developers who consider that the GPL brought good software to them, may >well choose to produce some GPL code in return, in so contributing to >the critical mass. You invite people to stop GPLing libraries because >it annoys those who do not like the GPL. I would rather read this as a >practical proof that the GPL serves its purpose: if people against the >GPL were not a bit bitten by it, the GPL would be useless. > > My concern is the waste of effort. The simple fact is that there are groups doing proprietary software. For them the GPL simply isn't a choice. Instead of getting their contributions added to an existing library, they must develop their own library. LGPL (or BSD/MIT), on the other hand, allows everyone to use the same code base, contributing and extending it. It avoids the fragmentation and waste. The FSF's original strategy with the GPL assumes that the library is of such value that it is reasonable to go the FSF way rather than re-implement. When the libraries are basically trivial, they don't even begin to surmount the barrier to entry, so all you're doing is forcing pointless fragmentation. The LGPL was developed precisely because there are lots of situations where that assumption just isn't true, and it's more valuable to get the contributions of everyone to the library than to force the bifurcation of libraries. If the FSF, which represents the most extreme view of the situation is having to admit that there is a need for such a license I'd submit that there's a pretty good argument for those not occupying the ideological extreme to seriously consider the argument for every library they develop. As for the idea that the goodwill engendered by GPL software will make others want to GPL their code, the same argument holds for BSD and/or MIT, no? I'd argue that it applies to an even greater extent, because the BSD/MIT software tends to treat the end-developer as an adult, rather than a recalcitrant child. >Sometimes, people want the butter and the money of the butter (from a >French idiom: "Le beurre et l'argent du beurre"). They want everything >without giving anything back. The GPL is there to remind people that >the overall game is a give-and-take. It is something useful. > > If you like it, feel free to continue liking it ;) . As I mentioned, I prefer the BSD licensing scheme. And just to clarify, the GPL isn't a reminder, it's an attempt to *force* give-and-take. That's perfectly fine if that's your goal, but don't mistake it for a touchy-feely reminder :) . The question is whether you feel the need to impose your desires, or whether you rely on people's better nature. >P.S. - Please do not read me as saying that the GPL is the only path to >free software, there are other good free software licenses too. But the >GPL is not "wrong", and developers are not "bad" because they choose it. > > Oh, come on, it's much more fun if we sling about huge generalisations and moral characterisations. I'll start the ball rolling: The GPL represents an attempt to enforce maturity on others, while the Python, BSD and MIT licenses assume the maturity of the audience. Whether there is a moral superiority depends on whether you consider the proper way to improve society to be exemplary conduct and education or the external imposition of law (more basically, are people generally "good" or "evil"). It would seem that the more "Zen" (and I use the term loosely) approach of living a good life, and giving your gifts to the world without attempting to impose your will on another is the path taken by the Python developers, but there are others, such as the Free Software Foundation who have chosen more of a bondage and discipline approach to improving society. The underlying philosophical question is one which every human must decide for themselves, so there is, perhaps no final solution to the question. That won't stop me from advocating my position, however ;) . And that, I think, is where I will stop, as we're obviously a good little way from discussing Python any more, and this debate really can't reach any sort of conclusion. Have fun, and peace out, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From peter at engcorp.com Fri Jun 18 21:31:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:31:30 -0400 Subject: How to extract complete file path from traceback info In-Reply-To: References: Message-ID: <9Y-dncEm9oTpCk7d4p2dnA@powergate.ca> Kenneth McDonald wrote: > I have a need to customize the output of Python error tracebacks, > and to that end I've implemented my own sys.excepthook function. > However, one remaining problem that I'm having is the information > passed to this function doesn't seem to have the _full_ path name > of the file in which the exception occurred. I need this because > the output is being parsed by an editor (jEdit) which uses this > information to set up links to errors origins in the source > code. > > Is there an easy way to get this info somehow? (I haven't been > able to find it.) I can think of some 'solutions' I'd prefer > not to attempt unless I have to. Searching the source for the traceback module, I saw that it calls code in the linecache module which apparently has to do a manual search down the sys.path to find the files that are imported... that probably means (a) there is no other way to do it, (b) there's example code for you in linecache.py, and (c) it might have some troubles with the new zip-file based imports etc... (not that that would be a particular problem in your case, but it could confuse things). -Peter From heikowu at ceosg.de Fri Jun 4 06:27:43 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Fri, 4 Jun 2004 12:27:43 +0200 Subject: Python reference In-Reply-To: <2ib02kFljftcU1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2ib02kFljftcU1@uni-berlin.de> Message-ID: <200406041227.43427.heikowu@ceosg.de> Am Freitag, 4. Juni 2004 12:09 schrieb Reiner Block: > Of course I did but if I right remember e.g. DosExec, WinExec and WinExecN > (I hope I remember the functions names in a right way ;-) ) don't needed > the process name a second time, isn't it? I've never done any Windows programming so far (under DOS, using TC++ 3.0 exec() took the program name as first parameter, I'm pretty sure of that...), so I don't know... ;) > But first I've to see how to get eric3 again running. Because I installed > the current snapshot but it has a problem inside the DebugClientBase.py and > DebugBase.py. There are many changes in comparision to version 3.4.2. And > 3.4.2 crashes wenn I called Run the script. :-( Hmm... Why not work with emacs? I actually like the emacs Python mode. It's pretty sophisticated, and does all I need to program in Python. I've yet to see eric (it's installed, but I've never used it), but I've never felt the need for more than the Python-mode of emacs. Heiko. From heikowu at ceosg.de Mon Jun 14 14:10:43 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 14 Jun 2004 20:10:43 +0200 Subject: [slightly OT] German Python Workshops on IRC Message-ID: <200406142010.43568.heikowu@ceosg.de> Hi all! Me and a couple of IRC-addicts have decided to hold regular Python-Workshops on IRC, especially oriented towards beginners and intermediate programmers, who have not used Python before, or are just beginning to pick up Python. These workshops will be held in #python.de on irc.freenode.net, and as the channel name suggests, will be held in german. Why I'm posting here is simply the fact that I thought that some people might be interested, regardless of the language, and regardless of the workshops to get to know that there is a german Python channel on IRC, which is currently frequented by about 10-15 people, some of them complete beginners, others quite advanced. This channel is advertised on python.org, but in such a far away corner, that I'd have never found it, had I not seen it on the channel list of freenode. If you're interested, anyhow, come by and join us in discussing about Python, and anything else that might arise. The next workshop will be: Date: 16th of June, 2004 (this week Wednesday) Time: 8pm CEST (20:00 german time) Topic: Python und Objekt-Orientierte Programmierung f?r Einsteiger Heiko. From peter.maas at mplusr.de Wed Jun 2 07:58:22 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 02 Jun 2004 13:58:22 +0200 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: David Fraser schrieb: >> Did you find these alternatives unsatisfactory? If somebody wants >> to use a Python templating framework why should he prefer >> HTMLTemplate? [..] > It looks cool because it doesn't embed Python code in the template. > Do any of the other frameworks have this approach? That's your personal taste. If this is what you like about HTMLTemplate that's fine. I don't bother wether a template language contains Python code or not. To answer your question: Hamish's example rewritten in TAL (TAL lines below Hamish's equivalents): TITLE ###TAL TITLE But I wanted to read Hamish's thoughts. That would be helpful for programmers because it takes some time to find your way through the maze of Python template languages. I prefer Cheetah. Hamish's example in Cheetah: $title Advantages: - No magic - placeholders occupy the places of their replacements - logic is visible in the template -> you see what's going on - logic is visible in the rendered html page -> you see where the replacements will go - Cheetah templates everything, not only markup Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From eurleif at ecritters.biz Wed Jun 23 21:08:43 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 23 Jun 2004 21:08:43 -0400 Subject: Efficiency of str.replace? Message-ID: <2junsqF15s54eU1@uni-berlin.de> For my web-based application, I need to make twelve different calls to str.replace for the content of /every/ page on /every/ page view (or find a harder to implement and probably less elegant solution). Would that be a major performance hit? From db3l at fitlinxx.com Wed Jun 16 20:24:47 2004 From: db3l at fitlinxx.com (David Bolen) Date: 16 Jun 2004 20:24:47 -0400 Subject: mutable default parameter problem [Prothon] References: Message-ID: Andrea Griffini writes: > But if there are those better-looking statics, why so > much use of that modifiable-default-of-a-fake-parameter > ugly trick ? Is this something that became legal > only recently ? Function attributes were in fact somewhat recently added (as of Python 2.1, so circa April of 2001). -- David From __peter__ at web.de Thu Jun 17 14:55:35 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 20:55:35 +0200 Subject: How to make an immutable instance References: Message-ID: Batista, Facundo wrote: > I'm working on Decimal, and one of the PEP requests is Decimal to be > immutable. > > The closer I got to that is (in short): > > class C(object): > > __slots__ = ('__x',) > > def __init__(self, value): > self.__x = value > > def getx(self): > return self.__x > > x = property(getx) > The problem is that you actually could, if you take the effort, to rebind > the __x name. > > So, if you use this "immutable" class in a dict, and then you (on purpose) > modify it, you'll have different hashes. I don't think this will be a problem in practice. If you are determined, there are easier ways to break your program :-) > Said that, how safer is this approach? Is there a better way? An alternative would be to subclass tuple: >>> class C(tuple): ... def __new__(cls, x): ... return tuple.__new__(cls, (x,)) ... x = property(lambda self: self[0]) ... >>> c = C(1) >>> c.x 1 Not necessarily better, as >>> isinstance(c, tuple) True and a Decimal pretending to be a sequence type may cause greater inconveniences than the "weak immutability" you currently have. > Thank you all! Thank you for your work to further improve Python. Peter From martin at v.loewis.de Sun Jun 13 14:48:06 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 20:48:06 +0200 Subject: does python have useless destructors? In-Reply-To: <873c4z47sb.fsf@pobox.com> References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <873c4z47sb.fsf@pobox.com> Message-ID: <40cca166$0$27020$9b622d9e@news.freenet.de> John J. Lee wrote: > If you have a file open for writing when the process exits, the data > you've .write()ten isn't necessarily guaranteed to actually get > written to disk. (Apparently, whether it does or not depends on the > OS) > > So, if an exception occurs after the first .write(), and there's no > finally: there to .close() your file, you might unexpectedly lose the > data that's already been written. That is not true: the data is not lost. The file is closed eventually (e.g. when Python exits), in which case the data is flushed to disk. Regards, Martin From tim.peters at gmail.com Thu Jun 17 23:31:52 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 17 Jun 2004 23:31:52 -0400 Subject: How to make an immutable instance In-Reply-To: References: Message-ID: <1f7befae04061720312f342ba5@mail.gmail.com> [Batista, Facundo] > I'm working on Decimal, and one of the PEP requests is Decimal to be > immutable. I wouldn't worry about this. The most important thing about immutability is that we promise the *implementation* of Decimal won't mutate a user-visible Decimal object. There's no way to prevent a determined idiot from mutating one themself in Python, and trying anyway leads to slower, bigger, uglier, more obscure code. When/if Decimal is recoded in C, it will be easy to make it "truly immutable". If you think you have to try in Python anyway, then yes, read-only properties are the intended way to get an idiot-resistant approximation to immutability. It should be enough (IMO) to give Decimal data members names with a single leading underscore. That's fair warning that users aren't supposed to muck with them. I've lived to regret it every time I've given a data member a "private name" (two leading underscores) -- that's no better at truly stopping determined users from cheating anyway, and has invariably created problems over time when refactoring code. From francesco.banconi at tin.it Sat Jun 5 09:14:56 2004 From: francesco.banconi at tin.it (Francesco Banconi) Date: Sat, 05 Jun 2004 13:14:56 GMT Subject: [OT] Preventivo per un software References: Message-ID: Alle 12:17, sabato 5 giugno 2004, Francesco Banconi ha scritto: Sorry, i've made a mistake with adresses... -- Francesco From alloydflanagan at comcast.net Tue Jun 8 16:54:38 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 8 Jun 2004 13:54:38 -0700 Subject: Using ConfigParse References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > I looked it up in the source: the read() method expects a filename or a > sequence of filenames. Incidentally that means, that every line in your > config-file is interpreted as a filename. It doesn't matter that none of > these files exist, as all IOErrors are silenced by the method. > I too looked at the source. I understand why it ignores IOErrors (though I'm not convinced it's a good idea), but I think I see a problem with the ConfigParse module. I would think it should raise some error if it can't find any file at all in the list you provide. It seems to me that would be more useful than having an empty object. Of course, it's probably not something we could change now... From edcjones at erols.com Sat Jun 19 11:01:28 2004 From: edcjones at erols.com (Edward C. Jones) Date: Sat, 19 Jun 2004 11:01:28 -0400 Subject: str() for containers In-Reply-To: <10d8d4696tjkf1b@news.supernews.com> References: <40d07ac6@rutgers.edu> <10d8d4696tjkf1b@news.supernews.com> Message-ID: <40d45691$0$3030$61fed72c@news.rcn.com> John Roth wrote: > "George Sakkis" wrote in message >>I find the string representation behaviour of builtin containers >>(tuples,lists,dicts) unintuitive in that they don't call recursively str() >>on their contents (e.g. as in Java) : > The only clean solution I can see is to provide a third built-in > that provides the "right" output when a container class needs > to turn an object into a string. However, someone else > is going to have to do the work of writing up the use > cases and the PEP - I don't care enough. For str of a container, I suggest using repr for strings in the container and str for everything else. From Rigga at hasnomail.com Sun Jun 20 15:02:11 2004 From: Rigga at hasnomail.com (Rigga) Date: Sun, 20 Jun 2004 20:02:11 +0100 Subject: Text over multiple lines References: Message-ID: On Sun, 20 Jun 2004 17:22:53 +0000, Nelson Minar wrote: > Rigga writes: >> I am using the HTMLParser to parse a web page, part of the routine I need >> to write (I am new to Python) involves looking for a particular tag and >> once I know the start and the end of the tag then to assign all the data >> in between the tags to a variable, this is easy if the tag starts and ends >> on the same line however how would I go about doing it if its split over >> two or more lines? > > I often have variants of this problem too. The simplest way to make it > work is to read all the HTML in at once with a single call to > file.read(), and then use a regular expression. Note that you probably > don't need re.MULTILINE, although you should take a look at what it > means in the docs just to know. > > This works fine as long as you expect your files to be relatively > small (under a meg or so). Im reading the entire file in to a variable at the moment and passing it through HTMLParser. I have ran in to another problem that I am having a hard time working out, my data is in this format: 123456 Some times the data is spread over 3 lines like: Some Shady Business Group Ltd. The data I need to get is the data enclosed in quotes after the word title= and data after the > and before the Message-ID: <23891c90.0406070159.1925a39d@posting.google.com> "Eric S. Johansson" wrote in message news:... > > When I was CTO of a small startup, we used twiki to hold all of the > development documentation. It worked reasonably well until the pages became > quite large. Eventually, we all noticed that we didn't update our pages as we > should because it was too much like work. Editing a markup language inside of > a browser text area was lame. Even the CEO complained and said something we > all should have recognized: "Why can't you edit wiki pages like you were in > word". Development documentation in Word? Welcome to a world of pain! Sounds like exactly the sort of thing a CEO would want to have. (Yes, of course I'm twisting the very meaning of the words, and perhaps the CEO didn't actually want you to use Word.) > with that simple statement, I realized that wikis are fundamentally good tools > but they are hampered, horribly hampered by the user interface. I'm not entirely in agreement. Certainly, the more arcane Wiki syntaxes in use somehow make the most straightforward notes baroque, whilst hardly scaling up to the level of sophistication required to do things like tables, for example. But I'd argue that when using Wikis to store information, minimalism is crucial, duplication of information (as is common in more traditional documentation) should be avoided, and linking should be used aggressively. Consequently, I'd imagine that many "high end" presentation techniques could be avoided, although the output might not, admittedly, look that good. Still, one could always postprocess the results, offer multiple "views" of the underlying data, and so on. > the project would be figuring out how to manipulate a wiki using a WYSIWYG > infrastructure components such as abiword. The reason I suggest using abiword > as the base is that it is a reasonable, lightweight word processor that can > use plug-ins written in Python. Why not use anything which can save documents in a half-decent representation (possibly XML since the user shouldn't actually see it, but it lends itself to deconstruction) and upload the documents to the Wiki? As far as I can tell, from looking at how various moderately large public Wikis are used, the biggest problem (apart from filtering out vandalism) is keeping the structure pertinent (so-called Wiki refactoring) and up-to-date. Paul From usenet at microtonal.co.uk Mon Jun 14 04:03:19 2004 From: usenet at microtonal.co.uk (Graham Breed) Date: Mon, 14 Jun 2004 09:03:19 +0100 Subject: pycaml (was: Searching for the best scripting language, In-Reply-To: References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <1Kdzc.66931$B63.10895@doctor.cableinet.net> Ryan Paul wrote: ... > required to learn a challenging language, learn OCaml. Additionally, I > should mention that OCaml libraries can easily be integrated with python > programs via pycaml. I use OCaml instead of C to write python extensions. do you have examples? i could only get it to work the other way round. graham From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Thu Jun 17 12:13:47 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Thu, 17 Jun 2004 18:13:47 +0200 Subject: How to download a file from an HTTP server given the URL? References: Message-ID: This sample run Ok on my windows : def recupfileweb(adr, repenregistrement): data = urllib.urlopen(adr).read() list = string.split(adr,'/') nomlocal=list[-1] f = open(repenregistrement+nomlocal, "wb") f.write(data) f.close() print('Fichier '+repenregistrement+nomlocal+' t?l?charg? depuis '+adr) recupfileweb("http://ponx.org/downloads/toto.zip","c:\\rdest\\") #==> C:\rdest\toto.zip -- @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B sites : http://mclaveau.com http://bergoiata.org http://ponx.org From ptmcg at austin.rr._bogus_.com Mon Jun 28 11:55:20 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 28 Jun 2004 15:55:20 GMT Subject: Class Chaos References: Message-ID: "Maximilian Michel" wrote in message news:d0ce39b4.0406280157.166b9d76 at posting.google.com... > Hallo everyone, > > i hope someone can help me with this kind a interesting problem i have > in python 2.3: > > my code looks like this: > > class Read: > list = [] > __init__(self): > self.list.append = ***data from file*** > print(self): > print self.list > You will also find that you avoid some funny Python behavior if you avoid using built-in type names (such as list, dict, and str) for variable names. -- Paul From michele.simionato at gmail.com Wed Jun 30 00:33:43 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 29 Jun 2004 21:33:43 -0700 Subject: Python Magazine exists! (was: Python intro questions) References: <4edc17eb.0406281943.32bb2e9a@posting.google.com> <87brj2f59y.fsf@pobox.com> Message-ID: <4edc17eb.0406292033.67e27b36@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87brj2f59y.fsf at pobox.com>... > > Yeah, but *your* article was all about some horrendous meta-metaclass > nightmare, right? The poor guy's probably too scared to respond ;-) > No, no, nothing so scary ;) It is just a very gentle introduction to optparse. A topic at least 100x more useful than metaclasses, IMHO ;) BTW, I also wrote a recipe about optparse which is in the Python cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844 To prove further that I don't write about metaclasses only, here is another article of mine: http://www.linuxdevcenter.com/pub/a/linux/2004/05/06/graphviz_dot.html That's enough shameless plug for today ;) Michele Simionato From jacek.generowicz at cern.ch Tue Jun 1 03:27:41 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Jun 2004 09:27:41 +0200 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes: > Calvin Spealman wrote: > > ... > > Have to admit tho, a continue feature might be useful. Some languages have > > this, don't they? The thing is, Where exactly to continue? Should you retry > > whatever raised the exception, continue just after it, at the beginning of > > that line, or what? > > > > See this older thread: > > > Xerox's experience (in deliberately removing the "continue from > exception" language feature) I found very instructive. Funny, Common Lisp (and some of its ancestors) allows you to "fiddle things and and return as well as even return from the exception", and people who write industrial strength applications is Common Lisp repeatedly state that this feature allows them to write software which is much more robust than any they would otherwise be able to create. Some go as far as considering any language without this feature to be fundamentally flawed. I have never heard anyone identify this feature as a source of bugs. So I am tempted to conclude that the Mesa implementation was flawed ... or maybe it was just the users who were flawed. The concept itself seems to have proven its worth over time. From dieter at handshake.de Wed Jun 16 14:48:50 2004 From: dieter at handshake.de (Dieter Maurer) Date: 16 Jun 2004 20:48:50 +0200 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> Message-ID: balaji at email.arizona.edu (Balaji) writes on 14 Jun 2004 11:37:42 -0700: > ... > In our application a expression 100>=x reads as 100 is an upper bound > on x. Mathematically it is same as saying x<=100 which also bounds x > by 100. But in modelling, the user wants to preserve the order in > which he has written the expression. Python's "rich comparison" methods have been defined for comparisons and not for modelling. For any senseful definition of ">=" and "<=", "x >= y" is equivalent to "y <= x". As you seem to be interested in modeling and not in comparisons, you must use your mapping of abstract syntax to objects and can not use Python's default one. The "ast" modul contains necessary prerequisites to implement such a mapping. Recently, I found an example in Zope's "RestrictedPython". Dieter From fumanchu at amor.org Thu Jun 10 19:02:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 10 Jun 2004 16:02:21 -0700 Subject: finding the right data structure...? Message-ID: David Hoare wrote: > I have an application in VB that I was using as a sample to > 're-create' > it using python. It involved storing information about sound > and light > cues (this was for a lighting / sound theater controller). > > The data was stored like this: > - a custom 'type' called lightCue which looked like this: > > Type lightCue > > Name As String 'optional short name > > Description As String 'optional longer description > > CueLine As String 'optional line in script where cue occurs > > upTime As Single 'time for lights fading UP > > downTime As Single 'time for lights fading down > > chanLevel(0 To maxChan) As Single 'stored intensity > level (0 to 100) for each channel on the lighting console > > End Type > > I then created an array... > dim lq(1 to 200) as lightCue > ...allowing me to iterate through the list of cues for any > information I > needed > > I am struggling to come up with a similar (in function) way > to do this > in Python. Any ideas? I think I understand about classes, but then I > need to 'name' each instance of that class when they are > created, don't I? No, you don't need to name each instance. Start with a simple class like this: class LightCue(object): def __init__(self, name='', description=''): self.name = name self.description = description self.cueLine = '' self.upTime = 0.0 self.downTime = 0.0 self.chanLevel = [0.0] * maxChan ...then create a Python list of them instead of a VB array...possibly: cues = [] for name in names: newCue = LightCue(name) cues.append(newCue) ...in which case, "cues[44]" will return the appropriate LightCue. Embellish as necessary. Robert Brewer MIS Amor Ministries fumanchu at amor.org From stacycollings at yahoo.com Wed Jun 9 20:01:29 2004 From: stacycollings at yahoo.com (Stacy) Date: 9 Jun 2004 17:01:29 -0700 Subject: Newbie Copy Question References: Message-ID: Thanks for the response, Peter! Another reader helped me out, too, but I figured out what the problem was...the folders and file names are case-sensitive! Once I changed documents and settings...blah blah blah to Documents and Settings blah blah blah it worked just fine. I'm doing some computer migrations at work and I wanted to write a frozen binary to copy all the important files automatically to my jump drive for transfer to the new PC. BTW a jump drive is just a USB thumb drive that I use to copy stuff from the old computers to the new :) Thanks again, Stacy Peter Hansen wrote in message news:... > Stacy wrote: > > > I'm new to Python (about 2 weeks) and I want to use the shutil module > > to copy files from Windows XP folders to my jump drive. My problem is > > that I can't figure out how to make Python deal with the spaces in > > Windows folder and file names. I tried putting the path in quotes > > (like you do at a DOS prompt) but still no good. I searched > > python.org and can't find an answer....any ideas? > > Please post an example of the paths that aren't working. Spaces > generally work fine, but perhaps the limitation is with your > "jump drive" (what's that?) rather than with Python itself. > Another possibility is that you are using single backslashes > inside the Python strings, without realizing the effect this > has when certain characters follow the backslash... this is > because of the "escape sequences" allowed in strings to let > a programmer produce special characters such as TAB (\t) or > LF (\n). If that's the case, switching to forward slashes > should work, or learn to use raw strings as in r'path\file'. > > -Peter From tjreedy at udel.edu Tue Jun 8 18:23:52 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 18:23:52 -0400 Subject: Passing parameters using **kargs References: Message-ID: "Aahz" wrote in message news:ca50ga$hhl$1 at panix1.panix.com... > >_f_orig = f > >def f(*largs, **kargs): > > print 'f called with' largs, 'and', kargs > > f(*largs, **kargs) > > You mean > > _f_orig(*largs, **kargs) Of course. Silly 'rushing out the door' mistake. > I prefer this version: > > def debugParams(func): > def debugger(*args, **kwargs): > for arg in args: > print type(arg), arg > for name in kwargs: > value = kwargs[name] > print name, type(value), value > return func(*args, **kwargs) > return debugger > > f = debugParams(f) So do I, for its elaboration, factorization, and closure. I am saving it. Terry J. Reedy From tom at orderweb.co.za Wed Jun 30 15:07:44 2004 From: tom at orderweb.co.za (Tom) Date: 30 Jun 2004 12:07:44 -0700 Subject: Python Bounties References: Message-ID: David Fraser wrote in message news:... > Tom wrote: > > The first of its kind in South Africa > > > > Python only commercial software shop > > > > Trying to start virtual company with virtual developers and spread > > Python acceptance ;-) > > > > More info at > > > > http://orderweb.co.za/open_source_developers_bounties.htm > > Interesting, but you don't really specify much like the architecture you > intent to use, etc. Or the license ... which makes a big difference. > There have been a few projects to set up open marketplaces for open > source developers, but I couldn't find them using google ... anyone? > > I hope you post more details soon :-) > > David I'm still busy working on details From pieper at viaregio.de Fri Jun 25 06:23:58 2004 From: pieper at viaregio.de (Oliver Pieper) Date: 25 Jun 2004 03:23:58 -0700 Subject: Code: Rolling a Container Into a String References: <889cbba0.0406241742.51a2980b@posting.google.com> Message-ID: <7b9dfa94.0406250223.76d6b9d9@posting.google.com> > I want to convert a dict into string form, then back again. Since you probably don't want to do this just for the joy of converting something to string an back ... Maybe the pickle (and cPickle) module does what you are looking for. Oliver From squirrel at WPI.EDU Wed Jun 30 12:10:45 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 30 Jun 2004 12:10:45 -0400 Subject: Getting User Display Information In-Reply-To: References: Message-ID: > I was wondering if it was possible to get the screen display size and > other associated properties somehow either using python modules or if > possible using Tk methods. Using Tkinter: from Tkinter import Tk w=Tk() print w.winfo_screenwidth(),w.winfo_screenheight() w.destroy() There's a plethora of other information available as methods of the Tk object (actually any Tkinter widget), including color depth, cursor position, window manager type, etc. Note that this is actually creating a Tk window; calling its destroy() method right after you've finished with it prevents it from appearing on screen. Don't do this if you actually are creating a GUI with Tk. From me at privacy.net Mon Jun 21 06:14:57 2004 From: me at privacy.net (Duncan Booth) Date: 21 Jun 2004 10:14:57 GMT Subject: How to do special encode in string ? References: Message-ID: "fowlertrainer at anonym.hu" wrote in news:mailman.88.1087811553.454.python-list at python.org: > Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" > > Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" > >>> s = "az \xe1llam \xe9n vagyok" >>> print s.decode('latin-1') az ?llam ?n vagyok >>> You want to use unicode strings if you have characters outside the ASCII range. The decode method on a byte string will let you convert it to a unicode string, and the encode method will let you convert it back to byte string. The tricky bit is that you need to know the correct encoding to use as \xe1 could mean different characters, but in this case it looks as though you meant latin-1. From donn at drizzle.com Sat Jun 12 11:21:11 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 12 Jun 2004 15:21:11 -0000 Subject: How to detect list versus string References: None Message-ID: <1087053670.304667@yasure> Quoth Jonathon McKitrick : | I have a method that builds a dynamic combo box. Before I do that, I set a | class variable to the new list of items. | | def make_new_cat_box(self, cats): | self.cat_list = cats | | Sounds simple. But sometimes, my combo box will only have one choice | available. When I call this method with a list of one string, the string is | split up, and my combo box now has a separate item for each letter in the | string. What I obviously want to do is detect when the object coming in is | a list or a string. type() isn't as useful as I had hoped, and len() will | give me the length of the string, so I cannot tell if it is a string or a | list of more that one item. Well, there are a variety of approaches. Some programmers like to try to discriminate on the basis of functional distinctions, so for example they'll try to add two quantities together to see if their types are compatible in that respect. Since you apparently don't get tuples, only lists, you could test for hasattr(cats, 'append'). Etc. But what's going on there, really? `When I call this method with a list of one string ...?' Like this, a.make_new_cat_box([v])? Why would that put you in this spot? It sounds like you're really calling this method with just a string, not a list of one string. In which case, if you can avoid that, please do, put the string in a list and consider the problem solved! Donn Cave, donn at drizzle.com From jjl at pobox.com Fri Jun 4 09:09:18 2004 From: jjl at pobox.com (John J Lee) Date: Fri, 4 Jun 2004 14:09:18 +0100 (GMT Daylight Time) Subject: Which is the most mature Soap module? In-Reply-To: References: <87d64jdpz3.fsf@pobox.com> Message-ID: On Fri, 4 Jun 2004, [ISO-8859-1] Mickel Gr?nroos wrote: > On Fri, 4 Jun 2004, John J Lee wrote: > > > > 2. Is there a way to use cookie authentification with SOAPpy > > > (client-side)? > > > > Yes, no reason why not to use my ClientCookie package to do that, but I > > don't know from memory exactly where you need to insert the required code > > in SOAPpy. > > Do you mean subclassing SOAPpy and changing the places where it uses > urllib to talk to the server? (This might be totally off target -- I've > been browsing the code in SOAPpy and I'm getting confused ...) Something like that. > > I'm slightly surprised if SOAP needs cookie handling, but not > > entirely, since I know it is required for some XML-RPC services. > > I don't think SOAP needs cookies for anything. My problem is that the SOAP > server for upload is only available if I have a certain cookie that I > can send to the web server in the http header, i.e. the web server won't > let me through to the SOAP server unless I can supply the cookie first. [...] Right. John From tim.one at comcast.net Fri Jun 11 13:56:19 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 13:56:19 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: Message-ID: [Michael Kent] ... > I've been unable to get using a bound method as the key in a > WeakKeyDictionary to work. Using a class instance object works fine as a > key, using a method of that same instance object does not. Here's some > code, in a file named test_weakref.py: > > #! /usr/bin/env python > > import unittest import weakref > > class someClass(object): > def aMethod(self): > print "Hi!" > > class TestCase_01_weakref(unittest.TestCase): > > def test_01_simple(self): > > obj1 = someClass() > obj2 = someClass() > wkd = weakref.WeakKeyDictionary() > > wkd[obj1] = 1 > self.assertEqual(len(wkd), 1) > > wkd[obj1.aMethod] = 1 > self.assertEqual(len(wkd), 2) > > wkd[obj2.aMethod] = 1 > self.assertEqual(len(wkd), 3) > > > if __name__ == "__main__": > unittest.main() > > And here's the output: > > ./test_weakref.py F > ====================================================================== > FAIL: test_01_simple (__main__.TestCase_01_weakref) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "./test_weakref.py", line 22, in test_01_simple > self.assertEqual(len(wkd), 2) > File "/usr/local/lib/python2.3/unittest.py", line 302, in > failUnlessEqual > raise self.failureException, \ > AssertionError: 1 != 2 > > ---------------------------------------------------------------------- > Ran 1 test in 0.001s > > FAILED (failures=1) The bound methods you create become unreachable (via any strong reference) the instant they're added to the weak dict, so they vanish from the weak dict immediately after being added. That's what a weak dict is supposed to do. One way to get the test to pass is to replace the tail end with: temp1 = obj1.aMethod wkd[temp1] = 1 self.assertEqual(len(wkd), 2) temp2 = obj2.aMethod wkd[temp2] = 1 self.assertEqual(len(wkd), 3) That keeps the bound methods reachable via strong references for the duration of the test. After that, you could add: del temp1, temp2 self.assertEqual(len(wkd), 1) That will pass under CPython today, but there's no general guarantee about exactly when a weak dict will notice that keys (or values) have become unreachable by strong references. From tjreedy at udel.edu Tue Jun 15 19:55:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jun 2004 19:55:48 -0400 Subject: Combined natural and unnatural list sorting References: <20040615213822.26735.qmail@web20810.mail.yahoo.com> Message-ID: "Derek Basch" wrote in message news:20040615213822.26735.qmail at web20810.mail.yahoo.com... > Hello All, > > I need to sort a list using an unnatural sequence. > > I have a list like so: > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] > > print foo.sort() > > ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S'] > > > The order that I actually need is: > > ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] > > > So, in other words, I need the colors sorted alphabetically and the the sizes > sorted logically. Last I knew, 'Black' sorts before, not after 'White' ;-) Or do you really want colors alphabetically? TJR From peter at engcorp.com Fri Jun 18 21:25:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:25:07 -0400 Subject: [ANN] isrealfile function In-Reply-To: References: Message-ID: Manlio Perillo wrote: > def isrealfile(file): > """ > Test if file is on the os filesystem > """ > > if not hasattr(file, 'fileno'): return False > > try: tmp = os.dup(file.fileno()) > except: return False > else: os.close(tmp); return True > > I have implemented this function for testing if a Python script is > being executed by Python.exe or Pythonw.exe. In the latter case, in > fact, Microsoft implementation of stdout/stderr is broken. I haven't tested this idea, but wouldn't "os.isatty()" be the right thing for this purpose, instead of the os.dup() and os.close() stuff? -Peter From BrendanSimon at fastmail.fm Tue Jun 15 21:27:14 2004 From: BrendanSimon at fastmail.fm (Brendan J Simon) Date: Wed, 16 Jun 2004 11:27:14 +1000 Subject: python with Java API In-Reply-To: References: Message-ID: <40cfa1c1$1@dnews.tpgi.com.au> I know very little about Java at this stage and I know basically nothing about Swing. I'm searching the web to find more information. In the meantime I was wondering what the pros and cons of using Swing as apposed to wxPython as a GUI. My experience with wxPython is positive. I like the way it is implemented and the GUI widgets seem very good and have a native OS look and feel. Many thanks, Brendan Simon. ellisjb at my-deja.com wrote: > I would drop the wxPython idea and go with Swing, either with straight > Java or Jython. Doesn't sound like you have a compelling reason to add > the extra complication of another set of dependencies; Swing is a quite > capable toolkit (and far better documented than wxPython). > > -Jonathan > > Brendan J Simon wrote: > >>Hi, >> >>I have a Java application from a company. They also provide an API > > in > >>C++ (MSW platforms only) and Java (for all platforms) for developers >>that want to create their own front end. I want to use wxPython to >>create a decent Unix opensource frontend. >> >>Is it possible to Interface python to a java application easily ??? >> >>Assuming yes to above, would something like Jython or SWIG or some > > other > >>tool be required. >> >>Any advice or pointers would be greatly appreciated. >> >>Regards, >>Brendan Simon. > > From ajsiegel at optonline.com Tue Jun 1 10:58:17 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 01 Jun 2004 14:58:17 GMT Subject: terminological obscurity References: <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> <40b83034$0$27038$9b622d9e@news.freenet.de> <40b931c8$0$24826$9b622d9e@news.freenet.de> Message-ID: On Sun, 30 May 2004 02:58:48 +0200, "Martin v. L?wis" wrote: >"A type is a predicate" > >In that definition "is green" is as much a type as "has used Python >to write software". In that sense, things in a list should share the >same type. I am as sorry as anyone else that I find this subject as interesting as I do. "Is green" doesn't help us if the list does not cohere around the concept of color. And the above sentences implies, and I could independently imagine, a list might cohere around nothing more then the concept of existence. But of course the possbility of including non-exitence data does not exist. Which makes the notion of homogeneity around that concept meaningless. So I have, after consideration, decided to outlaw, if not the terminolkgy itself (even its its most general form), than at least my own efforts to find meaning in it. Art From peter.maas at mplusr.de Tue Jun 8 04:47:09 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 08 Jun 2004 10:47:09 +0200 Subject: win32all - determine wrkstn vs. server In-Reply-To: References: Message-ID: ChrisH schrieb: > Does anyone know of a way to determine whether the current computer > running a python script is a workstation or server? > > I've used the following code, but it only tells me the version of > Windows. > > (majVer,minVer,buildNum,platID,osInfo) = win32api.GetVersionEx() Try asking in comp.os.ms-windows.programmer.win32, because it is not a Python but a Win32 API issue. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From tjreedy at udel.edu Mon Jun 7 11:26:44 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Jun 2004 11:26:44 -0400 Subject: Destructors and exceptions References: Message-ID: "David Turner" wrote in message news:e251b7ba.0406070651.1c98c09d at posting.google.com... > The problem is that when an exception is raised, the destruction of > locals appears to be deferred to program exit. Am I missing > something? When the last reference to an object disappears, the interpreter *may* but is *not required* to forget or destruct the object, if indeed the concept is meaningful. What happens is implementation dependent. CPython usually cleans up immediately, which is sooner than with Jython. I am not sure what human interpreters do. Write once, never erase storage of objects (keeping a complete audit trail of objects created) would also be legal. If you want to force the issue, give your class a close method, as with file objects, and call it explicitly. Then code in try:finally:, which is designed for this purpose. try: process finally: cleanup Terry J. Reedy From mark at prothon.org Wed Jun 16 02:52:33 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 15 Jun 2004 23:52:33 -0700 Subject: mutable default parameter problem [Prothon] References: <200406152201.20003.troy@gci.net> Message-ID: Troy Melhase wrote: > Here's an idea: if it ain't broke, don't fix it. > > Seriously, you see a "wart" and a "problem". I see a pleasant > side-effect of the documented semantics. True, new folks are > surprised by the behavior, but once it's understood, it becomes more > powerful. All four of the Python gotcha's, wart's and regrets lists I have found included this problem. It is not only a newbie's problem as I showed in my posting. > How do you intend to account for code like this: > > def F(a, b, cache={}): > try: > return cache[(a,b)] > except (IndexError, ): > value = cache[(a,b)] = do_some_long_calc(a,b) > return value > > Or even this: > > shared_cache = {} > > def F(a, b, cache=shared_cache): > ... The first example is very unreadable and uncool in general. Your second example will work just fine with our fix. > Of course you can argue that this is bad style, Yes I (and many others) will. > but the counter > argument is just as strong: this is quite pythonic and quite > readable. I disagree strongly. I would never be caught coding something like that and I love Python dearly. > Python is a tool, and you decrease the utility of that tool when you > limit it's idioms. So far you have only shown me an idiom that many say should not be used. Show me one that everyone agrees is useful. >> How much Python code would these different proposals break? > > A lot. I ran this: > > $ find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} > \; | wc > > And see 67 instances just in the standard library. Multiply that by > a factor of 1000, 10000 or more to reflect code in the field, and you > might start to understand the significance of changing the language > definition. That count is not accurate. Fixing this will not break every use of [] as a default formal param. Using [] in __init__ for example would break nothing. I can think of many other cases where it is legal to use []. The only case I can think of that would break would be the idiom we disagree on above. If I am wrong, then show me other cases. If I also might make a general argument for the fix then let me continue. Doing a late evaluation of the default expression makes the language more dynamic, which fits the overall goal of making Prothon more dynamic. Using prototypes instead of classes, dynamic var scoping, this fix, and many other Prothon changes from Python all work towards that goal. Dynamic var scoping fixed another Python gotcha which doesn't break anything. Here are the two versions of code showing the problem and the fix: --- Python --- >>> x = 1 >>> def f(): ... x = x + 1 ... print x ... >>> f() UnboundLocalError: local variable 'x' referenced before assignment --- Prothon --- O>> x = 1 1 O>> def f(): ... x = x + 1 ... print x ... O>> f() 2 Prothon's scoping rules are dynamic which means that x comes from outside the function until the actual assignment happens. At that point x becomes a local variable. This, along with the fact that vars are inherited from ancestors along with methods, allow for some intuitive and simple var initialization techniques. Obviously it is the responsibility of the programmer to make sure that the outer x has the proper initialization value for the local x. This can cause a hiding-of-uninitialized-vars bug if the programmer uses the same names for unrelated variables but it is worth the extra power and intuitiveness. From http Fri Jun 11 20:08:42 2004 From: http (Paul Rubin) Date: 11 Jun 2004 17:08:42 -0700 Subject: does python have useless destructors? References: Message-ID: <7x1xklprhx.fsf@ruckus.brouhaha.com> "Tim Peters" writes: > >>> myfile = open("myfilepath", "w") > >>> try: > >>> myfile.write(reallybigbuffer) > >>> finally: > >>> myfile.close() > > Believe it or not, it isn't entirely "safe", but for a different reason: > it's quite possible for, e.g., KeyboardInterrupt to get raised and processed > between the "finally:" and the "myfile.close()" -- Google on > > "safe asynchronous exceptions for python" > > for a good paper on the topic. Nice paper, though the solution proposed seems a bit cumbersome, and blocking signals always needs to be done with care (suppose "myfilepath" is on an HFS that takes a minute or two to physically load a tape into a drive in order to open the file). I think this particular example can be done with no blocking: class unopened_file: def close(self): pass myfile = unopened_file() try: myfile = open("myfilepath", "w") myfile.write(reallybigbuffer) finally: myfile.close() If there's an interrupt before the open completes, "myfile.close" will operate on the unopened_file and be a do-nothing. Maybe there's some more general and less ugly way to do something like that. From irmen at -nospam-remove-this-xs4all.nl Sun Jun 13 15:47:59 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 13 Jun 2004 21:47:59 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: <-N6dnc_ka_7JClHdRVn-gg@comcast.com> References: <40cc8deb$0$563$e4fe514c@news.xs4all.nl> <-N6dnc_ka_7JClHdRVn-gg@comcast.com> Message-ID: <40ccaf71$0$36861$e4fe514c@news.xs4all.nl> Tim Peters wrote: > [Irmen de Jong] > >>In fact, what algorithm is Python itself using when you try to: >> >> >>> print 2**24036583 - 1 >> >>?? > > > Recent Pythons convert to base 10000 internally by repeated division, along > the lines of [... interesting comments....] To me it sounds as if Python's default long-to-decimal-string code is heavily optimized already. So then why this discussion about a fast algorithm to print very large longs? How could it be better than just a simple: >>> print myHugeLong --Irmen From jepler at unpythonic.net Mon Jun 14 21:10:11 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 14 Jun 2004 20:10:11 -0500 Subject: Using metaclasses to play with decorators. In-Reply-To: References: Message-ID: <20040615011011.GB6648@unpythonic.net> Here's another way to use metaclasses to specify decorators: class O(object): __metaclass__ = DecoratedMeta def f(cls, x, __decorate__ = [classmethod]): return x*x def g(x, __decorate__ = [staticmethod]): return x**3 def h(self, x): return x I think this is a terrible abuse, and I would never want to see this used in real-world code, but that didn't stop me from writing the code to show how *cough*clever*cough* I am. Here's the little-tested implementation: import inspect, types def decorate(func): argnames, _, _, defaults = inspect.getargspec(func) try: i = argnames.index("__decorate__") except ValueError: # x not in list return func j = i - len(argnames) decorators = defaults[j] decorators.reverse() # XXX: Add code here to remove __decorate__ from func's arglist for d in decorators: func = d(func) return func def DecoratedMeta(name, bases, ns): for k, v in ns.iteritems(): if not isinstance(v, types.FunctionType): continue ns[k] = decorate(v) return type(name, bases, ns) if __name__ == '__main__': class O(object): __metaclass__ = DecoratedMeta def f(cls, x, __decorate__ = [classmethod]): return x*x def g(x, __decorate__ = [staticmethod]): return x**3 def h(self, x): return x print O.f(3), O.g(4) o = O() print o.f(5), o.g(6), o.h(7) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From inyeol.lee at siimage.com Wed Jun 9 14:12:38 2004 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Wed, 9 Jun 2004 11:12:38 -0700 Subject: How to write dos newline in unix? Message-ID: <20040609181238.GJ18163@siliconimage.com> Is there any simple way to dos-style newline (\r\n) in *nix environment, not by writing "\r" explicitly? What I'm trying to do is; ofile = file("foo", "w") print "hello, world" Then it writes "hello, world\r\n". I tried to assign "\r\n" to ofile.newlines but failed because it's read-only attribute. Inyeol Lee From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 29 14:49:37 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 29 Jun 2004 20:49:37 +0200 Subject: Problem with Python on MAC OSX In-Reply-To: References: <2kcql4Fo2nbU1@uni-berlin.de> Message-ID: <2kdri2F171lbU1@uni-berlin.de> edadk wrote: > Hi, > > >> But why don't you like the result? The directories pointed to by both >> paths are the same... >> > > This feature is casuing problem when I use the Scons build. See > www.scons.org. > > It call external tools to do various thing for instance calling the > perforce source control commandline tool p4 via spawn. So when Scons > do something like > > 'p4 sync file.c' > > perforce gets confused because it wants to work with > > /home/eda/file.c > > and not > > /private/home/eda/file.c > > I agree in most case this feature is not causing any problems but > sometimes it does. So you must resort to using the shell-set $PWD -- the kernel does not keep track of your current directory in the terms of links. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From cpbotha at i_triple_e.org Thu Jun 3 04:58:24 2004 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Thu, 3 Jun 2004 08:58:24 +0000 (UTC) Subject: VTK 4.2.6 + Python 2.3.4 and VTK Examples problem References: <2335b39d.0406020426.4522d772@posting.google.com> Message-ID: In article <2335b39d.0406020426.4522d772 at posting.google.com>, Ron Kneusel wrote: > I have installed VTK 4.2.6 and Python 2.3.4. Both are working and I > can run the VTK Python examples except for those in the GUI directory. > These always fail with messages similar to this: > > /home/rkneusel/VTK/Examples/GUI/Python> python2.3 BoxWidget.py > Traceback (most recent call last): > File "BoxWidget.py", line 57, in ? > boxWidget = vtk.vtkBoxWidget() > AttributeError: 'module' object has no attribute 'vtkBoxWidget' You forgot to build the Hybrid packages, i.e. VTK_USE_HYBRID should be set to ON during your cmake configuration. Many of the classes used in the GUI examples are part of the Hybrid code. By the way, it's probably a better idea to post VTK Python problems on the VTK list. -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From kboruff at optonline.net Sun Jun 13 07:24:03 2004 From: kboruff at optonline.net (Keith P. Boruff) Date: Sun, 13 Jun 2004 11:24:03 GMT Subject: Howegrown wordcount In-Reply-To: <40caf952$0$41751$5fc3050@dreader2.news.tiscali.nl> References: <40caf952$0$41751$5fc3050@dreader2.news.tiscali.nl> Message-ID: Gr?goire Dooms wrote: > What's the purpose of stripping the items in the list if you just count > their number ? Isn't this equivalent to > words += len(input.split(sep)) > >> return words >> else: >> for item in input: >> wordcount(item) >> >> return words > > > Removing the global statement and sep param, you get: > > def wordcount(input): > if isinstance(input, str): > return len(input.split()) > else: > return sum([wordcount(item) for item in input]) > > -- > Gr?goire Dooms After reading this thread, I decided to embark on a word counting program of my own. One thing I like to do when learning new programming languages is to try and emulate some of my favorite UNIX type programs. That said, to get the count of words in a string, I merely did the following: # Beginning of program import re # Right now my simple wc program just reads piped data if not sys.stdin.isatty(): input_data = sys.stdin.read() print "number of words:", len(re.findall('[^\s]+', input_data)) # End of program Though I've only done trivial tests on this up to now, the word count of this script seems to match that of the wc on my system (RH Linux WS). I ran some big RFC text files through this too. There could be some flaws here; I don't know. I'll have to look at it better when I get back from the gym. If anyone here finds a problem, I'd be interested in hearing it. Like I said, I love using these UNIX type programs to learn a new language. It helps me learn things like file I/O, command line arguments, string manipulations.. etc. Keith P. Boruff From BELLEMAIL-SA at exponent.com Thu Jun 17 03:56:41 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 00:56:41 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28E90@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = michele.simionato at poste.it(MicheleSimionato) Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 224 Scanning time = 06/17/2004 00:56:40 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment document_all02c.zip contained WORM_NETSKY.P virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From mwh at python.net Sat Jun 5 07:47:20 2004 From: mwh at python.net (Michael Hudson) Date: Sat, 5 Jun 2004 11:47:20 GMT Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: > 'Few immediate tangents: everyone read Miki's piece on > Python-coded *assemblers* http://www.unixreview.com/documents/s=9133/ur0404e/ >? I saw that article just *after* I'd written my PowerPC assembler in Python: http://starship.python.net/crew/mwh/hacks/PPY.html I wonder why people independently start thinking of the same crazy things at the same time? Cheers, mwh -- Not only does the English Language borrow words from other languages, it sometimes chases them down dark alleys, hits them over the head, and goes through their pockets. -- Eddy Peters From MAIL-SA at gcc-sg.org Fri Jun 25 02:20:05 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Fri, 25 Jun 2004 09:20:05 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F6509259D@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = ftp-upload at gnu.org Recipient(s) = python-list at python.org; Subject = Re: word document Scanning Time = 06/25/2004 09:20:05 Engine/Pattern = 7.000-1004/915 Action on message: The attachment document.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Jun 9 13:59:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 13:59:05 -0400 Subject: dropping into the debugger on an exception In-Reply-To: <2iovgrFq6taqU1@uni-berlin.de> References: <2inqlrFp53m5U1@uni-berlin.de> <2iolfjFp6c46U1@uni-berlin.de> <2iovgrFq6taqU1@uni-berlin.de> Message-ID: Jon Perez wrote: > Thomas Heller wrote: > >>> Just to be clear: you don't want this to happen all the time, >>> you want it to happen only with a particular script, yet you >>> don't want to modify that script at all? >> I also don't understand *why* he wants to have it that way. > > Just in case you missed the answer I gave earlier... > > I don't even want this behaviour all the time with the same > script because end-users will be confused if they get dropped > into pdb. Believe me, you don't want to explain what pdb is > to people who have a hard time even navigating via the > command prompt! > > The best situation would be to be able to invoke this behaviour > only when I want it (i.e. during coding/debugging) Basically this seems to require command line options, right?j If so, just include a standard snippet in the __main__ section of your scripts which checks the first command line option to see if it's "--jon's_special_pdb_magic" (or whatever ;-) ) and then programmatically invoke the excepthook stuff... -Peter From rogerb at rogerbinns.com Wed Jun 16 17:32:08 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 16 Jun 2004 14:32:08 -0700 Subject: thread help References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Peter Hansen wrote: > I didn't think things worked quite that way in Java. For > example, I thought InterruptedException was seen by a thread > only if it had actually been asleep at the time it was sent. > > I also didn't know it would actually terminate certain > blocking calls, such as in socket stuff. http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#interrupt() As is the Java way, they have different types of interrupted exceptions and sockets etc would need to be InterruptibleChannels. They also use checked exceptions which makes life a lot harder. More on Java best practises for thread interruption: http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html I would just settle for a nice clean mechanism whereby you can call Thread.interrupt() and have an InterruptException in that thread (which ultimately terminates the thread if it isn't handled anywhere). Some threads won't be interruptible because they are deep in extension libraries. Perhaps that can be returned to the caller of Thread.interrupt(). Roger From dominic.fox at square3.net Tue Jun 8 09:49:06 2004 From: dominic.fox at square3.net (Dominic Fox) Date: Tue, 8 Jun 2004 14:49:06 +0100 Subject: Callbacks to generators In-Reply-To: <_Zhxc.27159$sS2.784227@news20.bellglobal.com> Message-ID: It would be nice if something like this *could* work - you could instantly and effortlessly transform a SAX parser into a .Net-style XmlReader. Alas, it cannot... "yield" in a function causes the function to return a generator object to the caller - in this case, the caller of on_token, not the caller of process_iter. The inner function "on_token" in "process_iter" returns a generator when it is called by "process", and "process" promptly throws this generator away. The value returned by "process_iter" is just the return value from "process". It might be possible to do something with call/cc, but of course Python doesn't have that. Dominic -----Original Message----- From: Humpty Dumpty [mailto:oliver.schoenborn at utoronto.ca] Sent: 08 June 2004 13:07 To: python-list at python.org Subject: Re: Callbacks to generators > def process(text, on_token): > ... > > For each token that "process" finds in "text", it creates a token object, > "token", and calls "on_token(token)". > > Now, suppose I wanted to create a generator based on this function. I tried > to do the following: > > def process_iter(text): > def on_token(token): > yield token > process(text, on_token) > > However, rather than create a generator as I had hoped, this function > doesn't return anything. I guess it creates a bunch of singleton generators, > one per token, and throws them away. In any case, is there a way to do what > I am trying to do here without resorting to threads? Something weird here. I hven't used generators much, but seems to me that: 1) you maybe don't need them: def process_iter(text): def on_token(token): return token process(text, on_token) 2) you need some sort of while loop so the fnction doesn't return after the first yield: def process_iter(text): def on_token(token): while 1: yield token process(text, on_token) I'm curious to understand if neither of those are true, why... Oliver From belred1 at yahoo.com Sun Jun 6 19:02:18 2004 From: belred1 at yahoo.com (Bryan) Date: Sun, 06 Jun 2004 23:02:18 GMT Subject: py2exe/wxpython demo Message-ID: just for fun and my own experience, i wanted to use py2exe to wrap the wxpython demo. i put the setup script in the demo directory which is the following: from distutils.core import setup import glob import py2exe setup(windows=['demo.py'], data_files=[('bitmaps', glob.glob('bitmaps/*.*')), ('data', glob.glob('data/*.*')), ('bmp_source', glob.glob('bmp_source/*.*')), ('', glob.glob('*.py'))], ) and ran the command like this: setup py2exe --ignores wx.BitmapFromImage,wx.EmptyIcon --includes ActiveX_FlashWindow,ActiveX_IEHtmlWindow this was successful except for one thing... do i really have to explictly list every script file in the demo directory in the --includes argument on the command line? there are so many. i was hoping to somehow be able to add it in the script as a glob, but nothing i did worked. in case you aren't aware, the .py files in the demo directory is used both as a data file which is why i added them in the data_files section, and also as python scripts which needs to be added in the library.zip file. the --includes argument on the command line will correctly compile and place the .pyc files in the library.zip, there must be a better way that having to added them all explicitly on the command line. thanks, bryan From me at privacy.net Thu Jun 3 03:27:56 2004 From: me at privacy.net (Duncan Booth) Date: 3 Jun 2004 07:27:56 GMT Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> <69cbbef2.0406021049.41406074@posting.google.com> Message-ID: has.temp2 at virgin.net (has) wrote in news:69cbbef2.0406021049.41406074 at posting.google.com: >> The ultimate Python templating framework for separating Python from the >> template has to be PyMeld. PyMeld templates are pure XHTML with no >> additional attributes whatsoever. > > I looked at PyMeld early on as it's closest to HTMLTemplate in concept > and behaviour and about the same in code size and complexity. I got the impression that your HTMLTemplate was quite similar in concept to TAL but less powerful (probably deliberately). Certainly it looks as though most of your constructs map straight onto a very similar TAL expression. From diabolik at uku.co.uk Mon Jun 7 07:43:49 2004 From: diabolik at uku.co.uk (dean) Date: 7 Jun 2004 04:43:49 -0700 Subject: HPUX Installation error Message-ID: <70efe2ee.0406070343.5655862@posting.google.com> Hello Group: I obtained a copy ofthe python 2.3.3 depot (binary zipped) from the hp porting archive. I have successfully unzipped the file and installed it using swinstall. I received the following errors when installing: --------------------snip----------------------------- xx * Target logfile: hermes:/var/adm/sw/swagent.log ^ x xx * Reading source for product information. x xx * Reading source for file information. x xx The corequisite "gettext.gettext-SHLIBS" for fileset x xx "python.python-SHLIBS,r=2.3.3" cannot be successfully x xx resolved. x xx The corequisite "ncurses.ncurses-SHLIBS" for fileset x xx "python.python-SHLIBS,r=2.3.3" cannot be successfully x xx resolved. x xx The corequisite "openssl.openssl-RUN" for fileset x xx "python.python-SHLIBS,r=2.3.3" cannot be successfully x xx resolved. x xx ERROR: The dependencies for fileset "python.python-SHLIBS,r=2.3.3" x xx cannot be resolved (see previous lines). v x xxqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq Has anybody seem this error and how is it rectified. I am also unable to install the cx_oracle module. Please help -----------------------oracle error------------------------- root at hermes:/home/dlicheri/cx_Oracle-4.0.1 > python setup.py build install Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Traceback (most recent call last): File "setup.py", line 13, in ? import time ImportError: No module named time From elbertlev at hotmail.com Mon Jun 28 11:51:37 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 28 Jun 2004 08:51:37 -0700 Subject: poplib for multihomed machines Message-ID: <9418be08.0406280751.6cc50097@posting.google.com> There no way to tell the classPOP3 which of local interfaces (NICs) to use for connections). In most cases it is OK, but requires proper routing. Here is the __init__ from POP3 class POP3 def __init__(self, host, port = POP3_PORT): self.host = host self.port = port msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) except socket.error, msg: if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg self.file = self.sock.makefile('rb') self._debugging = 0 self.welcome = self._getresp() Can I subclass it in such a way, that derived class takes care of the problem? def __init__ (self, host, port = POP3_PORT, interface = ""): POP3.__init..(....) will create the socket and there is no way to bind it to local interface The problem with POP3 class is: it connects during __init__ and it is "hard coded". I do not see any way to change this behavior with no rewrite of POP3 class. Do you? From rogerb at rogerbinns.com Fri Jun 18 14:21:01 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 18 Jun 2004 11:21:01 -0700 Subject: does python have useless destructors? References: <7ifz8udxp2.fsf@enark.csis.hku.hk> Message-ID: <6jobq1-ksi.ln1@home.rogerbinns.com> David Turner wrote: > The most obvious way in which RAII can be enabled is by introducing > defined reference-counting semantics for objects with __del__. I > can't think of another way of doing it off-hand, but there must be > others (if reference counting has unacceptably high overhead). I would be quite happy to get an exception or equivalent when a situation arises that the GC can't handle. I would consider it a bug in my code or design and something I should fix, and consequently would want to know about it. Other people's opinion may differ (tm). Roger From j_mckitrick at bigfoot.com Thu Jun 17 20:55:55 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 17 Jun 2004 17:55:55 -0700 Subject: Code density References: Message-ID: Peter Hansen wrote in message > Blank lines are a readability tool as much as clear indentation is. > Depending on the definition of "sparingly", this may be the one > piece of Guido's advice that we've ever ignored... :-) I've found myself using even more blank lines in python than C++. But if you look at BitTorrent, for example, the author claims blank lines are a nuisance. He writes very dense code, but I wonder if it would be easily maintainable by anyone besides him. jonathon From __peter__ at web.de Sat Jun 19 04:18:20 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jun 2004 10:18:20 +0200 Subject: Help needed: optimizing dictionary creation/access References: <40d3e9fa$0$603$39db0f71@news.song.fi> Message-ID: Pekka Niiranen wrote: > def update(p_name, p_keyp, p_cost, p_unit, data): > t = time.asctime() > if data.has_key(p_name): > if data[p_name].has_key(p_keyp): > if data[p_name][p_keyp].has_key(p_cost): > if p_unit > data[p_name][p_keyp][p_cost][0]: > data[p_name][p_keyp][p_cost] = [p_unit, t] > else: > data[p_name][p_keyp][p_cost] = [p_unit, t] > else: > data[p_name][p_keyp] = {p_cost: [p_unit, t]} > else: > data[p_name] = {p_keyp: {p_cost: [p_unit, t]}} > return data > Untested: def update(name, keyp, cost, unit, root): data = root.setdefault(name, {}) data = data.setdefault(keyp, {}) oldunit = data.get(cost, None) if oldunit: if unit > oldunit[0]: oldunit[:] = [unit, time.asctime()] else: data[cost] = [unit, time.asctime()] return root You might consider using a single dictionary with (name, keyp, cost) tuples as keys. Peter From FBatista at uniFON.com.ar Thu Jun 17 15:07:43 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 17 Jun 2004 16:07:43 -0300 Subject: align on char Message-ID: [John Hunter] #- Suppose you have a sequence of strings, all known to have at #- least one #- occurance of char #- #- lines = ( #- 'user1 : John Hunter', #- 'another user : Bill Bragg', #- 'yet on more : Hi There', #- ) #- #- what is the best / easiest / most elegant way of producing this? #- #- aligned = ( #- 'user1 : John Hunter', #- 'another user : Bill Bragg', #- 'yet on more : Hi There', #- ) My way: >>> lines = ( 'user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There', ) >>> lines ('user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There') >>> aligned = [] >>> maxa = 0 >>> for line in lines: (a, b) = line.split(':') maxa = max(maxa, len(a)) aligned.append(':'.join((a.ljust(maxa),b))) >>> aligned ['user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There'] >>> print '\n'.join(aligned) user1 : John Hunter another user : Bill Bragg yet on more : Hi There . Facundo From davidf at sjsoft.com Wed Jun 2 03:52:58 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 09:52:58 +0200 Subject: OT: Cryptography puzzle In-Reply-To: <2i4v2qFj4rvhU1@uni-berlin.de> References: <7WZuc.134$mt.29@read3.inet.fi> <2i4v2qFj4rvhU1@uni-berlin.de> Message-ID: Greg Ewing wrote: > Christian Gudrian wrote: > >> And what about the 'ss' in 'ssfd'? I don't know many languages that >> allow >> words to start with two identical letters. > > > Obviously it's "my hovercraft is full of eels" with > several spelling mistakes. > The attached program shows that there is no one-to-one mapping of characters that will result in this string matching words from /usr/share/dict/words (at least on my machine) Could be faster/neater/more elegant but there you go David -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mapletters.py URL: From brett at coombs.anu.edu.au Mon Jun 7 22:24:59 2004 From: brett at coombs.anu.edu.au (Brett Calcott) Date: Tue, 8 Jun 2004 14:24:59 +1200 Subject: wxPython DnD stops working after SetSizeHints References: Message-ID: "Emiliano Molina" wrote > > from wxPython.wx import * > from wxPython.xrc import * > > class TestFrame(wxFrame): > def __init__(self,parent,ID): > wxFrame.__init__(self,parent,ID,"test frame",(100,30),(70,60),wxDEFAULT_FRAME_STYLE) > self.panel=wxPanel(self,-1) This gets overwritten -^ > > class FileDropTarget(wxFileDropTarget): > def __init__(self, window): unused --------------------^ > wxFileDropTarget.__init__(self) > > def OnDropFiles(self, x, y, filenames): > print filenames > > class App(wxApp): > def OnInit(self): > > self.res=wxXmlResource("test.xrc") > self.frame=self.res.LoadFrame(None,"FRAME1") > self.frame.panel=XRCCTRL(self.frame,"test_list") > > dt=FileDropTarget(self.frame) > self.frame.panel.SetDropTarget(dt) > > # The following lines break the drag and drop > # self.panel=XRCCTRL(self.frame,"panel") > # sizer=self.panel.GetSizer() > # sizer.SetSizeHints(self.frame) What is self.panel, as opposed to self.frame.panel? > > self.frame.Show() > self.SetTopWindow(self.frame) > > return True > Hi Emiliano, it isn't clear what you are trying to do here, you seem to have a panel being created in 3 different places -- which one do you want? I suspect that the self.panel, is hiding the other panel that you created (self.frame.panel) which is the drop target (just a guess) I've never used xrc, but this works for me (is it what you want?) class App(wxApp): def OnInit(self): self.res=wxXmlResource("test.xrc") self.frame=self.res.LoadFrame(None,"FRAME1") self.frame.panel=XRCCTRL(self.frame,"panel") dt=FileDropTarget() self.frame.panel.SetDropTarget(dt) # The following lines break the drag and drop sizer=self.frame.panel.GetSizer() sizer.SetSizeHints(self.frame) self.frame.Show() self.SetTopWindow(self.frame) return True From klachemin at home.com Thu Jun 24 17:13:58 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 14:13:58 -0700 Subject: Python Color Printing References: <889cbba0.0406240136.3a735356@posting.google.com> Message-ID: <889cbba0.0406241313.431e9f7b@posting.google.com> Duncan Booth wrote in message news:... > Try SciTE which can be downloaded free from http://www.scintilla.org Thanks, I'll check it out! From rogerb at rogerbinns.com Wed Jun 23 15:09:44 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 23 Jun 2004 12:09:44 -0700 Subject: Queue module and Python Documentation Rant References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: Skip Montanaro wrote: > If you are yourself a newbie how do you distinguish the wheat from the > chaff? The same way they do it when reading this group :-) Providing the documentation clearly distinguishes the "official" content from the user contributed comments I don't see a problem. Sure some idiot could put in clueless misleading drivel, but the same is true of wikis, mailing lists and the php doc. It has not been a major problem for any them. Roger From cmg at dok.org Thu Jun 10 13:38:47 2004 From: cmg at dok.org (Chris Green) Date: Thu, 10 Jun 2004 13:38:47 -0400 Subject: Distutil question References: Message-ID: Steve Menard writes: > How do I go about distributing those files so that a source > dsitribution will compile properly? should I rename them to .h files > instead? The way I always fix this type of thing is to create a MANIFEST.in and add recursive-include src *.hpp to it. -- Chris Green Laugh and the world laughs with you, snore and you sleep alone. From rigga at hasnomail.com Sat Jun 19 04:01:03 2004 From: rigga at hasnomail.com (RiGGa) Date: Sat, 19 Jun 2004 09:01:03 +0100 Subject: Help with parsing web page References: Message-ID: RiGGa wrote: > Miki Tebeka wrote: > >> Hello RiGGa, >> >>> Anyone?, I have found out I can use sgmllib but find the documentation >>> is not that clear, if anyone knows of a tutorial or howto it would be >>> appreciated. >> I'm not an expert but this is how I work: >> >> You make a subclass of HTMLParser and override the callback functions. >> Usually I use only start_ end_ and handle_data. >> Since you don't know *when* each callback function is called you need to >> keep an internal state. It can be a simple variable or a stack if you >> want to deal with nested tags. >> >> A short example: >> #!/usr/bin/env python >> >> from htmllib import HTMLParser >> from formatter import NullFormatter >> >> class TitleParser(HTMLParser): >> def __init__(self): >> HTMLParser.__init__(self, NullFormatter()) >> self.state = "" >> self.data = "" >> >> def start_title(self, attrs): >> self.state = "title" >> self.data = "" >> >> def end_title(self): >> print "Title:", self.data.strip() >> >> def handle_data(self, data): >> if self.state: >> self.data += data >> >> if __name__ == "__main__": >> from sys import argv >> >> parser = TitleParser() >> parser.feed(open(argv[1]).read()) >> >> HTH. >> -- >> ------------------------------------------------------------------------- >> Miki Tebeka >> The only difference between children and adults is the price of the toys. > Thanks for taking the time to help its appreciated, I am new to Python so > a little confused with what you have posted however I will go through it > again and se if it makes more sense. > > Many thanks > > Rigga Said I would be back :) How do I get the current position (offset) which I am at in the file? I have tried getpos() and variations thereof and keep getting syntax errors... Thanks R From dave at pythonapocrypha.com Thu Jun 17 11:30:31 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 17 Jun 2004 09:30:31 -0600 Subject: Rationale for core Python numeric types References: Message-ID: <04d501c45480$06a41460$8119fea9@boba> Matt wrote: > I'm new to Python, and was somewhat taken aback to discover that the > core language lacks some basic numerical types (e.g., single-precision > float, short integers). I realize that there are extensions that add > these types-- But what's the rationale for leaving them out? Have I > wandered into a zone in the space/time continuum where people never > have to read binary data files? The struct module is the most common way of reading/writing binary files. For complex structures stored in files I sometimes use ctypes. As for the rationale nehind not having types like 'short', 'long', etc. I can only guess - perhaps the reasons include (1) their presence in a language encourages programmers to worry about details they usually don't need to be burdened with and (2) for many (most?) cases, you're really talking about marshalling data - an OS API takes a short int, a file header has an unsigned long, a network message requires a byte for bit fields, etc. - and the problem of data marshalling doesn't necessarily need to be tied that closely to the numeric types of the language. Again, these are just my guesses... -Dave From aahz at pythoncraft.com Mon Jun 21 11:13:56 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Jun 2004 11:13:56 -0400 Subject: Watershed Python Versions References: <40dd3107.0406191120.6879a1c6@posting.google.com> Message-ID: In article , Ville Vainio wrote: >>>>>> "Ted" == Ted writes: > > Ted> I would like to collect opinions on which versions of Python > Ted> should be considered watershed versions. By this I mean > Ted> versions which are stable and contain significant landmark > Ted> features. > >All Python versions are (supposed to be) stable :). More or less, yup. >I think it's generally perceived that 2.2 is a watershed version. It's >the introduction of "modern" Python, with iterators, generators and >new style classes. > >2.0 might be also - 1.5.2 is the last "old" Python, and the version >that has no doubt been irritating to many, due to Red Hat using it as >the default Python in the old versions (pre 8.0). In fact I found >writing for Python 1.5.2 almost intolerable, having to do without a+=1 >(writing a=a+1 instead, ah, the pain). ISTR list comprehensions were >introduced back on 2.0 too, but I really started loving them on 2.1 >era. That's roughly correct, although the big news in 2.0 was Unicode. Other critical additions were string methods, augmented assignment, and garbage collection. See the "What's New" section of http://www.amk.ca/python/ Generally speaking, although all released Python versions have been extremely stable by industry standards, my preference is to wait for the first bugfix release of the first major version after a watershed version. IOW, good releases would be 2.1.x and 2.3.x. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From dkturner at telkomsa.net Mon Jun 14 10:56:55 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 07:56:55 -0700 Subject: does python have useless destructors? References: <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: Marcin 'Qrczak' Kowalczyk wrote in message news:... > On Mon, 14 Jun 2004 00:05:45 -0700, David Turner wrote: > > It doesn't help that only some objects must have reference counts changed, > because you statically don't know which are these, so you must check all > potential objects anyway. That's true, but the check could be cached so that all it would amount to is a single test-and-branch. The crucial difference is that there's no need to acquire a mutex. Regards David Turner From walter at livinglogic.de Thu Jun 3 15:06:29 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jun 2004 21:06:29 +0200 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: References: <69cbbef2.0406010619.7cd39e71@posting.google.com> <69cbbef2.0406021106.c393f20@posting.google.com> Message-ID: <1086289404.104509@homer.tmt.de> John Machin wrote: > [...] > Oh, you want *practical* experience eh? ;) > > I would think the "theory" is that you've got designers/authors working > on templates, who don't know code. They know HTML, and know CSS, but > they do not program or know any code. You give these people templates to > work on. XIST follows a different philosophy: All templates are pure XML (in fact most of our templates consist of a root element only (something like )). The rest is done in pure Python code. The designer develops the XML elements for the layout. This might be something simple like: class pageTitle(xsc.Element): def convert(self, converter): e = html.h1(self.content) return e.convert(converter) These layout elements can then be used for a static mockup to be presented to the customer (i.e. foobar in XML or layout.pageTitle("foobar") in Python). The developer responsible for the dynamic part uses these layout elements with XIST JSP elements to implement the business logic, e.g. by using layout.pageTitle(jsp.expression("myObject.getTitle()")). It would be possible to use any other templating system for implementing the business logic, e.g. use PHP: layout.pageTitle(php.expression("$myObject->getTitle()"). > [...] > Another successful separation of logic from presentation... or so the > theory goes... ;) XIST uses another version, just that both logic and presentation are implemented in Python. ;) You have to say goodbye to your HTML editor with this approach, but this gives you better control over your HTML code anyway. Our main designer had no previous programming experience and was using Adobe GoLive before joining our company. Now he's programming all his HTML templates in Python without any problems. Bye, Walter D?rwald From jjl at pobox.com Tue Jun 29 16:04:46 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Jun 2004 21:04:46 +0100 Subject: urlib - automatic cookie handling References: <10e2sgtng7f23b2@corp.supernews.com> <10e2v5f5es5lcd@corp.supernews.com> <10e2v891ru300c5@corp.supernews.com> Message-ID: <87n02mf7vl.fsf@pobox.com> Alex Hunsley writes: [...] > > http://wwwsearch.sourceforge.net/ClientCookie/ [...] > Snap! I think we both posted at about the same time. Good to know > someone was suggesting it anyway! You might care to know that the cookie-handling part of ClientCookie has found its way into Python 2.4, as module cookielib. So, the development version of CC (which is compatible with old versions of Python) is currently moving towards being as-compatible-as-possible with cookielib and 2.4 urllib2. Actually, if you're using Python 2.3 and want to be forwards-compatible with 2.4 here, I'm 95% sure you can just grab cookielib and urllib2 from Python CVS and use those. cookielib doesn't import urllib2, so you can leave 2.3's urllib2 intact and use a local copy of 2.4's urllib2, eg. by keeping it somewhere like ~/lib/python and renaming it urllib2_24.py. cookielib doesn't include stuff like HTTPEquivProcessor that are in ClientCookie, but I'll make those available in a form that works with 2.4 in a separate package soon (that package will probably be ClientCookie itself, in a 1.0.x or late 0.9.x version). I should mention these things on the web page... John From maney at pobox.com Sat Jun 12 21:15:32 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 13 Jun 2004 01:15:32 +0000 (UTC) Subject: speed problems References: Message-ID: Hans-Peter Jansen wrote: > if logfile.endswith('.gz'): > #ifd, lfd = os.popen2("%s %s" % (gzip, logfile)) > #XXX: cheating > ifd, lfd = os.popen2("%s %s | grep INFECTED" % (gzip, logfile)) > elif logfile.endswith('.bz2'): > #ifd, lfd = os.popen2("%s %s" % (bzip2, logfile)) > #XXX: cheating > ifd, lfd = os.popen2("%s %s | grep INFECTED" % (bzip2, logfile)) > else: > # uncompressed > lfd = open(logfile, "r") Why stop there? You've left on the verge of collapsing into the fully reduced (and regularized) form: if logfile.endswith('.gz'): cat_command = 'zcat' elif logfile.endswith('.bz2'): cat_command = 'bzcat' else: cat_command = 'cat' ifd, lfd = os.popen2("%s %s | grep INFECTED" % (cat_command, logfile)) (for that matter, is there some reason to use popen2 and the unnecessary ifd?) I've found it advantageous to preprocess large inputs with grep - the tens of MB of squid logs that are skimmed by a useful little CGI script really benefited from that! Python's raw I/O may be as good as anything, but for line by line parsing where a majority of the (many) lines are discarded, a grep prefilter is a big win. Which may or may not bring us back to... well, it's not a corollary to Steve Lamb's guideline for using shell script, though it's clearly related. Maybe it's the contrapositive. Never get so wrapped up in using that Python hammer that you forget about those carefully honed specialized tools. Use that one line of shell to the best effect! -- Anyone who calls economics the dismal science has never been exposed to educationist theories at any length. An hour or two is a surfeit. From k.loughran at qub.ac.uk Fri Jun 11 11:45:26 2004 From: k.loughran at qub.ac.uk (Karen Loughran) Date: Fri, 11 Jun 2004 16:45:26 +0100 Subject: raw Strings from XML attributes Message-ID: Hiya, I'm reading a string attribute from an XML document. The string contains newline characters and is treated as raw. I'm trying to match it with a string read from a file which is identical . But because it isn't raw it won't match. I've seen documentation for converting string 'literals' to raw form with r'Sample String'. But is there a function which will convert my raw string read from XML to non-raw/escaped sequence format ? Or to convert a string 'variable' read from a file to raw form ? ie, I'm not converting string 'literals' ? Thanks Karen From rogerb at rogerbinns.com Thu Jun 10 17:21:10 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 10 Jun 2004 14:21:10 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Duncan Booth wrote: > def f(filename): > dispose infile, outfile > > infile = file(filename, "r") > outfile = file(filename+".out", "w") > outfile.write(infile.read()) While that looks nice, the real problem I have with it is that the caller/consumer of objects has to know that they need disposing. For example they have to know that strings don't need to be disposed of but files do. And then things get really complicated with toolkits. For example in a graphical toolkit do windows, device contexts, colours, brushes etc have to be disposed of? The correct answer of course is that the object itself should be aware that it needs to be disposed of and that real world resources can leak if it isn't. Which brings us back in a full loop. Currently objects signify that they need disposing by having a destructor. Why not "fix" that mechanism? Roger From goodger at python.org Thu Jun 3 16:15:44 2004 From: goodger at python.org (David Goodger) Date: Thu, 03 Jun 2004 16:15:44 -0400 Subject: reStructuredText Cheat Sheet In-Reply-To: References: Message-ID: <40BF86F0.5090406@python.org> chris wrote: > to be honest i find it a bit confusing... It's a quick reference card to for authors who already know the syntax but need reminders. It's not meant as something to learn from. That's what the "See for full info" is for. You'll find tutorial and user documentation there. -- David Goodger From brianc at temple.edu Wed Jun 23 18:34:13 2004 From: brianc at temple.edu (brianc at temple.edu) Date: Wed, 23 Jun 2004 18:34:13 -0400 Subject: strange behaviour with remove Message-ID: Common newbie learning step. A variable in python is a reference, not the actual data itself. So in "d = { 'list' : l }", you are storing a reference to the original "l", not a new list. Look at the following interactive session: >>> x=['foo','bar'] >>> y=x >>> x[1]='foo' >>> y ['foo', 'foo'] >>> import copy >>> y=copy.deepcopy(x) >>> x[1]='bar' >>> y ['foo', 'foo'] You need to use the copy module in order to make an entirely new list. -Brian ---- Original message ---- >Date: Sat, 19 Jun 2004 12:41:58 +0200 >From: Panard >Subject: strange behaviour with remove >To: python-list at python.org > >Hi! > >Can anyone explain this to me : >$ cat test.py >l = [ 1, 2, 3 ] >d = { 'list' : l } > >for x in l : > print "rm", x > d[ 'list' ].remove( x ) > print "l =", l > >print d > >$ python test.py >rm 1 >l = [2, 3] >rm 3 >l = [2] >{'list': [2]} > > >Why 2 isn't removed ? and why l is changing during the loop ?? >Am I missing something ? > >My python is 2.3.4 > >Thanks > >-- >Panard >-- >http://mail.python.org/mailman/listinfo/python-list From n/a Tue Jun 1 19:28:55 2004 From: n/a (Maboroshi) Date: Tue, 1 Jun 2004 16:28:55 -0700 Subject: Python Crypto Question Message-ID: <10bq4a142unvn06@corp.supernews.com> Hi I was interested if there was a way to encrypt common ports on my computer like port 80: and my FTP port on the Client side using Python Forgive me if this sounds like an amatuer question but I don't know to much about this I understand I can access secure servers that offer this encryption but when I recieve information from a server is it possible for my computer to download it anonomously and have it encrypted. So basically the server can't see that I am there and any information passed from my computer to that server for a request, that server log or whatever would just be a bunch of numbers appearing. I understand that a proxie might make me anonymous does this make sense I would like to program something like this if it is a plausible idea Thanks in advance From rogerb at rogerbinns.com Sat Jun 12 12:03:03 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 12 Jun 2004 09:03:03 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Duncan Booth wrote: > "Roger Binns" wrote in > news:q3ipp1-4bp.ln1 at home.rogerbinns.com: > > > You have totally confused me now. Ignoring special cases such as > > cycles, Python destructs an object when there are no references left > > to it, and in CPython that happens at the moment the last reference is > > released. So in normal code the objects will go away as names > > referencing them go out of scope. > > I wouldn't say that cycles are special cases exactly. They are to the point I was trying to make, which is that objects are freed when there are no references left in the CPython implementation. The rest of your comment is missing my point. I don't particularly care about *when* an object is garbage collected, just that *is* garbage collected at some point. The whole problem that this thread is about is that Python has this bizarre scheme that an object will be garbage collected *unless* you add a __del__ method, at which point the docs imply you will be lucky for garbage collection to *ever* happen on the object. > No, Python guarantees that the object will (almost always) be destroyed. The issue is the cases when it doesn't destroy objects. That is the whole point of this discussion and I refer you to the very first message: http://groups.google.com/groups?selm=slrnccetd9.gag.msoulier%40tigger.digitaltorque.ca > Guaranteeing that all resources will be released at a specific time has > implications for performance, and finalisers are actually pretty rare in > practice, so the usual solution is to compromise. It isn't a timing issue. It is a "will it ever happen" issue. Roger From paulo.pinto at cern.ch Thu Jun 10 09:39:41 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Thu, 10 Jun 2004 15:39:41 +0200 Subject: xml.dom.minidom help! In-Reply-To: <2c60a528.0406100238.101de8bc@posting.google.com> References: <2c60a528.0406100238.101de8bc@posting.google.com> Message-ID: pxdom doesn't work either. It fails to read the DTD declarations inside the files. :( I'll have to look for alternative ways of manipulating the files. Thanks anyway, Paulo Andrew Clover wrote: > Paulo Pinto wrote: > > >>When I read the file the parser builds the DOM nodes >>with those default values. So when I write the file >>I get those default values inside the tags! > > >>I don't want this behaviour. Is it possible to change? > > > Not AFAIK, short of deleting the attributes manually. minidom does not > support Attr.specified. (See: > > http://pyxml.sourceforge.net/topics/compliance.html > > though actually minidom/4DOM are actually broken in a slightly more > involved way than described here, should update that really.) > > pxdom will do it OK, if the DOM Level 3 LS 'discard-default-content' > property is set True on LSSerializer.domConfig, which it is by > default. > From tim.golden at viacom-outdoor.co.uk Wed Jun 16 03:59:59 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 16 Jun 2004 08:59:59 +0100 Subject: computer names and samba shares Message-ID: | can anyone tell me how to find the list of computer names on | a samba network, and | | the list of shared folders / devices on a samba networked computer? | | We have a GNU/Debian Server, and I am trying to do it first | from a Win2000 machine (though ideally, the code should be | platform-independent). The meaning of "the list of computer names on a samba network" is not terribly well defined, but taking the request at face value, there are several possibilities: 1) NET VIEW (From NET HELP VIEW) "When used without options, [NET VIEW] displays a list of computers in the current domain or network." 2) http://tgolden.sc.sabren.com/python/win32_how_do_i/list_machines_in_a_domain .html This uses the WinNT: object under Windows. There are other options, using the win32net code, Active Directory (either via ADSI objects or via LDAP), and the Samba equivalent to NET VIEW (check the Samba docs for that), but an amount depends on exactly what you're after and whether you're trying to get. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From mcfletch at rogers.com Tue Jun 29 12:18:35 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 29 Jun 2004 12:18:35 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: <40E1965B.5090600@rogers.com> Sion Arrowsmith wrote: >A.M. Kuchling wrote: > > >>It seems much simpler to choose PostgreSQL (or perhaps Firebird) instead of >>MySQL; neither database presents such an irritating licensing issue. >> >> > >Unless your target platform is Windows, in which case Postgres >presents an even more irritating licensing issue, in that not >only do you need a licence, but you need to decide who you're >going to get it from. > >(Compatability of Firebird's SQL with any existing SQL you >have lying around is another matter which is giving me a major >headache at the moment.) > > Well, somewhat pointless, as the OP has stated his belief that he must go with MySQL, but I'm pretty darn sure PostgreSQL is freely available for Windows platforms (I use it every day). It can be quite readily installed as part of the CYGWIN environment, and the server thus installed works nicely with any of the PostgreSQL client libraries for Python (including PyPgSQL, which is BSD licensed). Oh well, time to go back to real work now, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From project5 at redrival.net Mon Jun 28 05:48:06 2004 From: project5 at redrival.net (Andrei) Date: Mon, 28 Jun 2004 09:48:06 +0000 (UTC) Subject: wxPython syntax References: Message-ID: OKB (not okblacke aol.com> writes: > I've started taking a look at wxPython, and, well, I've noticed > that the syntax needed to code with it is extremely ugly. I am > wondering if there exist any preprocessing tools or clever refactorings > that allow users to write more sane-looking code. In particular, it wax is supposed to be more Pythonic, but I haven't used it (yet). > seems to me that the structure of the code often does not reflect the > structure of the GUI being designed. For instance, the wxPython wiki > "Getting Started" guide includes this code to set up a file menu with > About and Exit options: You're right, this kind of code is ugly. Fortunately you don't *have to* write any of it, since you can use one of the design tools available to generate all the ugly stuff. You'll still have to live with lots of Get... and Set... methods instead of just plain properties, but that's bearable. My fav. is wxGlade. > Pieces of the code, like "filemenu" and ID_ABOUT and OnAbout, are > confusingly repeated throughout the definition. Doesn't it seem like wxGlade won't make the id's go away though. wax will. Yours, Andrei From nobody at nowhere.com Mon Jun 14 04:38:25 2004 From: nobody at nowhere.com (PaxDiablo) Date: Mon, 14 Jun 2004 16:38:25 +0800 Subject: How to Access Unix Shell References: <2d7af4f8.0406131648.42868c63@posting.google.com> Message-ID: "Miki Tebeka" wrote in message news:mailman.929.1087194935.6949.python-list at python.org... > Hello PaxDiablo, > > > [[snip]] > How about : > === > files = os.listdir(".") > === > > Bye. > -- > ------------------------------------------------------------------------- > Miki Tebeka > The only difference between children and adults is the price of the toys. > Well, I could claim that I knew about listdir but was simply answering the original question which was how to run arbitrary shell commands. But in fact I knew nothing of listdir (all of my coding so far has been with wx(Python|Widgets) so I rarely use the python system stuff) , so I thank you for the education :-). Pax. From theller at python.net Tue Jun 29 14:19:29 2004 From: theller at python.net (Thomas Heller) Date: Tue, 29 Jun 2004 20:19:29 +0200 Subject: win32 pyserial requires javax.comm for py2exe? References: Message-ID: Peter Hansen writes: > Grant Edwards wrote: > >> I'm trying to package a small Python program using py2exe. >> Everything works fine until I add an "include serial", then py2exe >> fails because >> The following modules appear to be missing >> ['javax.comm'] > > Actually, you are assuming too much. It's a warning, not a failure. > The .exe file is generated and will run just fine under Windows. > > Don't bother editing PySerial! You'll just create a maintenance > hassle for yourself. Right. pyserial probably uses the same code for CPython and Jython, if you want to avoid the warning you should exclude 'javax.comm' from the build, either with the '--excludes javax.comm' command line option, or by passing something like this to the setup function in your build script: setup(... options = {'py2exe': {'excludes': ['javax.comm']}}) Thomas From mark at prothon.org Sat Jun 26 01:28:01 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 25 Jun 2004 22:28:01 -0700 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: "Doug Holton" wrote > That's a great goal, creating a simplified python dialect that can be > converted to regular Python syntax and bytecode. It's a little outside > of my reach right now though. And prothon which was mentioned recently > is incompatible with the python "virtual machine". I'm not trolling for Prothon users, since Prothon isn't ready for use anyway, but I'm curious why you have to use the Python intepreter. Can you fill me in? Prothon by the way doesn't have anonymous code blocks, but it can do: b = button() def b.onClick(): print "You clicked me" Is that what you wanted? From tfreeman at cs.uchicago.edu Thu Jun 3 00:32:07 2004 From: tfreeman at cs.uchicago.edu (Tim Freeman) Date: Wed, 2 Jun 2004 23:32:07 -0500 Subject: C compiler written in Python Message-ID: <20040602233207.4bc48ffa@localhost> Doing an independent study with Dave Beazley this quarter, Atul Varma has written a C compiler on his own in Python. It generates annotated x86 assembly code from arbitrary C files. Quoting Atul's website: * The different stages of compilation are encapsulated in visitor classes, which (in my opinion) makes the code quite readable, and also made writing the compiler a lot easier. The yacc rules merely generate the abstract syntax tree and visitors do the rest. * The code generator is also a visitor, which makes the process very modular; for instance, although this compiler doesn't generate intermediate code (which is what most compilers that compile for different architectures use), one could simply write, say, a SPARC code generation visitor and run the AST through it to generate assembly for that architecture. This separation also means that the rest of the compiler is independent of machine architecture. * Writing the compiler in Python allowed me to focus entirely on the task at hand (compilation), without being distracted by issues of memory management and low-level data structure creation. Using such a high-level language also made reading and refactoring the code a lot easier. Have a look: http://people.cs.uchicago.edu/~varmaa/mini_c/ And this is the annotated assembly output: http://people.cs.uchicago.edu/~varmaa/mini_c/foo.s From rswerdlow at transpose.com Fri Jun 11 15:38:14 2004 From: rswerdlow at transpose.com (Bob Swerdlow) Date: Fri, 11 Jun 2004 15:38:14 -0400 Subject: Bad install of 2.3.4 on Solaris 8 Message-ID: <027801c44feb$a8e1dda0$046fa8c0@RSWERDLOW800> I'm having trouble getting Python 2.3.4 installed properly on Solaris 8. First some configuration stuff: bash-2.05# export . . . declare -x HOSTTYPE="sparc" declare -x MACHTYPE="sparc-sun-solaris2.8" declare -x OSTYPE="solaris2.8" I copied Python-2.3.4.tgz to /var/tmp, ran gunzip and tar xvf then ran./configure, make and make install from the Python-2.3.4 directory. ./configure report this error: configure: WARNING: term.h: present but cannot be compiled configure: WARNING: term.h: check for missing prerequisite headers? configure: WARNING: term.h: proceeding with the preprocessor's result configure: WARNING: ## ------------------------------------ ## configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## configure: WARNING: ## ------------------------------------ ## I went ahead anyway. make report this warning gcc -shared build/temp.solaris-2.8-sun4u-2.3/_ssl.o -L/usr/local/ssl/lib -L/usr/local/li b -lssl -lcrypto -o build/lib.solaris-2.8-sun4u-2.3/_ssl.so *** WARNING: renaming "_ssl" since importing it failed: ld.so.1: ./python: fatal: libssl.so.0.9.7: open failed: No such file or directory and a bunch of errors building sunaudiodev.o which I assume are not important since I'm not having audio problems Now, python runs and reports that it is 2.3.4, but: 1. SSL doesn't work: bash-2.05# python Python 2.3.4 (#3, Jun 11 2004, 14:57:33) [GCC 3.3.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import xmlrpclib >>> s = xmlrpclib.ServerProxy('https://goombah.emergentmusic.com') >>> s.hello() Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/xmlrpclib.py", line 1029, in __call__ return self.__send(self.__name, args) File "/usr/local/lib/python2.3/xmlrpclib.py", line 1316, in __request verbose=self.__verbose File "/usr/local/lib/python2.3/xmlrpclib.py", line 1055, in request h = self.make_connection(host) File "/usr/local/lib/python2.3/xmlrpclib.py", line 1237, in make_connection raise NotImplementedError( NotImplementedError: your version of httplib doesn't support HTTPS 2. A 32 bit version was installed rather than the 64-bit version that should be installed for this machine. This prevent the installation of MySQLdb from installing properly bash-2.05# file /usr/local/bin/python /usr/local/bin/python: ELF 32-bit MSB executable SPARC Version 1, dynamically linked, not stripped Can you please help me get a good build so I can get on with my work? Thanks, Bob From fabianosidler at my-mail.ch Tue Jun 22 20:39:18 2004 From: fabianosidler at my-mail.ch (Fabiano Sidler) Date: Wed, 23 Jun 2004 00:39:18 +0000 (UTC) Subject: Stopping a thread from another one Message-ID: Hello Newsgroup! In my Python script, I use the 'thread' module (not 'threading') and 'signal' simultaneously. All spawned threads execute 'pcapObject.loop(-1, callback)', which does not return. The problem now is: When the script catch a signal (let's say: SIGHUP), only the main thread is affected. But I need also the subthreads to be ended, because the script reopen()s files on SIGHUP and would also re-create the threads. NOT a solution is: The main thread sets a lock in the signal handler, the pcap-callback() function examines this lock everytime it's called, and if set, exit()s the thread. This is not very beautiful. I would prefer, if I end the subthreads by the main thread. Is there any chance? Greetings, fps From noamr at correctme.users.sourcephorge.net Sat Jun 5 20:16:41 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Sun, 06 Jun 2004 03:16:41 +0300 Subject: repr of floating points Message-ID: Hello, repr(0.1) is '0.10000000000000001', in my Python 2.3. From reading the article "Floating Point Arithmetic: Issues and Limitations", I understand that it's the closest 17-digit decimal representation of the binary floating-point number actually stored. However, I don't understand why this should be what repr of floats returns. repr should, if possible, return a string that evaluating it will be == to the original object. But eval("0.1") obviously returns the same floating point as 0.1 does! So why not make repr of floats return the *shortest* decimal representation that will evaluate to the stored binary number? Specifically, why not make repr(0.1) be "0.1"? Thanks, Noam Raphael From beliavsky at aol.com Tue Jun 8 12:09:54 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 Jun 2004 09:09:54 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> Message-ID: <3064b51d.0406080809.2b94b54c@posting.google.com> Peter Hickman wrote in message news:<40c58636$0$8219$afc38c87 at news.easynet.co.uk>... > You are correct, it is just that if all you are concerned about is speed then > assembler is what you need. However when you put this to people you find out > that what they really want is 'easy to write fast programs'. Assembler comes > with many hurdles but you are not going to get any faster using a higher level > language. Do you have experience to back up your claims? I have not written assembler, but sources I respect tell me that good C++ and Fortran (especially Fortran 95 with its array operations) compilers DO let you write programs in a high-level language that are more efficient than the hand-coded assembly you might produce (taking infinitely longer to write). Given an infinite amount of programming time, very few programmers are going to write assembly code that outperforms LAPACK (in Fortran) for linear algrebra or FFTW (in C) for Fourier transforms. Your point that Python is a productive language despite its slower execution speed is valid, but don't pretend that the natural alternative is assembly language. From anand at easi.soft.net Mon Jun 21 05:28:56 2004 From: anand at easi.soft.net (Anand K Raydu) Date: Mon, 21 Jun 2004 14:58:56 +0530 Subject: cmp ?? Message-ID: <40D6AA58.7070901@easi.soft.net> Hi All, How does cmp work? I have 2 PyCObjects, and both of them have same C object. can i use cmp(ob1,obj2) in another case i have obj2 as NULL and i want to check if it is a NULL object. can some one suggest how to check it? Thanks & Best Regards, Anand From francesco.banconi at tin.it Sat Jun 5 08:17:12 2004 From: francesco.banconi at tin.it (Francesco Banconi) Date: Sat, 05 Jun 2004 12:17:12 GMT Subject: [OT] Preventivo per un software Message-ID: Mi trovo nella scomoda situazione di dover quantificare le spese per un software che dovr? scrivere (ovviamente usando python). La scomodit? deriva dalla mancanza di informazioni, sia per quanto riguarda il budget disponibile, sia anche rispetto alle specifiche e alle funzionalit? del software stesso. Vi dico in breve le poche info che ho: il software dovr? gestire la trascrizione e la digitalizzazione di documentazione manoscritta antica, probabilmente i tecnici che effettueranno la trascrizione si serviranno di tag ad-hoc inerenti vari campi specifici della materia trattata (quindi ho intuito che bisogner? implementare una sorta di parser che filtri la trascrizione riempiendo i campi di un database. Quindi immagino che dovr? implementare un inserimento dati (con parsing), e poi la possibilit? di modificare, rimuovere ed effettuare ricerche sui dati inseriti. Tali ricerche dovranno tener conto di alcuni alias che ricorrono dove nei manoscritti ad esempio la stessa persona compare con nomi leggermente diversi. Ho pensato di usare WxPython+MySQL. Questo ? quanto. Scusandomi per l'OT e per aver forse abusato della vostra pazienza vi chiedo qualche dritta sia sul possibile costo del software sia sul tempo di implementazione secondo voi necessario (ovviamente a grandi linee). Grazie. -- Francesco From hank at nicht-prosysplus-schpamme.com Sat Jun 12 16:12:00 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Sat, 12 Jun 2004 16:12:00 -0400 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> <504ced20c24ba170fd83d409302113ae@news.teranews.com> Message-ID: <10cmosch4o00c08@corp.supernews.com> In addition, for your advanced class you could take a look at Leo, part of the Literate programming effort. Think of a outliner, where your code resides under the nodes of the tree. For the data-oriented aspect of the application, you can put the data-oriented Use Cases as the tree, and put the code that implements each use case right there. Leo does much more, but it's a tool that will open your students' minds, and probably spoil them for the future. Hank Fay -- "Mediocre Person" wrote in message news:504ced20c24ba170fd83d409302113ae at news.teranews.com... > Leif K-Brooks wrote: > > Mediocre Person wrote: > > > >> So, what pitfalls should I look out for in introducing Python to > >> students who have had a year of Visual BASIC? > > > > > If at all possible, I would recommend changing the Visual Basic class to > > RealBASIC (http://realbasic.com/). It's not perfect, but it has proper > > OO support, and would make the transition to Python much easier. Even > > better would be teaching basic Python to the VB class and more advanced > > Python to the 12th graders; > Using Python for the early class is not out of the question--but I'd > want to find an environment that mimics (or improves upon) VB's > brilliantly (forgive me) easy model of designing the gui and then > programming responses to events. Someone mentioned SPE, which I haven't > seen in action yet. > > Python's biggest strength is allowing > > beginners to use simple OO or even procedural techniques without ever > > noticing the advanced stuff like list comprehensions and metaclasses. From has.temp2 at virgin.net Mon Jun 21 05:14:24 2004 From: has.temp2 at virgin.net (has) Date: 21 Jun 2004 02:14:24 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> Message-ID: <69cbbef2.0406210114.439f4ee@posting.google.com> Paramjit Oberoi wrote in message news:... > > FWIW, I've designed, written, used and killed both types of systems, > > and think the DOM-style beats macro-style hands down for the majority > > of use-cases, and definitely the most graphic designer-friendly > > approach. > > I expect it depends on what is changing more. If you are working on code > in the application, then you want the templates themselves to have no > code. On the other hand, if you are using a "finished" application and > want to make changes to the HTML produced without fiddling with the > application code, Presentation logic is application code too, regardless of where you put it and what language it's written in. - The advantage of embedding logic in markup is it's easier for non-programmers and other folk who aren't good at/don't like working in the abstract to see what's going on. (i.e. easier mental modelling) - The advantage of separating the two is very designer-friendly markup and complete freedom in how you design and implement the logic. (i.e. easier maintainance) With HTMLTemplate et-al, there's nothing to stop you putting the controller code in separate modules to the model code, making it easy to edit the former without messing with the latter. (Splitting each layer into its own module is probably a good design practice anyway.) > Cheetah-like systems are much more flexible (and simple > substitution-only templates are very limiting). DOM-style templating systems aren't 'substitution-only', and can easily match or surpass macro-style systems for power and flexibility at a fraction of the size and complexity. From http Thu Jun 3 00:16:51 2004 From: http (Paul Rubin) Date: 02 Jun 2004 21:16:51 -0700 Subject: ANN: PyGMP 0.9 (Python GNU Multiple Precision Library wrapper) References: Message-ID: <7x8yf5ff7w.fsf@ruckus.brouhaha.com> Heiko Wundram writes: > PyGMP is a wrapper for the GNU multiple precision library. It > currently sports two types, GMPi (for doing integer arithmetic), and > GMPrand (for handling random numbers). How is this different from gmpy? From andrea.gavana at polymtl.ca Thu Jun 17 10:54:19 2004 From: andrea.gavana at polymtl.ca (Andrea) Date: 17 Jun 2004 07:54:19 -0700 Subject: Python & Mayavi Problem Message-ID: <73a69f04.0406170654.328aecb6@posting.google.com> Hello NG, I'm trying to follow the mayavi documentation in order to run mayavi from python. In "Chapter 4. Using MayaVi from Python", there is a simple example like this: # generate the data. from Numeric import * import scipy x = (arange(50.0)-25)/2.0 y = (arange(50.0)-25)/2.0 r = sqrt(x[:,NewAxis]**2+y**2) z = 5.0*scipy.special.j0(r) # Bessel function of order 0 # now dump the data to a VTK file. import pyvtk # Flatten the 2D array data as per VTK's requirements. z1 = reshape(transpose(z), (-1,)) point_data = pyvtk.PointData(pyvtk.Scalars(z1)) grid = pyvtk.StructuredPoints((50,50, 1), (-12.5, -12.5, 0), (0.5, 0.5, 1)) data = pyvtk.VtkData(grid, point_data) data.tofile('test.vtk') import mayavi v = mayavi.mayavi() # create a MayaVi window. d = v.open_vtk('test.vtk', config=0) # open the data file. # The config option turns on/off showing a GUI control for the data/filter/module. # load the filters. f = v.load_filter('WarpScalar', config=0) n = v.load_filter('PolyDataNormals', 0) n.fil.SetFeatureAngle (45) # configure the normals. # Load the necessary modules. m = v.load_module('SurfaceMap', 0) a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) # configure the axes module. o = v.load_module('Outline', 0) v.Render() # Re-render the scene. Everything goes fine, but at the end I obtain the mayavi window completely red (without the expected surface/image), and when I click on this window I get different errors depending on which Python editor I run: 1) Pythonwin: Error: Microsoft Visual C++ Runtime Error. Everything Crashes. After this, I get a vtkwindow coming up and showing me the "always-present" error message from mayavi: "Generic Warning: In /debian/stage/vtk-4.2.4/Rendering/vtkTkRenderWidget.cxx, line 638 A TkRenderWidget is being destroyed before it associated vtkRenderWindow is destroyed. This is very bad and usually due to the order in which objects are being destroyed. Always destroy the vtkRenderWindow before destroying the user interface components" I don't know why, but with mayavi this warning is EXTREMELY common... 2) IDLE for Python: All is frozen, nothing happen, I have to kill Python; 3) Python Command Line: No windows appears, nothing happen. Moreover, I would like to be able to compile my Python application to a standalone EXE file by using py2exe, but py2exe complains about some missing modules (either from mayavi and for scipy), and the created EXE does not start. I have installed Python using the Enthought Installer for Python (with lots of site-packages inside), located at: http://www.enthought.com/python/ I'm running Win2000, without administrator privileges (if this can make differences). Does anyone have an idea? Thanks for every suggestion. Andrea. From lists at andreas-jung.com Fri Jun 4 05:01:16 2004 From: lists at andreas-jung.com (Andreas Jung) Date: Fri, 04 Jun 2004 11:01:16 +0200 Subject: undefined symbol: PyObject_GenericGetAttr when trying to embed Python Message-ID: <9E731D6947D6517162BAB48F@[192.168.0.100]> I am trying to embed Python within a C++ application (Linux, Python2.3.4). I am using the example from the example from the "Embeding and Extending" docs. This works fine importing a simple module without any imports. However when I add an "import urllib" inside the Python script to be imported through my C++ application then the import fails: Traceback (most recent call last): File "/home/ajung/sandboxes/HR2/hr2_zope_wrapper/hr2_wrapper.py", line 16, in hr2_wrapper import urllib File "/opt/python-2.3.4/lib/python2.3/urllib.py", line 26, in ? import socket File "/opt/python-2.3.4/lib/python2.3/socket.py", line 44, in ? import _socket ImportError: /opt/python-2.3.4/lib/python2.3/lib-dynload/_socket.so: undefined symbol: PyObject_GenericGetAttr Any ideas? Andreas From fredrik at pythonware.com Sat Jun 5 15:28:05 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 5 Jun 2004 21:28:05 +0200 Subject: #! shbang for pyc files? References: Message-ID: "MarkV" wrote: > FYI, the context here is that we want to distribute scripts as part of an > application, but we don't want users to go mucking around with the scripts. > Yeah, I know, that's half the fun, but they don't get to muck around with > the C programs, and when they do muck around with the current shell scripts, > it causes us fits because their changes don't get into our source control. here's one way to do it: http://www.pythonware.com/products/python/squeeze/ From http Tue Jun 29 13:14:44 2004 From: http (Paul Rubin) Date: 29 Jun 2004 10:14:44 -0700 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: <7xvfhacmm3.fsf@ruckus.brouhaha.com> Lothar Scholz writes: > This is not a possible option. I must use MySQL. 95% (??) of the > databases in the small company world are MySQL based. > > Now this world becomes to look more and more like Micrsosoft, > especially if you keep in mind that MySQL AB is now owned by the > worlds 3rd largest Software Company SAP. I don't understand what your issue is. You want to use a MySQL client library in your application, you don't want to pay a license fee to use the library, but on the other hand you don't want use the GPL'd client because you want to charge a license fee your own users. If the license fee system works so well for you, why don't you want to participate in it in both directions instead of just one? You're asking for an environment where you get to charge license fees but nobody else does. That just seems like asking a bit much. From rupole at hotmail.com Tue Jun 8 23:16:07 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 8 Jun 2004 23:16:07 -0400 Subject: pywin32 support for CreateTypeLib2 References: Message-ID: <40c67d1b_5@127.0.0.1> Since you already have working code, the best bet would be to submit a patch to the Pywin32 project on Sourceforge. It would probably go over better as an addition rather than a replacement so it doesn't break any working code. Roger "Philip Rittenhouse" wrote in message news:MPG.1b2fbaf892ad01d8989680 at nntp.wcom.ca... > I was just wondering if there are any plans to support the > CreateTypeLib2 API either instead of, or in addition to, the > CreateTypeLib API. > > I am currently using pythoncom to generate type libraries, but > I ran into an issue supporting optional parameters. After a > lot of digging I discovered that the old CreateTypeLib API doesn't > support them. I have currently built a custom version of pywin32 > that uses the new CreateTypeLib2 API, and everything works great. > I'm hoping that the CreateTypeLib2 support can be added to the > official release. > > > Thanks, > Phil > From peter at engcorp.com Wed Jun 2 13:25:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jun 2004 13:25:47 -0400 Subject: OT: Cryptography puzzle In-Reply-To: References: <7WZuc.134$mt.29@read3.inet.fi> <3ngrb0le5g1l08li3rmbl3258i5e0pt731@4ax.com> Message-ID: rzed wrote: > This thread reminds me of my favorite highly-insecure encryption > method. It does give a moment's pause to those intent on decoding > such things, and works far better with longer messages than short, > but it can bring a smile at least, and will completely fool a child > of six for several hours. Here's an example of some encoded text: > > *[ > Thgi snia lpn itxetht iw tpyrcedtp yrcn ednasdn ei rfruoy ezamaye. > Ko nse ri uqer dn alair et amlautxet sedo. Ce ddnas edoc nehto > (1853, 1927), bmargo rpemase ($315.23) hty lfeht noe-docedot reikc, > irteltti lasi ta h thguoh tlaffuts la utxetn on reh tod. Nas tnuo > marallo dset adhtiws kro wtimrof detpyrc neronial, pni daerebna ct > ire. Doced laut canatuo hti wnevede/tpyrced ebyl idae rn actxe > tsiht! > ]* And, perhaps most remarkably for an encryption algorithm, it happens to have the exact same letter-distribution frequency as regular English! ;-) -Peter From lsolis at mu.intecsa-inarsa.es Fri Jun 11 04:20:04 2004 From: lsolis at mu.intecsa-inarsa.es (Luis Solís) Date: Fri, 11 Jun 2004 08:20:04 GMT Subject: replace a line in a text file Message-ID: I need open a text file, for example 1 2.3 4.5 4.5 open file mode=x read the file line by line if some in line i == xx: replace line i by newline close file Thanks in advance From peter at engcorp.com Thu Jun 10 09:52:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 09:52:41 -0400 Subject: does python have useless destructors? In-Reply-To: <10cfmnrr8su9050@corp.supernews.com> References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <10cfmnrr8su9050@corp.supernews.com> Message-ID: Michael Geary wrote: > Peter Hansen wrote: >>This code, on the other hand: >> >>>try: >>> myfile = open("myfilepath", "w") >>> myfile.write(reallybigbuffer) >>>finally: >>> myfile.close() >> >>... "feels" just right. This is how you do it when you >>want to be sure the file is closed, regardless of >>other considerations like garbage collection, etc. >> >>It is simple, clean, and most of all, very explicit. > > And it has a bug. :-) > > What if "myfilepath" is not writable? The open() call raises an exception, > which jumps to the finally: block, where myfile.close() fails because myfile > is undefined. > > What would be the cleanest way to code this to handle that error situation? You're quite right! Sorry... I was reacting to just the presence or absence of the exception handling code, without even reading it. :-( The correct approach is of course to open the file *before* the exception block starts. If you are concerned that the open might fail, which is a *different* type of exception, then you probably want a try/except block around the whole thing as well as the try/finally. -Peter From fabianosidler at my-mail.ch Mon Jun 21 10:48:37 2004 From: fabianosidler at my-mail.ch (Fabiano Sidler) Date: Mon, 21 Jun 2004 14:48:37 +0000 (UTC) Subject: [pylibpcap] Sniffing with multiple pcapOjbects Message-ID: Hello Friends! How would you implement as parallel as possible sniffing with multiple pacpObjects? On my machine, I must create pcapObjects for two interfaces, but I don't want the others, for example, eth0 and lo to be put to promiscious mode. Thanks for reply && Greetings, fps From alloydflanagan at comcast.net Tue Jun 8 17:04:08 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 8 Jun 2004 14:04:08 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<40c1e793$0$563$e4fe514c at news.xs4all.nl>... > Maboroshi wrote: > > > > In my opinion Python is the best language there is and I love it. The > > reason for me asking these questions was because I saw a lot of people > > trying to compare python to C and I had to find out what the big deal was > > and why C would be a faster language - I like to know how things work - > > > I have taken the liberty of taking a few of the comments made > in this thread and writing them down here: > http://www.razorvine.net/python/PythonSpeed > I've added a few other things related to Python's performance, > such as a short reference to Psyco. > > > --Irmen de Jong. Nice page. May I suggest you link into the "official" python wiki at http://www.python.org/cgi-bin/moinmoin/? I'd like to see a lot more contribution to that one. From me at privacy.net Thu Jun 24 09:57:53 2004 From: me at privacy.net (Duncan Booth) Date: 24 Jun 2004 13:57:53 GMT Subject: Private/public module members References: <9418be08.0406240537.6404a96@posting.google.com> Message-ID: elbertlev at hotmail.com (Elbert Lev) wrote in news:9418be08.0406240537.6404a96 at posting.google.com: > Not only doc(foo) has '_c', '_private' and 'b', but one can call them > from outside the module. > It this "by design"? Yes. All that prefixing with an underscore or listing names in '__all__' is intended to do is to modify the behaviour of 'from foo import *'. It does not prevent access, or even restrict visibility in any way. From mcfletch at rogers.com Thu Jun 24 20:25:31 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 24 Jun 2004 20:25:31 -0400 Subject: SNMP Toolkit In-Reply-To: References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> Message-ID: <40DB70FB.8010701@rogers.com> Les Smithson wrote: >>>>>>"Matthew" == Matthew Bell writes: >>>>>> >>>>>> ... > Matthew> I've tried PySNMP which, while a fine piece of code (I've > Matthew> learnt a lot looking through it!), it's fairly CPU > Matthew> intensive in my application. I've also tried using > Matthew> UCDSNMP via popen() but that has a tendency to hang in a > Matthew> multi-threaded environment. > > ... >SNMP agents/managers that >I've worked on (admittedly not using Python) were always I/O bound, >rather than CPU bound. > > PySNMP is actually a *very* heavy library compared to C ASN.1 parsers. I've certainly run into situations where it's just not fast enough to do what we want to do. Thing is, it's flexible and can be readily integrated with Twisted, so we still use it, even if it does mean it can take 10 minutes to scan a plant. That's all processor-bound time, not IO bound. Some day I'm going to try to squeeze some money out of the budget to spend a week on figuring out how to make PySNMP faster, but until then I'm afraid I just don't have a good suggestion for large SNMP querying tasks. Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From __peter__ at web.de Mon Jun 21 09:26:06 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jun 2004 15:26:06 +0200 Subject: ConfigParser Keys References: Message-ID: Neil Benn wrote: > To my chagrin, I've just discovered that SafeConfigParser, by > default, returns all the keys in the key/value pairing in lowercase > (what earthly possible reason it would do this I do not know!). Does The config file may be edited by a non-programmer. It is a safe assumption that he will expect KEY=value, key=value and Key=value to affect the same option. > anyone know of a way of stopping it doing this? Untested: class CaseSensitiveSafeOptionParser(SafeOptionParser): def optionxform(self, optionstr): return optionstr Peter From peter at engcorp.com Fri Jun 11 09:08:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 09:08:42 -0400 Subject: [python] struct module round off error? In-Reply-To: References: Message-ID: David Stockwell wrote: > When I first set it and print it, it has the correct value (50.3). > > However all i did was pack it, and then unpack it and it lost its > definite value of 50.3. > After the unpack it was approximately 50.3 (50.29999......) Actually, they have the same value each time. See http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate for more... (Hint: try repr(d) right after you do d=50.3 and see what you get.) -Peter From stuart at stuartbishop.net Thu Jun 10 04:22:38 2004 From: stuart at stuartbishop.net (Stuart Bishop) Date: Thu, 10 Jun 2004 10:22:38 +0200 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <559D1562-BAB7-11D8-97AE-000A95A06FC6@stuartbishop.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 10/06/2004, at 7:51 AM, Terry Reedy wrote: > "Donn Cave" wrote in message > news:donn-BCE10C.15003209062004 at nntp3.u.washington.edu... >> In article , >> "Michael P. Soulier" wrote: >> >>> I recently had a friend tell me that because the Python spec does not >>> guarantee that an object will necessary be destroyed when all > references >>> to it are gone, that desctructors in Python are not reliably called, > and >>> thus useless. > > To me, this is useless over-dramatization ;-) Is your car useless > because > there is no guarantee that the engine will never quit? or the brakes > fail? Your metaphor is flawed - *python* is not useless. The __del__ method is useless. Your metaphor should be 'Are your brakes useless if the brakes fail?'. >> - Reference cycles can prevent immediate finalization. >> If an object holds a reference to itself, however >> indirectly, it won't be deleted automatically and has >> to be recovered through garbage collection, and garbage >> collection won't delete instances with a __del__ method, >> among other things. > > This is admittedly a nuisance. Howver, the original solution was > reference > counting only. Programmers had to explictly break loops to reclaim > resources. This option remains available. Only if you write everything. Is there any guarantee that cyclic references will not be introduced into your parent class by your co-programmer, or in the next release of Zope, Twisted, Python, etc.? If you use __del__, you are writing fragile code in all but the most trivial situations (where it is usually unnecessary anyway). An argument can be made to issue warnings whenever __del__ is defined if this cannot or will not be fixed. - -- Stuart Bishop http://www.stuartbishop.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (Darwin) iD8DBQFAyBpTAfqZj7rGN0oRAn+VAKCNRE7BViqQsLz0coRVEd57e1sALwCeKGLl kwYQAG7QbKJiWteMdv663eQ= =FBlh -----END PGP SIGNATURE----- From bart_nessux at hotmail.com Thu Jun 17 16:39:08 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 17 Jun 2004 16:39:08 -0400 Subject: Queue module and Python Documentation Rant Message-ID: How can one view the contents of a queue? I'd like to verify that the queue has the same number of objects as the list that has been put into it. Also, should one think of a queue as static or dynamic (on the put side)? Do you put stuff in it once and then get from it until it's empty or do you put stuff in it a bit at a time? Or, can you do both? Also, does the queue actually get smaller as the threads feed from it or does it stay the same size and remember what stuff has been gotten from it already? Is this an appropriate way to create a queue of 100,000 items? url_queue = Queue.Queue(0) for url in urls: url_queue.put(url) I ask all of these questions because I find the Python documentation lacking, to say the least. Python is a most excellent language, but the docs are horrible! IMO, one can learn more about less sane languages such as Perl and PHP simply because their documentation is so well done... PHP especially. Don't get me wrong, I love Python, just hate it's documentation. For a lang that prides itself on ease of use and newbie-friendliness, Python should be ashamed of its module documentation Bart From ducky at osafoundation.org Mon Jun 7 23:57:51 2004 From: ducky at osafoundation.org (Ducky Sherwood) Date: Mon, 07 Jun 2004 20:57:51 -0700 Subject: yes, confirm Jing Jing to me (was: BayPIGgies: June 10, 7:30pm) In-Reply-To: <20040605143125.GA23049@panix.com> References: <20040605143125.GA23049@panix.com> Message-ID: <40C5393F.1010401@osafoundation.org> Aahz wrote: >Before the meeting, we'll continue the tradition started last month and >meet at 6pm for dinner, somewhere around downtown Palo Alto. Ducky >Sherwood is handling that; please send RSVPs to ducky at osafoundation.org >Discussion of dinner plans is handled on the BayPIGgies mailing list. >(I'm assuming we're going to Jing Jing again, but Ducky will post a >correction if I'm wrong. ;-) > > Just confirming that yes, we will go to Jing Jing again and that I will arrange the reservation. Please RSVP to me. It would be helpful if our headcount were a tad more reliable than last time; last time I had RSVPs for 16 and we ended up having more like 30. From tim.one at comcast.net Thu Jun 10 13:50:20 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jun 2004 13:50:20 -0400 Subject: reference counting and PyTuple_SetItem In-Reply-To: <40C888B2.7090804@unidata.ucar.edu> Message-ID: [Anne Wilson] ... > while () > { > pyRHost = PyString_FromString(rHost); You now own a reference to pyRHost. > Py_INCREF(pyRHost); /* ---> Note 3 <--- */ Now you own two references to it. > PyTuple_SetItem(pyFiveMinArgs, 4, pyRHost); Now you own one reference; PyTuple_SetItem stole one. > PyTuple_SetItem(pyOneHourArgs, 4, pyRHost); Now you own no references. You must not call Py_DECREF on pyRHost after this point (unless you obtain a new reference to it first). Apart from all that, you're cheating in ways that can hurt you: tuples are supposed to be immutable objects, and it's not strictly legal to mutate them inside the loop. You'd be much better off not trying to micro-optimize (i.e., build a new tuple each time you need one -- never use PyTuple_SetItem on the same index twice for a given tuple; the code as-is is too clever to ever work <0.9 wink>). From sholden at holdenweb.com Sat Jun 26 09:03:16 2004 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 26 Jun 2004 09:03:16 -0400 Subject: Help formatting a mysql query string In-Reply-To: References: Message-ID: <40DD7414.6080406@holdenweb.com> Pierre-Fr?d?ric Caillaud wrote: > >> sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" > > > - what are the "," doing here if you are trying to build a string ? > - you should use the python povided way which is better (yours looks > like php) > > cursor.execute( "INSERT INTO %(tb)s VALUES(%(a)s,%(b)s,%(c)s)", { > 'tb':tablename, 'a':first data, 'b':second data, etc... } Better still, create the query string with the right table name in it and parameter markers for the data: sqlquery = "INSERT INTO %s VALUES (%%s, %%s, %%s)" % tablename Supposing tablename is "customer" this gives "INSERT INTO customer VALUES (%s, %s, %s)" Then you can use the parameter substitution mechanism of the DB API to insert your data in there. Suppose datavalue is ("Steve", "Holden", 85) then you would do cursor.execute(sqlquery, datavalue) The problem with building the data portion of the statement is having to put the single quotes in around strings and escape any single quotes that might occur in the values you present. It's much easier to use the parameter substitution mechanism, even though that *can't* be used to change a table name in most SQL implementations. I've assumed for the sake of argument that you're using MySQLdb, which uses the "%s" paramstyle. mxODBC, for example, you'd use the "?" style, which makes building statements rather easier. One final comment: it's much safer to use the column names in INSERT, as in INSERT INTO customer (First, Last, age) VALUES ('Steve', 'Holden', 95) because that isolates you from a change in the column ordering, which can happen during database reorganizations when you insert a new column without thinking about the consequences. Just paranoia induced by years of experience, and therefore often effort-saving. regards Steve From tjreedy at udel.edu Tue Jun 1 10:37:05 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Jun 2004 10:37:05 -0400 Subject: question on garbage collection for python References: Message-ID: "David Stockwell" wrote in message news:BAY2-F108yo5EjEJi9D0002dfdb at hotmail.com... > Does Python leave things in an unknown state? If you include internal, system-dependent vars in 'state', yes. > say I do this in my python code > someFile = open('somefile' , 'r') > data = someFile.read() > someFile = 3 > > At this point I would hope python would know to destruct the prior reference > to someFile Rebinding the name 'someFile' to another object does that > by unallocating the memory (under the hood) and closing the file. When the last reference to an object disappears, (as happens above to the file object previously bound to 'someFile'), the interpreter *may* do some implementation-defined 'clean-up action'. > The questions here are: > If in my code if I forget to close a file, when will the file be closed? In current reference-counted CPython, immediately upon reference count dropping to 0. In garbage-collected-only Jython, whenever. It is controversial (Ie, discussed on several previous threads without agreement) whether or not it is 'legitimate' to depend on the current CPython behavior. > Is it when something goes out of scope? As far as I know, going out of scope is no different from explicit deletion of the binding or implicit deletion by rebinding. > Or will it close when the python session ends? CPython make some effort to cleanup without crashing. You can register your own onexit function. You can find more discussion in past threads (archives/Google). > If I define a class of somesort, is there a way I can have a destructor > method (like I would under C++ ?) Yes: __del__(self) - but be careful. 1). The time of it being called is still implementation dependent as described above for closing. 2). For CPython (don't know about Jython), presence of such a methods disables cyclic garbage collecion for instances of such a class because collector cannot know which del to call first and because calling Python-coded dels in middle of internal C-coded gc code too easily puts system in unstable state. > Thanks in advance, See archives/Google for more. Terry J. Reedy From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 21 10:20:37 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 21 Jun 2004 16:20:37 +0200 Subject: sys.stdout.write() question In-Reply-To: References: Message-ID: <2jo8trF1439a9U1@uni-berlin.de> Gian Mario Tagliaretti wrote: > Hi all, > > It is (I hope) a simple question, > I cannot figure out why sys.stdout.write() doesn't print immediatly the first > text in the small example below, but before it process the code in between > and then print both lines in one time. > > #!/usr/bin/env python > import sys, time > sys.stdout.write('write ') > time.sleep(3) > sys.stdout.write('this\n') > > if you try to run this, before it will wait 3 seconds and then print "write > this" in one time. Apparently the stdout "file" is buffered on your system. Have a look at file.flush() which could help you out. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From cpl.19.ghum at spamgourmet.com Wed Jun 2 02:51:17 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 2 Jun 2004 08:51:17 +0200 Subject: Could python help to create hundreds of NT accounts ? References: Message-ID: > Because there are about 1600 accounts, I'd really love it if there > was a way to do this with a script. Also google for tim golden wmi It is very helpfull to deal with windows accounts From flamingivanova at punkass.com Sat Jun 19 08:32:37 2004 From: flamingivanova at punkass.com (ivanova) Date: Sat, 19 Jun 2004 14:32:37 +0200 Subject: asyncore: limiting connections? References: <84n030ry10.fsf@redpeanut.com> Message-ID: On Sat, 19 Jun 2004 04:00:13 +0000, David Fisher wrote: > ivanova writes: > >> I'm using asyncore to test a list of proxies. I load the whole list >> and call asyncore.loop(). But I need to limit the amount connections >> because with a large list everything slows down a lot. How would I >> do this? >> >> Any help would be appreciated > > You question is so vague, I have no idea what you are talking about. Well I'm using asyncore to go through a list of proxies and connecting to them. I would like to know how to limit the number of connections uses at once by asyncore. From rupole at hotmail.com Tue Jun 1 19:43:07 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 1 Jun 2004 19:43:07 -0400 Subject: Could python help to create hundreds of NT accounts ? References: Message-ID: <40bd10b0_2@127.0.0.1> The Pywin32 windows extensions ( http://sourceforge.net/projects/pywin32/ ) contain functions to do just about any kind of NT account management, the win32net module in particular. Mark Hammond's book Python Programming on win32 is a very practical reference for this kind of task. hth Roger "google account" wrote in message news:e84f5d12.0406011439.57ec785f at posting.google.com... > Not really being a programmer, but thinking that there must be a > better way than to do it by hand and havign a friend who likes to tell > me that python is the answer to everything I am hoping. > > I have two NT4 domains, and I need to create instances of all the > account names from one in the other. > > All accounts need to have identical group memberships to each other, > and different passwords. > > I have in mind some program that will automatically generate a > password (I already wrote one of those) and write out to a csv file > username,passwd thgat we can refer to when the clients need to log > into their new account. > > Because there are about 1600 accounts, I'd really love it if there > was a way to do this with a script. > > I bought the Dietel How to Program Python book in an attempt to learn > this language, but it doesn't seem to have much in it related to NT > stuff like this. > > IF anyone has done anything like this, or knows how, I'd love to > hear from you. > > Cha! > > nemir (at) hot mail dot com From manatlan at online.fr Fri Jun 11 18:29:49 2004 From: manatlan at online.fr (marco) Date: Sat, 12 Jun 2004 00:29:49 +0200 Subject: dynamic import with heritage In-Reply-To: <21064255.0406111249.74894d3a@posting.google.com> References: <40c8d0d0$0$26780$636a15ce@news.free.fr> <40c9c54e$0$26793$626a14ce@news.free.fr> <21064255.0406111249.74894d3a@posting.google.com> Message-ID: <40ca325e$0$26814$626a14ce@news.free.fr> Peter Abel a ?crit : > marco wrote in message news:<40c9c54e$0$26793$626a14ce at news.free.fr>... > >>Gr?goire Dooms a ?crit : >> >>>In your dhuile package, you need bidon in your namespace. >>>This can be done by importing the module containing bidon's definition. >>>According to what you say ("here my main"), this module is __main__ . >>> >>>So a simple >>>from __main__ import bidon >>>class vidange(bidon): >>> pass >>>should do the job. >>> >> >>your statement doesn't work >>but it works, if i do : >>------------------------- >>import sys >>sys.path.append("../..") >>from main import bidon >>------------------------- >> >>does it exists a way to do it easier ? (i don't like this technick to >>append a path to sys.path) >> >> >>>If you want your dhuile package to be more portable, it would be better >>>to define bidon in a separate module (e.g. a "contenants.py" module ) >>>and get both your main and dhuile import it. >>> >>>Hope it helps. >>>-- >>>Gr?goire Dooms >>> >>>marco wrote: >>> >>> >>>>i try to make a dynamic import of a plugin which herits from another >>>>class >>>> >>>>here my main: >>>>------------------------------------------------------------------- >>>>class bidon: >>>> pass >>>> >>>>plugin = __import__( "plugins.dhuile" , globals(), locals()) >>>>------------------------------------------------------------------- >>>> >>>>And in the file /plugins/dhuile/__init__.py, i've got : >>>>------------------------------------------------------------------- >>>>class vidange(bidon): >>>> def test(): >>>> return "ok" >>>>------------------------------------------------------------------- >>>> >>>>python2.3 gives me : >>>>"__init__.py : NameError: name 'bidon' is not defined" >>>> >>>>i don't understand where is the mistake ?! >>>>(class "bidon" is in passed by the globals() ... but it seems >>>>__init__.py doesn't understand) >>>> >>>>anybody have got an idea ? >>>>thanx > > > Try: > > import plugins.dhuile as plugin > > class vidange(plugin.bidon): > def test(self): > ... > ... > Should work no ;-( ... it doesn't ... > Bonne chance. > Regards > Peter From akupries at shaw.ca Sat Jun 5 00:06:16 2004 From: akupries at shaw.ca (Andreas Kupries) Date: Sat, 05 Jun 2004 04:06:16 GMT Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <10c12igm2nsl4e9@corp.supernews.com> Message-ID: <87oenyd57t.fsf@bluepeak.home> Jacek Generowicz writes: > claird at lairds.com (Cameron Laird) writes: > > > Also related http://wiki.tcl.tk/Scripted%20Compiler -- Sincerely, Andreas Kupries Developer @ Private ------------------------------------------------------------------------------- } From miki.tebeka at zoran.com Wed Jun 16 05:31:30 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 16 Jun 2004 11:31:30 +0200 Subject: Learning Python - Resources Needed In-Reply-To: References: Message-ID: <20040616093130.GB616@zoran.com> Hello Phyrestang, > Hi there. I've decided that my first real language I want to learn to > program in is Python. I've been using the Python tutorials at > Python.org, but I'm looking for something a little more in depth. > > Can anyone recommend any good books for a someone new to python, and > to programming? I should mention that while I am new, I do catch on > quickly, so I'm not looking for a book that gives just the bare > basics. http://www.python.org/topics/learn/ Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From skchim0 at engr.uky.edu Tue Jun 22 16:17:54 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Tue, 22 Jun 2004 16:17:54 -0400 Subject: FFT with Python Message-ID: <012201c45896$002e0090$559ea380@D4XN6B41> Hi All, Did anyone compute FFT - Fast Fourier Trans using Python ? I am looking for a simple Python package which can do spectral analysis for me. Can someone help me get such a package ? Thanks Regards, Satish Chimakurthi -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidf at sjsoft.com Thu Jun 17 08:32:14 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 17 Jun 2004 14:32:14 +0200 Subject: Just testing In-Reply-To: References: Message-ID: Peter Hansen wrote: > Mitja wrote: > >> Michael Lauzon >> (news:mailman.25.1087341507.21521.python-list at python.org) wrote: >> >>> I am just testing, as I need to create a filter. >> >> >> Use alt.test, then > > > Sounds like he probably gets this group as email through the > mailing list, but it's still rude to impose on the thousands > of other readers (tens of thousands?) for his own minor > convenience like that. > In this case, the best thing to do is to ask a real question that you're not actually interested in and that will be easily answered, or start a flamewar :-) The benefit of the latter is that you get *lots* of posts to test your filter on... David From jceasar at tmp.org Sun Jun 20 14:29:03 2004 From: jceasar at tmp.org (jceasar at tmp.org) Date: Sun, 20 Jun 2004 23:59:03 +0530 Subject: Hi Message-ID: The access is open !!! password -- 80081 -------------- next part -------------- A non-text attachment was scrubbed... Name: TextDocument.zip Type: application/octet-stream Size: 22113 bytes Desc: not available URL: From michele.simionato at poste.it Thu Jun 10 16:30:58 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 10 Jun 2004 13:30:58 -0700 Subject: exceptions References: <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Message-ID: <95aa1afa.0406101230.2c7692d0@posting.google.com> Jacek Generowicz wrote in message news:... > I'm pretty sure that Scheme allows you > to do this without any restriction. Indeed. I knew it was possible to redefine macros but I did not expect it was possible to redefine "built-in" "globally" so easily: (define-macro (if c . args) ''surprise!) (display (if #t 'true 'false)) ;=> surprise By "globally" I mean that everything that depends of "if" will be modified: (display (when #t 1)) ;=> surprise which is a recipe for disasters. So I see the logic of the restriction in Common Lisp. Michele Simionato From haim at babysnakes.org Mon Jun 28 05:40:48 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Mon, 28 Jun 2004 12:40:48 +0300 Subject: sending signals to the calling function In-Reply-To: References: Message-ID: <1088415648.4727.6.camel@parker.babysnakes.org> On Mon, 2004-06-28 at 12:24, Tim Golden wrote: > | I have a function that receive a list of files and creates a zip from > | these files. I want it to send signal to the calling function with the > | name of the file it currently compressing. is there a way to do this > | (without threads)? > > Of course, just pass in a callback function, and call that > whenever a file is being compressed. Alternatively, make > the zipper-upper a generator which yields its current filename: > > > > import os, sys > import zipfile > > def zipup (zip_filename, list_of_files): > archive = zipfile.ZipFile (zip_filename, "w") > for filename in list_of_files: > yield filename > archive.write (filename) > archive.close () > > if __name__ == '__main__': > import glob > file_pattern = os.path.join (sys.path[-1], "*") > list_of_files = [f for f in glob.glob (file_pattern) if os.path.isfile > (f)] > for zipping_file in zipup ("test.zip", list_of_files): > print "About to zip", zipping_file thanx, that's exactly what I needed. Bye -- Haim -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From ivoras at __geri.cc.fer.hr Mon Jun 21 17:23:41 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Mon, 21 Jun 2004 23:23:41 +0200 Subject: Unicode perplex In-Reply-To: <10deickd7vpmo7a@news.supernews.com> References: <10deickd7vpmo7a@news.supernews.com> Message-ID: John Roth wrote: > The problem is that I've got a normal string where > the byte stream is actually UTF-8. How do I turn > it into a Unicode string? Remember that the trick does str2 = str.decode('utf-8') work? -- What part of "Ph'nglui mglw'nath Cthulhu R'lyeh wgah'nagl fhtagn" don't you understand? From graeme at osdc.com.au Sun Jun 27 20:47:18 2004 From: graeme at osdc.com.au (Graeme Cross) Date: Mon, 28 Jun 2004 10:47:18 +1000 Subject: ANN: Talk deadline for Python track at OSDC 2004 is closing Message-ID: <1088383638.21238.199276427@webmail.messagingengine.com> A reminder that the deadline for submitting a paper proposal for the Python track at the Australian Open Source Developers Conference is rapidly approaching (technically it is June 28, but a day or two late isn't going to hurt :) For details on submitting a paper, see: http://www.osdc.com.au/papers/call_for_papers.html For information about the Python track, and OSDC in general, see: http://www.osdc.com.au/python/index.html http://www.osdc.com.au/ Regards Graeme -- Graeme Cross, graeme at osdc.com.au OSDC 2004: The Australian Open Source Developers' Conference From manoj_tamhankar at hotmail.com Tue Jun 15 14:48:28 2004 From: manoj_tamhankar at hotmail.com (manoj_tamhankar at hotmail.com) Date: Tue, 15 Jun 2004 11:48:28 -0700 Subject: Administration Message-ID: Bad Gateway: The message has been attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: data.txt .scr Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From oliver.schoenborn at utoronto.ca Fri Jun 11 18:21:29 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Fri, 11 Jun 2004 18:21:29 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: "Peter Hansen" wrote in message news:PfednezhqfRRjlfdRVn-vg at powergate.ca... > Humpdydum wrote: > > > The object actually *does* know when to dispose of itself: when its ref > > count goes to zero. Naturally, if you have an object that wraps a resource > > that needs cleanup, it goes without saying that that object shouldnt' be > > referenced all over the place; rather, there should be only one ref to it, > > in the function that instantiates it, and that's all. Then when the function > > exits, the object sees ref cnt=0 and knows to cleanup after itself. > > This is an unrealistic requirement. It implies that all access > to some resource must occur within a single function, which is > too great a limitation for many real applications. As long as only one ref left on function exit, there is no limitation of access. Oliver From opengeometry at yahoo.ca Thu Jun 10 17:34:04 2004 From: opengeometry at yahoo.ca (William Park) Date: 10 Jun 2004 21:34:04 GMT Subject: [script] dis/assembling mbox email Message-ID: <2is2ebFr1sbvU1@uni-berlin.de> Crossposted to Python group, because I think this is cleaner approach. :-) Time to time, I need to - extract main header/body from a MIME email, - parse and extract multipart segments, recursively, - walk through the email tree, and edit/delete/add stuffs - regenerate new MIME email. You can edit the file manually, but it's difficult to keep track of where you are. So, I wrote shell scripts (included below my signature): 1. unmbox.sh -- to extract email components into directory tree 2. mbox.sh -- to generate email from directory tree So, you can "walk" through MIME email by simply "walking" through directory tree. Analogy is 'tar' file. You extract files into directory tree, and you create tarball from the directory tree. Or, if you are using Slackware, analogy is 'explodepkg' and 'makepkg'. Usage are unmbox.sh dir < email mbox.sh dir > email 'unmbox.sh' will extract email components into directory tree. Header and body will be saved respectively as 'header' and 'body' files. If it's MIME, then each multipart segment will be saved as 'xx[0-9][0-9]' file, and it will in turn be decomposed recursively. In reverse, 'mbox.sh' recursively walks the directory tree, and assembles email components into mbox-format. Strictly speaking, MIME boundary pattern consists of any number of [A-Za-z0-9 '()+_,./:?-] not ending in space. And, boundary line in the message body consists of \n--pattern\n \n--pattern--\n where 'pattern' is the boundary pattern assigned from Content-Type: header. For the sake of sanity, 1. The script recognizes only boundary="..." as MIME boundary parameter, ie. it must be double-quoted and no spaces around '='. 2. Only lines consisting of '--pattern' or '--pattern--' are recognized as boundary lines, because Formail puts blank line (if doesn't already exist) at the top and bottom of email body, undoing '\n' prefix/suffix anyways. 3. '.' needs to be escaped for Sed and Grep, and '()+.?' needs to be escaped for Csplit and Egrep. Use at your risk, and enjoy. -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. ----------------------------------------------------------------------- #! /bin/sh # Usage: unmbox.sh dir < email [ ! -d $1 ] && mkdir $1 cd $1 cat > input formail -f -X '' < input > header # no blank lines formail -I '' < input > body # blank lines at top/bottom if grep -o "boundary=\"[A-Za-z0-9 '()+_,./:?-]*[A-Za-z0-9'()+_,./:?-]\"" header > boundary; then . boundary eboundary=`sed 's/[()+.?]/\\&/g' <<< "$boundary"` csplit body "/^--$eboundary/" '{*}' # xx00, xx01, ... for i in xx??; do if head -1 $i | egrep "^--$eboundary\$" > /dev/null; then sed '1d' $i | unmbox.sh $i.mbox fi done else rm boundary fi ----------------------------------------------------------------------- #! /bin/sh # Usage: mbox.sh dir > email cd $1 sed '/^$/ d' header # NO blank lines in header if [ -f boundary ]; then . boundary echo for i in xx??.mbox; do echo "--$boundary" mbox.sh $i done echo "--$boundary--" echo else [ "`head -1 body`" ] && echo # blank line at top cat body [ "`tail -1 body`" ] && echo # blank line at bottom : # dummy, so that return code is 0 fi ----------------------------------------------------------------------- From dooms at info.LESS.ucl.SPAM.ac.be Sun Jun 13 03:46:10 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Sun, 13 Jun 2004 09:46:10 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: References: Message-ID: <40cc065a$0$41764$5fc3050@dreader2.news.tiscali.nl> Tim Peters wrote: > [Gr?goire Dooms] > >>If speed is the matter, go for C: >> >>with the GNU MP library use >>void mpz_pow_ui (mpz_t rop, mpz_t base, unsigned long int exp) and >>char * mpz_get_str (char *str, int base, mpz_t op) > > > There are some GMP wrappers for Python. Using Marc-Andre Lemburg's mxNumber > wrapper (which is maximally convenient for me on Windows, since it includes > a precompiled-for-Windows GMP), the OP's task is spelled like so: > > >>>>from mx.Number import * >>>>Integer(2)**24036583 - 1 > < snip ... > > Lessons to take home : > > + The speed of bigint operations can be data-dependent in implementation- > specific ways (Python's native pow() ran circles around GMP's for this > particular data). > > + That changes over time (recent Pythons are much faster at some of these > tasks than the one you used). > > + A better algorithm is always the better answer (computing in decimal > from the start allows pure Python to run circles around GMP computing > in binary then forced to do a non-trivial 24-million bit base > conversion). Could you tell us more about the computational complexity of that operation in base 10 compared to the same one in base 2 and base2->base10 conversion ? -- Gr?goire Dooms From arcane at deepfort.com Tue Jun 15 12:45:19 2004 From: arcane at deepfort.com (Arcane) Date: Tue, 15 Jun 2004 17:45:19 +0100 Subject: Python IDLE GUI In-Reply-To: <1082403283.261220@sj-nntpcache-5> References: <1082403283.261220@sj-nntpcache-5> Message-ID: <40CF279F.6040207@deepfort.com> Paul Dankoski wrote: > I checked the INSTALL.LOG file. The only thing that possibly looks > fishy is: > > Date/Time: Following file not copied. > File Overwrite: C:\WINNT\system32\msvcirt.dll | 05-08-2001 | 06:00:00 > | 6.1.8637.0 | 77878 | 571d0e6 > File Overwrite: C:\WINNT\system32\msvcrt.dll | 06-19-2003 | 12:05:04 | > 6.1.9844.0 | Those would be visual c runtime files (well, afaik msvcrt is), which is probably not the problem - see below. If you have a curious nature, and must know whether replacing those dlls would help, you could drop the required copies of the correct dlls(ie the ones that weren't installed above) in the application folder with idle, and leave the system32 directory alone, since iirc win 2000 allows for keeping app-relevant copies of the library in the application directory, and it will look there first for dlls the app wants. Backing up and replacing them in the system32 dir would only have the same effect on IDLE but also might mess up other applications by replacing them with a probably older version. > Hello. I downloaded and installed Windows Python-2.3.exe. > The install appears to be successful. There is a Start menu > item showing "Python 2.3" --> "IDLE (Python GUI)". > > When I select this, nothing appears on my Windows 2000 screen. I shouldn't take it personally if the dll's (or other possible issues you might notice) aren't the problem, there seem to be quirks with Python2.3/Tkinter apps on the NT-type windowses, often amounting to an inexplicable failure to do anything at all even on a simple blah=Tkinter.Tk(). That's even outside of IDLE, which can also stuff up use of Tkinter itsself - it certainly clashes with other Tkinter apps on win32, if anybody knows of the reason/s for the problems with win32/Python23/Tkinter, I'd be interested to know. Incidentally, a quiet hello to the list, please forgive my antisocial lurking/uninvited posting :) Arca. PS: All this is ignoring redundant statements of the obvious re: the shortcut being correct, or closing other TK apps before running IDLE. From miki.tebeka at zoran.com Mon Jun 14 06:58:10 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 14 Jun 2004 12:58:10 +0200 Subject: help In-Reply-To: References: Message-ID: <20040614105810.GL1124@zoran.com> Hello Ru, > does anyone have an algorithm (in python) for an LU decomposition > method? really need it. thanks http://www.catb.org/~esr/faqs/smart-questions.html Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From hyperbob at walla.com Thu Jun 24 12:31:40 2004 From: hyperbob at walla.com (hyperbob) Date: 24 Jun 2004 09:31:40 -0700 Subject: processes Message-ID: Hello, I have a simple little problem. I am writing a program that consists of several distinct processes (GUI, database, etc.). I ran into problems trying to make them all run in parallel and independently. I wanted to write a script that will get them all up and running, but it does not seem to be possible without either killing the parent process or depriving the child processes of a console window. This is essentialy what I want: scripts = ["monitor.py", "server.py", "test2.py"] for script in scripts: run_and_forget_about_it("python.exe " + script) Anyone knows who to implement run_and_forget_about_it? Thanks, Bob. From python-url at phaseit.net Tue Jun 8 18:13:08 2004 From: python-url at phaseit.net (Peter Otten) Date: Tue, 08 Jun 2004 22:13:08 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 8) Message-ID: <10ccefk197cpr4d@corp.supernews.com> QOTW: "With so many languages being written these days, someone [is] bound to name [his] language 'Right' simply because all the other words are taken." -- Tor Iver Wilhelmsen QOTW: "Why did no one invent Python before?" -- Jonathon McKitrick If you are new to Python and would rather write a few more statements than bite the bullet and build your own class, then relax, Robert Brewer shows how to create a dictionary with a default value for missing keys - Chris demanded "Perlish behaviour" - in no more than three lines. http://groups.google.com/groups?selm=mailman.563.1086294655.6949.python-list%40python.org David Stockwell stumbles over a line of code designed for sharing version information between a Python module and the revision control system. http://groups.google.com/groups?th=eb1c3fc8589f6023 David Goodger anounces a cheat sheet for reStructuredText for those who already have some knowledge of the format. http://docutils.sourceforge.net/docs/user/rst/cheatsheet.txt Duncan Booth motivates class methods using the classic OO example, a hierarchy of shapes. http://groups.google.com/groups?&selm=Xns94FB6E2B335A3duncanrcpcouk%40127.0.0.1 Axel Scheepers has converted a Perl script to Python and now wants a speed boost. The more concrete proposals show the tendency to make the code both shorter and more elegant. Let's hope it will be fast enough, too. http://groups.google.com/groups?th=4c7acd0fdcb2190d Speaking of speed, some recipes appear in the newsgroup time and again, and Irmen de Jong has set up a Wiki page to collect common wisdom. You are invited to participate. http://www.razorvine.net/python/PythonSpeed Atul Varma has written a minimal C compiler in Python - the news is brought to our attention by Tim Freeman. The extension of the tool chain fosters plans of world domination in an otherwise humble community. Read the full thread here http://groups.google.com/groups?th=acc961b08f1cb88a or go directly to the source at http://people.cs.uchicago.edu/~varmaa/mini_c/ So why did no one invent Python before? The question spawns an interesting thread and is not as silly as the questioner fears, as Erik Max Francis proves with his profound answer. http://groups.google.com/groups?selm=40BE621C.97EEC2AA%40alcyone.com ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From rmb25612 at yahoo.com Sun Jun 13 16:34:43 2004 From: rmb25612 at yahoo.com (Richard James) Date: 13 Jun 2004 13:34:43 -0700 Subject: Searching for the best scripting language, Message-ID: <2c60f0e0.0406131234.49b485ec@posting.google.com> Are we looking at the scripting world through Python colored glasses? Has Python development been sleeping while the world of scripting languages has passed us Pythonista's by? On Saturday Slashdot ran this article on the "best" scripting languages. http://developers.slashdot.org/developers/04/06/12/2125229.shtml?tid=126&tid=156 "Folks at the Scriptometer conducted a practical survey of which scripting language is the best. While question like that is bound to generate flamewars between the usual Perl vs PHP, Python vs Perl, VBScript vs everything crowds, the Scriptometer survey is practical: if I have to write a script, I have to write it fast, it has to be small (less typing), it should allow me to either debug itself via a debugger or just verbose output mode. sh, Perl and Ruby won the competition, and with the difference of 1-2 points they were essentially tied for first place... Interesting that ICFP contests lately pronounced OCaml as the winner for rapid development." Scriptometer site: http://merd.sourceforge.net/pixel/language-study/scripting-language/ Needless to say, the Ruby site was Slashdot-ed today. What points are the Scriptometer survey missing, in regards to the ease of use and beauty of the Python language? Or should I convert my code base to Ruby and or OCaml? :) Let the rabid "in defense of Python" flames begin! -- R.J. From klachemin at home.com Sat Jun 26 19:18:27 2004 From: klachemin at home.com (Kamilche) Date: 26 Jun 2004 16:18:27 -0700 Subject: i have a big dictionary...:) References: Message-ID: <889cbba0.0406261518.1550296@posting.google.com> gabor farkas wrote in message news:... Have you considered keeping only the key in memory, plus an offset of its location in the text file? So it would look like: key offset key1 14 key2 275 key3 64004 Then as you need to access individual lines, hop to the right spot in the file based on the offset, and read the line. From elbertlev at hotmail.com Sat Jun 26 18:54:43 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 26 Jun 2004 15:54:43 -0700 Subject: Case insensitive dictionary? References: <9418be08.0406250921.71f4eba4@posting.google.com> Message-ID: <9418be08.0406261454.3c067507@posting.google.com> Thanks! In my case I know for sure, that keys are strings. So I fill the dictionary with keys as they come to me from the source (preserve the case). Once the dictionary is filled, it is a "READ ONLY" object. In other words: there is no group operation writing it back to the source and there is no reason to modify it. Is there something wrong with this code: class RegValuesDict(dict): def __init__(self): pass def __getitem__(self, k): try: tmpk = k.strip().lower() for key in self.keys(): if key.strip().lower() == tmpk: return dict.__getitem__(self, key) except: pass return None def has_key(self, k): try: tmpk = k.strip().lower() for key in self.keys(): if key.strip().lower() == tmpk: return True except: pass return False ######## regdict = RegValuesDict() regdict["keyname1"] = "value1" regdict["keyname2"] = "value1" val1 = regdict["keyName1"] if val1 == None: print "Too bad" or if not regdict.has_key("keyName1"): print "Too bad" else: val1 = regdict["keyName1"] or val1 = regdict.get("keyName1", "good value") Doing this in such a way, I remove the need for trapping exceptions in every line of the client code. Again: is there something wrong with this approach? From dmq at gain.com Wed Jun 23 17:51:53 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 23 Jun 2004 14:51:53 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: <0vtjd0pakf9haehvhh753otgk48k36kre0@4ax.com> On Wed, 23 Jun 2004 07:30:34 -0400, "Colin J. Williams" wrote: > > >David MacQuigg wrote: >> On Sun, 20 Jun 2004 14:48:23 -0400, "Colin J. Williams" >> wrote: >> >> >>>I have yet to wrap my mind around decorators. >> >> >> Decorators are very simple. They are just a way to provide different >> forms of methods, without introducing a new keyword, or some other >> more awkward syntax. >> >> Say you wanted to define a method that didn't have 'self' as its first >> argument. You could add a new keyword to the language: >> >> noself methodA(x,y): >> return x + y >> >> Or you could add a "decorator" to the existing syntax: >> >> def methodA(x,y) [noself]: >> return x + y >> >> Change 'noself' to 'staticmethod' and you have one of the current >> proposals in PEP318. >> >> Don't get distracted by 'staticmethod' and other mumbo-jumbo >> terminology, and you should have no problem with decorators. > >OK, I'll ignore 'staticmethod', but could you tell me how > > def methodA(x, y) [noself]: > return x + y > >differs in substance from > > def methodA(self, y): > return self + y > >or > def methodA(x, y): > return x + y > >What has been gained by the added syntactic clutter? The example above was to explain decorators, not justify them. If they were to be used *only* to clean up the current syntax for staticmethod, then I would say a better alternative would be to get rid of the need for a separate staticmethod form entirely. ( See the thread "Unification of Methods and Functions" for a thorough discussion of this topic.) Are decorators on functions necessary? I can't think of a simpler or more consistent way to handle all the variations proposed in PEP 318. Assuming that we *will* have a decorator syntax with many options, I think that making [staticmethod] one of those options is appropriate. I would still prefer a word more meaningful to new users, however. The rational I have heard for "staticmethod" is so contorted, it is not worth repeating. -- Dave From indigo at bitglue.com Wed Jun 2 14:26:07 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 2 Jun 2004 14:26:07 -0400 Subject: scoping questions In-Reply-To: References: Message-ID: <20040602182607.GA26852@unununium.org> In Python, all objects are represented by structures allocated on the heap. Whenever you pass python objects around in python, you are actually passing references to those objects. However, python has a notion of objects being "mutable" or "immutable". Some objects are mutable, such as lists, dictionaries and classes. Others are immutable, such as strings, tuples, and integers. A namespace in python is implemented internally as a dictionary. There are ways to access this dictionary directly from python, although I'd have to read the manual to see how, as it's not something you need to do often. A function has its own namespace. When you have something such as this: def fu(bar): bar = 3 you are not derefrencing 'bar', and assigning 3 to it. Rather, you are changing the namespace of fu (a dictionary, actually) to map "bar" to 3. This explains your first example. However, if you use a mutable type, as you did with a file in the latter example, it is possible that an object passed as a parameter might be modified when passed as a parameter to a function. Using lists as an example: def fu(bar): bar.append(1) l = [] fu(l) print l # l = [1] In this case, 'bar' is a reference to 'l'. By calling append(), 'bar' remains a reference to 'l', but the contents of 'l' are changed. Because 'l' and 'bar' reference the same object, the changes are visible in both places. This is possible because a list is a mutable type. On Wed, Jun 02, 2004 at 05:47:31PM +0000, David Stockwell wrote: > Hi, > > Another of my crazy questions. I'm just in the process of learning so bear > with me if you can. I actually ran it.... with two test cases > > TEST CASE 1: > Say I have the following defined: > --- beginning of code snippet ---- > > def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > > aFile = open('/tmp/test','r') > me(aFile) > data = aFile.read() > print data > > ------ end of code snippet ---- > my test file has a sentence 'This is a test of the /tmp/test file' > > When I run it I observed this output: > hello world > This is a test of the /tmp/test file > > Now what this means to me and this is where I need your help: > > When I call the 'me' function, its passing a reference to my original aFile > variable. > Inside the me function, I'm guessing it is now a new reference to the same > original aFile contents. When I assign it to a simple string, it simply > changes the local reference to point to that string. Since its a copy of > the reference, it doesn't affect the caller's value. > > In essence if i understand correctly > > At the global scope I have > > variable aFile that points to an instance of a 'file' > > Inside the me function scope I have > a parameter named aFile that is a local copy of the original reference of > what global::aFile was pointing to. > Essentially local::aFile is pointing to a file object > > At this point I have two references to the file object. > > When I assign the new value to aFile (local) it simply does the assignment. > The global reference is untouched. > > I would sort of expect this behavior as I am not returning anything > > If test #1 is true, then test case 2 boggles me a bit > > TEST CASE 2: > ------- > def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > def me2(dog): > """ > Note I am testing scoping > """ > print "Inside me2" > dog.close() > > > aFile = open('/tmp/test','r') > me(aFile) > data = aFile.read() > print "test1", data > aFile.close() > aFile = open('/tmp/test','r') > > me2(aFile) > print "test2", aFile.read() > ===== > > It bombs out on the last line because aFile was closed in the function > 'me2'. > > Perhaps the way to explain it is that Inside me2 when my copy of the > original reference is made, I have a global and local variable both > referencing the same 'object'. I am able to do operations in the local > me2 scope and have them effect the behavior of the global scope. > > Its just a bit confusing because python is apparently smart enough to > realize that my action on the local reference hasn't redefined the > capability of the global so it has allowed this to occur on the actual > global file referenced object. (as opposed to just a local copy). And I > didn't return anything.... > > > I'm just confused a bit here.... Perhaps someone can clarify > > Thanks > > David > ------- > Tracfone: http://cellphone.duneram.com/index.html > Cam: http://www.duneram.com/cam/index.html > Tax: http://www.duneram.com/index.html From __peter__ at web.de Thu Jun 17 04:56:57 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 10:56:57 +0200 Subject: Python interceptor package References: Message-ID: Fritz Bosch wrote: > What I'm looking for is an Interceptor class whose > constructor would interpose its (callable) instance > between a caller and a specified function or method, > and whose 'destroy' method would remove the interposition. > I have actually started to experiment with an Interceptor > class, whose constructor modifies the __dict__ of a specified > class, to 'wrap' its (callable) instance around the specified > method. > So, comments are invited! Maybe there isn't such a package because the following is often sufficient: def wrap(method): def wrapped(self, *args, **kw): print "begin" method(self, *args, **kw) print "end" return wrapped class Test(object): def method(self, name): print "method(%r)" % name t = Test() t.method("pure") Test.method = wrap(Test.method) t.method("wrapped") Peter From hungjunglu at yahoo.com Thu Jun 10 10:20:56 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 10 Jun 2004 07:20:56 -0700 Subject: exceptions References: <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> <95aa1afa.0406092138.338568b2@posting.google.com> Message-ID: <8ef9bea6.0406100620.7de79250@posting.google.com> michele.simionato at poste.it (Michele Simionato) wrote: > Sorry for the previous message, but I couldn't resist the temptation > to mock you. So you may realize how irritating certain statements can > be. Ha. We are in newsgroups. No one pays money to get answers. Whether someone wants to give you answers or not, it's up to them. If someone answers, you are grateful. If no one answers, tough luck, that's life. Move on. You can never force anyone to teach you. Irritating, why? Are other people your slaves? Why should anyone spend their time to educate you? That just does not work. It's a free world. On the other hand, you are welcome to ask other people, ask as many people as you can. I have helped hundreds of people in this newsgroup, often posting detailed code where no one else did. So I have been more than nice and helpful to many people, and you probably know that. If you look at the Lisp group, you'll understand what I mean. :) By the way, I posted there before I posted to Python. Others have provided more complete and detailed answers. At this modern age, one not only needs to learn, but one needs to learn how to learn. Meta-learning, if you wish. :) regards, Hung Jung From oliver.schoenborn at utoronto.ca Thu Jun 10 13:42:03 2004 From: oliver.schoenborn at utoronto.ca (Humpdydum) Date: Thu, 10 Jun 2004 13:42:03 -0400 Subject: does python have useless destructors? References: Message-ID: "David Turner" wrote in message news:e251b7ba.0406100011.39a795e1 at posting.google.com... > > This makes me sad. But there is some hope in the following pattern, > although it can be quite awkward: > > def with_file(fname, mode, oper): > f = open(fname, mode); > try: > oper() > finally: > f.close() > > Of course, this can very quickly turn your code into so much > functional goo. That's not necessarily a bad thing, as Lisp > programmers can attest... But it's still not quite as powerful as > RAII. I tried out a technique yesterday that shows it's possible to have reliable 'finalization' in Python, and not surprisingly it relies on try/finally (how else...), BUT user no longer has to use this construct (it's automatic). I posted on python-dev to get feedback about whether or not the technique could be put right into the interpreter, which would improve performance and robustness. In any case, the module is currently called *scope*. The usage idiom looks like (pythonic pseudo-code): class YourClass(scope.NeedsFinalization): ... nothing else to change, except: def _finalize(self): ... do the clean-up def yourFunc(...): # do stuff that uses one or more instances of YourClass # that need some form of "clean-up" ... yourFunc = scope.ScopeGuarded(yourFunc) # do some calls to yourFunc(); whether exception or normal return, # your instances are guaranteed to be cleaned-up before returning yourFunc(...) I used the term 'finalization' even though technically not rigorous. Conceptually that's what it is because after the call to _finalize() the object should be assumed in an unusable state. Some advantages over try/finally: - Coder of class makes explicit by base class that finalizaiton is important, no need to remember to document. - User of class knows just by looking at class def, can't overlook a sentence saying "call this-that when done with object" - Some error checking can be done to decrease likelyhood of user forgetting the scope-guarding rebind or of asking for finalization before refcount 0. - Recursive functions need no try/finally There are a couple of limitations in the current implementation (e.g. make it work for global scope exit, and methods, don't know yet about thread safety) but you get the idea. The *scope* module would make it trivial to create some modules that wrapped some of the standard python library classes in scope.NeedsFinalization. If you'd like to comment on the code send me an email and I'll email scope.py back to you. Oliver From michael at foord.net Tue Jun 8 09:10:00 2004 From: michael at foord.net (Fuzzyman) Date: 8 Jun 2004 06:10:00 -0700 Subject: Passing parameters using **kargs References: Message-ID: <8089854e.0406080510.606df643@posting.google.com> tkpmep at hotmail.com (Thomas Philips) wrote in message news:... > I want to access parameters that are passed into a function using the > **kargs idiom. I define f(**kargs) via > > def f(**kargs): > print kargs > . > . > > the keyword arguments are converted to a dictionary, so that if I type > f(a=1, b=2, c=3) > > the function prints > {'a': 1, 'b': 2, 'c':3} > > Now assume the function has three variables a, b and c to which I want > to assign the dictionary's values of 'a', 'b' and 'c'. How can I > assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I > be trying to construct a string representation of each variable's name > and using that as a key, or am I just thinking about this the wrong > way? > > Thomas Philips MY reading of what you say is - I have three variable a, b and c.. and a dictionary, kargs, with keys 'a', 'b' anc 'c'. I want to assign the contents of kargs to the three variables. The specific case is surely ? : a = kargs['a'] b = kargs['b'] c = kargs['c'] or is it the more general case you're after ? I think I'm misunderstanding you I'm afraid.... Fuzzyman http://www.voidspace.org.uk/atlantibots/pythonutils.html From mark at prothon.org Wed Jun 16 05:00:07 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 16 Jun 2004 02:00:07 -0700 Subject: mutable default parameter problem [Prothon] References: <200406152201.20003.troy@gci.net> <200406152350.51601.troy@gci.net> Message-ID: Troy Melhase wrote: > You're right, it's not a newbie problem. It's a problem for everyone > who hasn't bothered to read the documentation. Having a language with features intuitive enough to require less trips to the documention is a laudable goal. Of course you know what I really meant was what I said in the original posting. Even experts have to write extra code to get around this problem The following is a common piece of Python code that is a problem work-around: def f( a = None ): if a == None: a = [] > Uncool? Do you mean "uncool" as in "forking a language and > distracting a bunch of folks ... Evolution works by forking. If you have some problem with Prothon then let's discuss it. Don't hide your problem with Prothon behind your discussion of this thread's topic. > (And by the way, one definition of love means to accept what we > perceive as deficiencies. So maybe you don't love Python as dearly > as you love the idea of Python.) You can love something and still want to improve it. Don't tell my wife I said this :-) >> That count is not accurate. Fixing this will not break every use of >> [] as a default formal param. . I can think of many >> other cases where it is legal to use []. The only case I can think of that would >> break would be the idiom we disagree on above. If I am wrong, then show >> me other cases. > > Oh, but it will. You'll have to read and comprehend every function > definition that uses mutable default arguments to start to prove > otherwise. I'm not sure I follow you. I'm saying that you only have to show me one or two cases for me to realize I'm wrong. > Maybe you should take a step back and look at what you're doing. > From my perspective, you're adding a whole lot of additional rules to > the language, and a completely different way of doing things. That's > fine, and more power to you, but if you're bent on changing so much, > you should stop looking to c.l.p to validate your ideas. I'm not looking for validation, just a reasonable discussion of the issue of which of the three methods to use to fix the problem. You are the one that started the seperate discussion as to whether it should be fixed or not. By the way, Prothon is removing a lot of rules, not adding them, by it's simplification in almost all areas. > (Of course, I don't speak for the Python community or c.l.p, but I am > horrified nonetheless with what you're doing. Please forgive me if > I've been disagreeable while disagreeing.) No problem. I am quite thick-skinned. I also apologize if I have been harsh. I am sorry you are so upset that someone is daring to make a changed Python. I expected this reaction from many Python afficionados who may love the warts as much as the beauty. I was surprised that Prothon was received as warmly as it was here at c.l.p. All you have to do is ignore any postings with subjects that end in [Prothon]. From michael at foord.net Tue Jun 22 05:27:49 2004 From: michael at foord.net (Fuzzyman) Date: 22 Jun 2004 02:27:49 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <8089854e.0406220127.c59d2e9@posting.google.com> Mediocre Person wrote in message news:<513d6f09f74eb423c810692fb7bb1f46 at news.teranews.com>... > Well, after years of teaching grade 12 students c++, I've decided to > make a switch to Python. > > Why? > > * interactive mode for learning > * less fussing with edit - compile - link - run - debug - edit - > compile - link - run -..... > * lots of modules > * I was getting tired of teaching c++! Bored teacher = bad instruction. > * thought about tcl/tk but it's just too different syntactically > (for me, not my students!) after so much time with languages like > c++/ada95/pascal/BASIC/Fortran, etc. > * it appears to be FREE (which in a high school environment is > mightily important) from both python.org or activestate.com. I think I > like activestate's ide (under Win98) a bit better than idle, but your > comments/suggestions? > > I've decided to give John Zelle's new book a try as a student > textbook--it's as good an introductory CS book in any language I've > seen. I've done a couple of small projects with tkinter, like what I > see, and would like to introduct my students to it, although Zelle > doesn't make use of it in his text. > > So, what pitfalls should I look out for in introducing Python to > students who have had a year of Visual BASIC? I don't know anything about visual basic.... but the difference between an object and a name bound to that object bites *every* python newbie at some point..... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html > > Regards, > > chackowsky dot nick at portal dot brandonsd dot mb dot ca <-- have the > spambots figured this one out yet? From michael at foord.net Mon Jun 7 08:23:19 2004 From: michael at foord.net (Fuzzyman) Date: 7 Jun 2004 05:23:19 -0700 Subject: My Experiences Subclassing String Message-ID: <8089854e.0406070423.5d2d1d71@posting.google.com> I recently went through a bit of a headache trying to subclass string.... This is because the string is immutable and uses the mysterious __new__ method rather than __init__ to 'create' a string. To those who are new to subclassign the built in types, my experiences might prove helpful. Hopefully not too many innacuracies :-) I've just spent ages trying to subclass string.... and I'm very proud to say I finally managed it ! The trouble is that the string type (str) is immutable - which means that new instances are created using the mysterious __new__ method rather than __init__ !! :-) You still following me.... ? SO : class newstring(str): def __init__(self, value, othervalue): str.__init__(self, value) self.othervalue = othervalue astring = newstring('hello', 'othervalue') fails miserably. This is because the __new__ method of the str is called *before* the __init__ value.... and it says it's been given too many values. What the __new__ method does is actually return the new instance - for a string the __init__ method is just a dummy. The bit I couldn't get (and I didn't have access to a python manual at the time) - if the __new__ method is responsible for returning the new instance of the string, surely it wouldn't have a reference to self; since the 'self' wouldn't be created until after __new__ has been called...... Actually thats wrong - so, a simple string type might look something like this : class newstring(str): def __new__(self, value): return str.__new__(self, value) def __init__(self, value): pass See how the __new__ method returns the instance and the __init__ is just a dummy. If we want to add the extra attribute we can do this : class newstring(str): def __new__(self, value, othervalue): return str.__new__(self, value) def __init__(self, value, othervalue): self.othervalue = othervalue The order of creation is that the __new__ method is called which returns the object *then* __init__ is called. Although the __new__ method receives the 'othervalue' it is ignored - and __init__ uses it. In practise __new__ could probably do all of this - but I prefer to mess around with __new__ as little as possible ! I was just glad I got it working..... What it means is that I can create my own class of objects - that in most situations will behave like strings, but have their own attributes. The only restriction is that the string value is immutable and must be set when the object is created. See the excellent path module by Jason Orendorff for another example object that behaves like a string but also has other attributes - although it doesn't use the __new__ method; or the __init__ method I think. Regards, Fuzzy Posted to Voidspace - Techie Blog : http://www.voidspace.org.uk/voidspace/index.shtml Experiences used in the python modules at : http://www.voidspace.org.uk/atlantibots/pythonutils.html From peter at engcorp.com Thu Jun 10 09:58:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 09:58:26 -0400 Subject: Creating True Global Functions by Modifying Builtins In-Reply-To: <2c60a528.0406100246.554d18b6@posting.google.com> References: <889cbba0.0406090951.32a6434b@posting.google.com> <45adnQYny6eOzFrdRVn-sw@powergate.ca> <2c60a528.0406100246.554d18b6@posting.google.com> Message-ID: Andrew Clover wrote: > Peter Hansen wrote: > >>The only time I've found a valid reason to stick stuff in __builtin__ >>is when trying to make current code *forward compatible* with newer >>versions of Python, such as when bool() and True/False where added >>in 2.2 (?) and we had to stick with 2.0. > > Even this isn't really a good idea. Many other modules have various > different workarounds for lack of feature support, which if you are > unlucky can get confused by builtin-hacking. You're right in general, but what I didn't mention was that this was code intended for an embedded system with total control on what was present or not. It was not on code meant for general distribution to the outside world. As such, it served the purpose perfectly well, without any such negatives. > Having a 'constants' module from which a package can from ... import * > is usually a better approach. Quite true, in most cases. -Peter From http Wed Jun 30 12:23:48 2004 From: http (Paul Rubin) Date: 30 Jun 2004 09:23:48 -0700 Subject: Python Bounties References: Message-ID: <7xwu1povzf.fsf@ruckus.brouhaha.com> David Fraser writes: > > http://orderweb.co.za/open_source_developers_bounties.htm > ... > There have been a few projects to set up open marketplaces for open > source developers, but I couldn't find them using google ... anyone? > > I hope you post more details soon :-) If that's Mark Shuttleworth's project, there was a Slashdot thread about it a month or two ago. From rigga at hasnomail.com Sun Jun 27 05:10:00 2004 From: rigga at hasnomail.com (Rigga) Date: Sun, 27 Jun 2004 09:10:00 GMT Subject: Help formatting a mysql query string References: <40DD7414.6080406@holdenweb.com> Message-ID: Steve Holden wrote: > Pierre-Fr?d?ric Caillaud wrote: > >> >>> sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" >> >> >> - what are the "," doing here if you are trying to build a string ? >> - you should use the python povided way which is better (yours looks >> like php) >> >> cursor.execute( "INSERT INTO %(tb)s VALUES(%(a)s,%(b)s,%(c)s)", { >> 'tb':tablename, 'a':first data, 'b':second data, etc... } > > Better still, create the query string with the right table name in it > and parameter markers for the data: > > sqlquery = "INSERT INTO %s VALUES (%%s, %%s, %%s)" % tablename > > Supposing tablename is "customer" this gives > > "INSERT INTO customer VALUES (%s, %s, %s)" > > Then you can use the parameter substitution mechanism of the DB API to > insert your data in there. Suppose datavalue is ("Steve", "Holden", 85) > then you would do > > cursor.execute(sqlquery, datavalue) > > The problem with building the data portion of the statement is having to > put the single quotes in around strings and escape any single quotes > that might occur in the values you present. It's much easier to use the > parameter substitution mechanism, even though that *can't* be used to > change a table name in most SQL implementations. > > I've assumed for the sake of argument that you're using MySQLdb, which > uses the "%s" paramstyle. mxODBC, for example, you'd use the "?" style, > which makes building statements rather easier. > > One final comment: it's much safer to use the column names in INSERT, as > in > > INSERT INTO customer (First, Last, age) > VALUES ('Steve', 'Holden', 95) > > because that isolates you from a change in the column ordering, which > can happen during database reorganizations when you insert a new column > without thinking about the consequences. Just paranoia induced by years > of experience, and therefore often effort-saving. > > regards > Steve Thanks for the help, sorry I posted this twice, my news reader was not showing the original post so i resubmitted it. I normally work with php thats why I was trying to build it as a string. I now see how I can load the data values from my variables, however is the same possible for the fields? I know you say its best to specify the column names etc however my script is parsing a web page and getting the field headings (which will stay the same), data and table name so I wanted to make the script handle all this rather than having to have a seperate cursor.execute() for each table I want to update - does this make sense? Regards Rigga From lbates at swamisoft.com Fri Jun 11 10:29:52 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 09:29:52 -0500 Subject: property file References: Message-ID: I would use ConfigParser from the standard library. It supports sections, built in conversions, default values, variable insertion, and writing of the file (as well as reading). -Larry Bates "Neil Benn" wrote in message news:mailman.860.1086962012.6949.python-list at python.org... > Hello, > > One way that I have done this is to make a file with : > > =\n > > Then open the file and use the following list comprehension to get > back a dict with the properties in it : > > objFile = file('MyConfigurationFile.conf') > > dctConfiguration = dict([(key.strip(), value.strip()) \ > for (key,value) in [line.split('=') \ > for line in objFile]]) > > It's not as simple as Properties in Java but you could wrap it in a > class to copy the Java Properties class. You could also add some > intellegence to it so that it doesn't bomb out if the properties file is > slightly wrong. > > Cheers, > > Neil > > Mariano wrote: > > >Hi > > > >Have someone any idea how create/read a property file as java property file? > >If not, is there some other solutions? > > > >Thank's in advance > > > > > > > -- > > Neil Benn > Senior Automation Engineer > Cenix BioScience > BioInnovations Zentrum > Tatzberg 47 > D-01307 > Dresden > Germany > > Tel : +49 (0)351 4173 154 > e-mail : benn at cenix-bioscience.com > Cenix Website : http://www.cenix-bioscience.com > > From newsham at lava.net Thu Jun 10 20:52:56 2004 From: newsham at lava.net (Tim Newsham) Date: Thu, 10 Jun 2004 14:52:56 -1000 Subject: webrowser and linux (also os.execv) In-Reply-To: References: Message-ID: > import webbrowser > webbrowser.open("http://www.google.com/") > opens a browser (if not yet open) but fails to redirect it. Another > window of mine receives an error message: Oh man, I feel dumb, please ignore this question. I figured it out and its unrelated to python. Tim N. From Ian.Sparks at etrials.com Tue Jun 29 15:28:18 2004 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 29 Jun 2004 15:28:18 -0400 Subject: Listing functions in a file IN ORDER Message-ID: <41A1CBC76FDECC42B67946519C6677A9C5A73D@pippin.int.etrials.com> > Peter Otten wrote : > > import compiler > > class Visitor: > def __init__(self, module, *args): > self.module = module > self.args = args > def visitFunction(self, node): > getattr(self.module, node.name)(*self.args) > > def callInOrder(module, *args): > ast = compiler.parseFile(module.__file__) > compiler.walk(ast, Visitor(module, *args)) > > if __name__ == "__main__": > import xyz > callInOrder(xyz) > > > Not particularly elegant, but crazy enough to be worth posting... Neat. I'll try it, thanks! > -----Original Message----- > From: Peter Otten [mailto:__peter__ at web.de] > Sent: Tuesday, June 29, 2004 11:53 AM > To: python-list at python.org > Subject: Re: Listing functions in a file IN ORDER > > > Ian Sparks wrote: > > > I have a python file with a number of functions named with > the form doX so > > : > > > > doTask1 > > doThing > > doOther > > > > The order these are executed in is important and I want them to be > > executed top-down. They all have the same parameter > signature so I'd like > > to do : > > > > for name, func in vars(mymodule).items(): > > if not name.startswith("do") and callable(func): > > apply(func,my_params) > > > > but the problem is that the return from vars is not ordered > the same as in > > the file. i.e. it could be > > > > doOther > > doTask1 > > doThing > > > > The low tech solution is to use dir() and re-name the > functions to sort > > alphabetically but perhaps there is a more elegant solution? > > The following minimal code will break with methods and nested > functions. > > > def z(): print "ZZZ" > def y(): print "YYY" > def x(): print "XXX" > > > > import compiler > > class Visitor: > def __init__(self, module, *args): > self.module = module > self.args = args > def visitFunction(self, node): > getattr(self.module, node.name)(*self.args) > > def callInOrder(module, *args): > ast = compiler.parseFile(module.__file__) > compiler.walk(ast, Visitor(module, *args)) > > if __name__ == "__main__": > import xyz > callInOrder(xyz) > > > Not particularly elegant, but crazy enough to be worth posting... > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > From chris.cavalaria at free.fr Mon Jun 7 17:31:09 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Mon, 07 Jun 2004 23:31:09 +0200 Subject: left-quote ( ` ) on International keyboards [Prothon] References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: <40c4de9e$0$13927$636a15ce@news.free.fr> Mark Hahn wrote: > Timo Virkkala wrote: > >> Mark Hahn wrote: >>> We are thinking of using it as a marker for "symbols" in Prothon. >>> They are like strings but can only be legal variable labels: `var, >>> `init_, `x, `account_balance, etc. I think in our application they >>> look good and won't be mistaken for quotes since they don't come in >>> pairs. They are readable and distinquishable in this context. >>> Also, symbols won't be used that frequently so typing won't be too >>> much of a pain. >> >> Why not use something like $ or something? I'm not familiar with >> Prothon, so I don't know if $ is already used for something, but it's >> a character normally used with symbols/placeholders/etc. > > We aren't using any of the oddball symbols any more, so $ is free. I'm a > little wary of proposing using it though. The last time I proposed using > $ Prothon was accused of being Perl :-) > > I'll put it up for vote on the Prothon mailing list. You can come by and > vote for it :-) > > Is $ easier to type on foreign keyboards? $ is one of the only thing easy to type in a french keyboard. Thanks god that we don't need to type too many {} in Python for they are the worst :) Of course, I can't speak for other keyboard layouts. From rodelrod at hotmail.com Wed Jun 16 05:53:29 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Wed, 16 Jun 2004 11:53:29 +0200 Subject: interpreting hotshot results Message-ID: <1lazo5e2thyw3$.1wf1lr5sy3l60$.dlg@40tude.net> I'm having trouble understanding hotshot's results. It's the first time I use a profiler. I'm trying to profile a loop that takes almost six hours (~21000 seconds) to execute in production. The profiler stats, however, give me a total of 16.903 CPU seconds (that's ~17 seconds, right?). The results *are* relevant, as they helped me to pull execution time down from the original 80 hours, but I wonder if I'm missing something that might help take the execution time further down. Follows a simplified version of the code and the real hotshot stats. Thanks, Rodrigo --rodelrod.py """Personal toolbox""" def selectDistinct(list): """Get distinct elements from a list""" [zip] class LookupTable: """Key-acessed table with multiple fields (dictionary with multiple values) """ def __init__(self, *fields): self.data = {} self.fields = fields def __setitem__(self, key, values): self.data[key] = dict(zip(self.fields, values)) def __getitem__(self, key): return self.data[key] [other methods] --cdr.py """From a list of cdrs (call detail records) calculate number of calls to a given destination and above a given duration threshold """ import rodelrod import hotshot class DestinationResult: """Data structure to store results for each country destination""" def __init__(self): self.calls = 0 self.duration = 0 def addcall(self, callduration): self.calls += 1 self.duration += callduration [other methods] # LookupTable {prefix: {'destination': d, 'mincallduration': m}} destLookup = rodelrod.LookupTable('destination', 'mincallduration') [among other stuff, populate DestLookup] profiler = hotshot.Profile('d:/tmp/cdr.prof') profiler.start() # Build results (dictionary of DestinationResult() objects) destinations = rodelrod.selectDistinct([destLookup[x]['destination'] for x in destLookup]) destinations.sort() results = dict(zip(destinations, [DestinationResult() for x in range(len(destinations))])) # - If destination ANI (cdr[idxDnis]) in destination lookup table, # add call to respective result object. # - Iteration must be on a reverse sorted list so that longer (more specific) # prefixes are evaluated before shorter (more general) prefixes lstPrefixes = destLookup.keys() lstPrefixes.sort() lstPrefixes.reverse() # cdrs is a list of tuples (destination phone number, call duration) cdrs.sort() cdrs.reverse() for prefix in lstPrefixes: # len(lstPrefixes) about 80 ~ 200 destination = destLookup[prefix]['destination'] mincallduration = destLookup[prefix]['mincallduration'] addcall = results[destination].addcall #XXX should probably ditch #this object thing altogether lenprefix = len(prefix) for cdr in list(cdrs): # len(cdrs) about 500k ~ 1M cdrprefix = cdr[0][:lenprefix] if cdrprefix > prefix: continue #XXX try and remove these cdr from cdrs right away # doubt that it will do any good though elif cdrprefix == prefix: cdrDuration = cdr[1] if cdrDuration > mincallduration: addcall(cdrDuration) cdrs.remove(cdr) # each cdr must be counted only once elif cdrprefix < prefix: break profiler.stop() --hotshot stats >>> stats4.print_stats() 313303 function calls in 16.903 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 313042 16.836 0.000 16.836 0.000 cdr.py:34(addcall) 246 0.049 0.000 0.049 0.000 rodelrod.py:44(__getitem__) 6 0.018 0.003 0.018 0.003 cdr.py:31(__repr__) 1 0.000 0.000 0.000 0.000 rodelrod.py:21(selectDistinct) 6 0.000 0.000 0.000 0.000 cdr.py:27(__init__) 1 0.000 0.000 0.000 0.000 rodelrod.py:48(__iter__) 1 0.000 0.000 0.000 0.000 rodelrod.py:52(keys) 0 0.000 0.000 profile:0(profiler) From benn at cenix-bioscience.com Fri Jun 11 09:53:48 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Fri, 11 Jun 2004 15:53:48 +0200 Subject: property file In-Reply-To: References: Message-ID: <40C9B96C.9080401@cenix-bioscience.com> Hello, One way that I have done this is to make a file with : =\n Then open the file and use the following list comprehension to get back a dict with the properties in it : objFile = file('MyConfigurationFile.conf') dctConfiguration = dict([(key.strip(), value.strip()) \ for (key,value) in [line.split('=') \ for line in objFile]]) It's not as simple as Properties in Java but you could wrap it in a class to copy the Java Properties class. You could also add some intellegence to it so that it doesn't bomb out if the properties file is slightly wrong. Cheers, Neil Mariano wrote: >Hi > >Have someone any idea how create/read a property file as java property file? >If not, is there some other solutions? > >Thank's in advance > > -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From tim.one at comcast.net Sun Jun 13 17:49:10 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 17:49:10 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <2j3pb9Ft3kn2U1@uni-berlin.de> Message-ID: [Tim Peters] >> The fastest pure-Python solution I've found consumed about 20 CPU minutes >> ... [Claudio Grondi] > I have already used such approach (see code below), but was not able to > get any improvement, even the opposite because of increase of time needed > for calculation for each next iteration step. > > Is my code not well designed? What is the difference to yours? (consider > please, that I started with Python some weeks ago and just trying to > check out the advantages and the limits) Sorry, I really can't make time to review unfamiliar code today. Instead I'll just show the code I used. It implements just enough of the BigDec class to get the problem solved (multiplication, power, and squaring), but in a general way (i.e., __mul__(), __pow__() and square() don't rely on any specifics of the problem instance). Note that BigDec instances are (like all numeric types in Python) conceptually immutable. # Compute in decimal, using 5,000-digit "digits". EXP = 5000 BASE = (5L ** EXP) << EXP # 10**EXP class BigDec(object): def __init__(self, digits): # digits is a list of base-BASE digits, least- # significant first. self.digits = digits def __mul__(self, other): # Force 'other' to have the fewer # of digits. if len(self.digits) < len(other.digits): self, other = other, self # Straightforward cross-product. Don't worry about digits # getting out of range for the duration. result = [0] * (len(self.digits) + len(other.digits) - 1) for baseindex, otherdigit in enumerate(other.digits): for i, selfdigit in enumerate(self.digits): result[baseindex + i] += selfdigit * otherdigit normalize(result) return BigDec(result) __imul__ = __mul__ def __pow__(self, n): # "The usual" left-to-right efficient exponentiation algorithm. # n must be vanilla integer, not BigDec. mask = 1L while mask <= n: mask <<= 1 mask >>= 1 # position of n's most-significant bit result = BigDec([1]) while mask: result = result.square() if n & mask: result *= self mask >>= 1 return result def square(self): # Efficient divide-and-conquer squaring, based on # (a*x+b)**2 = a**2*x**2 + 2*a*b*x + b**2. n = len(self.digits) if n <= 5: return self * self nlo = n // 2 lo, hi = BigDec(self.digits[:nlo]), BigDec(self.digits[nlo:]) result = lo.square().digits result += [0] * (2*nlo - len(result)) result += hi.square().digits for elt in (lo * hi).digits: result[nlo] += elt << 1 nlo += 1 normalize(result) return BigDec(result) def __str__(self): result = map(str, self.digits) # Pad all digits except for the MSD with leading zeroes. for i in xrange(len(result) - 1): digit = result[i] if len(digit) < EXP: result[i] = "0" * (EXP - len(digit)) + digit result.reverse() return "".join(result) def normalize(x): # Force the digits in x into range(BASE), by propagating # carries. x is modified in-place. carry = 0 for i, elt in enumerate(x): carry += elt carry, x[i] = divmod(carry, BASE) while carry >= BASE: carry, leftover = divmod(carry, BASE) x.append(leftover) if carry: x.append(carry) # Strip insignificant leading 0 digits. while x and x[-1] == 0: x.pop() x = BigDec([2]) ** 24036583 # subtract 1 assert x.digits[0] != 0 x.digits[0] -= 1 print x From peter.maas at mplusr.de Wed Jun 9 09:21:09 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 09 Jun 2004 15:21:09 +0200 Subject: promoting [] by superclass? In-Reply-To: <40C61CBA.D6A8BC0A@alcyone.com> References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9hjFnvcsbU1@uni-berlin.de> <40C4FF56.F81105B@alcyone.com> <2il6llFo4tkpU1@uni-berlin.de> <40C580A0.A01B38A7@alcyone.com> <2im7kkFnjduhU1@uni-berlin.de> <40C61CBA.D6A8BC0A@alcyone.com> Message-ID: Erik Max Francis schrieb: > Jim Newton wrote: [...] >>class Pair(list): >> ... >> >>how can i "cast", "promote" [] to class Pair? > > > You can't. Perhaps I've got it wrong but Jim probably asks for overwriting the __getitem__ method. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From mike at nospam.com Mon Jun 14 12:40:11 2004 From: mike at nospam.com (Mike Rovner) Date: Mon, 14 Jun 2004 09:40:11 -0700 Subject: wxPython online documentation is no more accessible References: Message-ID: Boris Boutillier wrote: > Anyone know where to find it now ? > Online doc link is broken : http://www.wxpython.org/onlinedocs.php Use wxwidgets.org Mike From eddie at holyrood.ed.ac.uk Thu Jun 17 13:43:56 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 17 Jun 2004 17:43:56 +0000 (UTC) Subject: Parsing by Line Data References: Message-ID: python1 writes: >Having slight trouble conceptualizing a way to write this script. The >problem is that I have a bunch of lines in a file, for example: >01A\n >02B\n >01A\n >02B\n >02C\n >01A\n >02B\n >. >. >. >The lines beginning with '01' are the 'header' records, whereas the >lines beginning with '02' are detail. There can be several detail lines >to a header. >I'm looking for a way to put the '01' and subsequent '02' line data into >one list, and breaking into another list when the next '01' record is found. >How would you do this? I'm used to using 'readlines()' to pull the file >data line by line, but in this case, determining the break-point will >need to be done by reading the '01' from the line ahead. Would you need >to read the whole file into a string and use a regex to break where a >'\n01' is found? def gen_records(src): rec = [] for line in src: if line.startswith('01'): if rec: yield rec rec = [line] else: rec.append(line) if rec:yield rec inf = file('input-file') for record in gen_records (inf): do_something_to_list (record) Eddie From jacek.generowicz at cern.ch Thu Jun 3 11:14:39 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 03 Jun 2004 17:14:39 +0200 Subject: Optimizing multiple dispatch References: Message-ID: Jacek Generowicz writes: > Hmm, ok, the extension seems to be significantly faster. This > surprises me, because everything that executes in > "tuple(map(type,args))" is coded in C already, so I don't see where > the gain is coming from. Forgot to mention: your map and list comp versions included an unnecessary call to a pure Python function (maptype). The extension you proposed would replace an inlined "tuple(map(type, args))", so we don't get hit by pure Python function call overhead at that point[*]. Still, eliminating that overhead knocks off only one third of the time, while your extension was better by a factor of 7 ... so there's still a factor of 4.5ish to be had by coding it as an extension (sorry, I don't have Pyrex, so I can't show the time): -s 's = ("", 0, 0.0, 0L, str, int, type)' -s 'def maptype(s): return tuple(map(type, s))' 'maptype(s)' 100000 loops, best of 3: 4.73 usec per loop -s 's = ("", 0, 0.0, 0L, str, int, type)' 'tuple(map(type, s))' 100000 loops, best of 3: 4.46 usec per loop [*] There is a pure Python function call overhead I would like to eliminate by recoding in C, but it concerns a closure (which Pyrex doesn't allow, IIRC), and that seems a bit tricky to do. From dmq at gain.com Wed Jun 16 22:15:35 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 16 Jun 2004 19:15:35 -0700 Subject: Bug in New Style Classes Message-ID: I have what looks like a bug trying to generate new style classes with a factory function. class Animal(object): pass class Mammal(Animal): pass def newAnimal(bases=(Animal,), dict={}): class C(object): pass C.__bases__ = bases dict['_count'] = 0 C.__dict__ = dict return C Canine = newAnimal((Mammal,)) TypeError: __bases__ assignment: 'Mammal' deallocator differs from 'object' If I remove the 'object' from the class C(object) statement, then I get a different, equally puzzling error message: TypeError: __bases__ items must be classes The function works only if I remove 'object' from all base classes. -- Dave ************************************************************* * * David MacQuigg, PhD * email: dmq at gain.com * * * IC Design Engineer * phone: USA 520-721-4583 * * * * Analog Design Methodologies * * * * * 9320 East Mikelyn Lane * * * * VRS Consulting, P.C. * Tucson, Arizona 85710 * ************************************************************* * From j_mckitrick at bigfoot.com Fri Jun 11 14:46:22 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 11 Jun 2004 11:46:22 -0700 Subject: How do you write test suites for GUI components? References: <86isdynp6c.fsf@sysfault.org> Message-ID: I guess mine will be much simpler, then. :-) I have pygtk guis tha are the interface to my application. If test suites are so important, how can they be applied to modules that just run dialogs or windows? From chrisks at NOSPAMudel.edu Thu Jun 24 10:43:49 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Thu, 24 Jun 2004 10:43:49 -0400 Subject: Classic and New Style Classes? In-Reply-To: <4edc17eb.0406240221.708028bd@posting.google.com> References: <4edc17eb.0406240221.708028bd@posting.google.com> Message-ID: Michele Simionato wrote: > Also Old.__class__ raises an error whereas New.__class__ returns type(New). > > Is this what you are asking for? > > Michele Simionato Yes, thanks a lot. From dummy at scriptolutions.com Fri Jun 25 07:57:15 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Fri, 25 Jun 2004 13:57:15 +0200 Subject: Retrieve FTP directory with hidden files Message-ID: Hello, i know that this is not a python but a FTP protocol question but maybe someone in this newsgroup could help me. I use the standard ftplib.FTP class and get the listing wia ftp.retrlines('LIST mydir') but this does not get hidden files like ".htaccess" and more important i can't delete directories because they are not empty. From j_mckitrick at bigfoot.com Thu Jun 17 21:54:30 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 17 Jun 2004 18:54:30 -0700 Subject: Why does one work, but not the other? Message-ID: I've done this before: data = [self.cong.tm[k] for k in self.cong.tm.li] #li is list, tm is dict instead of: for k in self.cong.tm.li: data.append(self.cong.tm[k]) but when I try: self.liststore = [[item] for item in data] instead of: for item in data: self.liststore.append([item]) I get an empty list! What gives?? jonathon From giles_brown at hotmail.com Tue Jun 8 05:13:46 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 8 Jun 2004 02:13:46 -0700 Subject: Calling Python Script from MS Excel? References: <40c51309$0$2944$61fed72c@news.rcn.com> Message-ID: <57de9986.0406080113.1090717a@posting.google.com> "Kevin T. Ryan" wrote in message news:<40c51309$0$2944$61fed72c at news.rcn.com>... > Hi Group - > > I have written a "semi-program" in MS Excel related to running a football > pool. I've updated it over the past two years or so, to the point where it > is getting pretty advanced. Only, there are a few tricks that I want to > add that I could not do in Excel - so I did them in Python :) Except as it > stands, the current python scripts have to be run via the command line. > Does anyone know how to allow interaction between Excel and Python via > EXCEL? > > I've looked on Mark Hammond's page, and I've figured out how to interact > with Python and Excel from PYTHON, but I can't seem to find the right info > for making the calls from the other end (i.e. from Excel). Any advice > would be GREATLY appreciated! One way of approaching this would be to package your Python code as a COM server. This is actually much easier than you might think (this reference is quite old but is still relevant): http://www.python.org/windows/win32com/QuickStartServerCom.html You can make calls on your object from Excel VBA. For example you could call on the object in the reference above as: Dim HelloWorld As Object Set HelloWorld = CreateObject("testcomserver.HelloWorld") MsgBox HelloWorld.Hello("Kevin") Hth, Giles From niki at vintech.bg Thu Jun 10 03:44:26 2004 From: niki at vintech.bg (Niki Spahiev) Date: Thu, 10 Jun 2004 10:44:26 +0300 Subject: simple mapi Message-ID: <40C8115A.2000006@vintech.bg> first self-sending program :) maybe for inclusion in ctypes? regards, Niki Spahiev -------------- next part -------------- A non-text attachment was scrubbed... Name: ct_mapi.py Type: application/x-python Size: 2860 bytes Desc: not available URL: From winexpert at hotmail.com Tue Jun 1 09:16:00 2004 From: winexpert at hotmail.com (David Stockwell) Date: Tue, 01 Jun 2004 13:16:00 +0000 Subject: question on garbage collection for python Message-ID: Hi, Does Python leave things in an unknown state? say I do this in my python code someFile = open('somefile' , 'r') data = someFile.read() someFile = 3 At this point I would hope python would know to destruct the prior reference to someFile by unallocating the memory (under the hood) and closing the file. The questions here are: If in my code if I forget to close a file, when will the file be closed? Is it when something goes out of scope? Or will it close when the python session ends? If I define a class of somesort, is there a way I can have a destructor method (like I would under C++ ?) Thanks in advance, David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/ From nopsoft at poczta.onet.pl Thu Jun 24 10:15:39 2004 From: nopsoft at poczta.onet.pl (Janusz U.) Date: Thu, 24 Jun 2004 16:15:39 +0200 Subject: eZ80 - correction [z80 vs Python thread] Message-ID: I have an idea that implements the Python interpreter for eZ80 as an universal flexible language (like scripts) to support attached hardware. What would it be shortest way to do it? I think of course about C (Zilog has good support of own products...). > I wouldn't recommend this. The standard Python interpreter is quite hefty > (>700K dynamically linked), not to mention the standard libraries. Seeing > as Z80 has only 64K address space, I don't see a full implementation as > possible. I know. Sorry, I didn't precise. I thought exactly about eZ80F91 - it's based on Z80 but much more expanded... I will start on the module (and deviloper kit) for that procesor. It would be independent platform for tests software in the Python. > What you /could/ do would be to implement a (very) small subset of Python; > i.e. leave out generators, new-style class, list comprehensions, ability > to override built-in types, functions, and operators, and most of the > standard library, then you /might/ be able to fit a language with Pythonic > syntax in that address space. I think to expand language by own library for Python - eg. control GPIO of eZ80, read > > Another issue would be speed. Z80s, though they've gotten faster over the > years, still only run at speeds on the order of 10MHz. You might be better > off writing a Z80 compiler for a Python-esque language -- this would save > both speed and memory. speed 50MHz (or 20MHz in F92, F93...) > > If you can pick a different chip, go with something like a StrongARM. > These have the power and address space necessary for Python. Plus, it's > been done before (Python runs beautifully on modern PDAs). I have just bought the developer kit for eZ80 so I have limited way. I'd be happy to run Python on eZ80 platform. I'm waiting for the opinion. The best regards Janusz U. From tim.one at comcast.net Sun Jun 13 12:35:38 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 12:35:38 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <40cc065a$0$41764$5fc3050@dreader2.news.tiscali.nl> Message-ID: [Tim Peters] >> + A better algorithm is always the better answer (computing in decimal >> from the start allows pure Python to run circles around GMP computing >> in binary then forced to do a non-trivial 24-million bit base >> conversion). [Gr?goire Dooms] > Could you tell us more about the computational complexity of that > operation in base 10 compared to the same one in base 2 and base2->base10 > conversion ? The asymptotic complexity of the elementary arithmetic operations (+, -, *, /, integer power) is independent of base. From aljosa at mi2.hr Thu Jun 17 11:13:41 2004 From: aljosa at mi2.hr (Aljosa Mohorovic) Date: Thu, 17 Jun 2004 17:13:41 +0200 Subject: isdn caller id Message-ID: if i write an app in python, how can i find out callerId? is there some lib for python which uses some standard way to listen on isdn line? aljosa From paul at prescod.net Sat Jun 12 05:08:39 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 12 Jun 2004 02:08:39 -0700 Subject: raw Strings from XML attributes In-Reply-To: References: Message-ID: <40CAC817.8090607@prescod.net> Karen Loughran wrote: > > Hiya, > > I'm reading a string attribute from an XML document. The string > contains newline characters and is treated as raw. > I'm trying to match it with a string read from a file which is identical > . But because it isn't raw it won't match. As Peter Otten points out, "rawness" is a concept that Python forgets as soon as a string is loaded into memory. r"abc" == "abc" r"\123abc" == "\\123abc" So your problem is something else. Perhaps you could use the "repr" function to print out the representations of the two strings and that will give you more information. print repr(string1) print repr(string2) print string1 == string2 Paul Prescod From simonf at cshl.edu Tue Jun 29 09:33:52 2004 From: simonf at cshl.edu (Vsevolod (Simon) Ilyushchenko) Date: Tue, 29 Jun 2004 09:33:52 -0400 Subject: Introspection, importing and Flash Message-ID: <40E16FC0.6010804@cshl.edu> Hi, Last year I have written a Perl module to serve as a backend to Macromedia Flash applications: http://www.simonf.com/amfperl I have just rewritten it in Python, which I have not used before. Thus, a couple of questions which I was not able to solve with online research: 1. To send an arbitrary object to Flash, I would like to use introspection to find out the values of all its instance variables. How can I get their names? I've read about __dict__, __slots__, and __getattr__, but I am not sure what would be the most universal way to get all the instance variable names from both old-style and new-style objects. I would need something like __listattr__, which does not exist. 2. Python class importing works in a rather confusing way. In Perl, I have a top-level class AMF::Perl, which I "import" once and then create its instance like this: "new AMF::Perl". The file Perl.pm lives in the AMF directory. In Python, the most concise way I found was to have AMFPython.py in the AMF directory, place __init__.py with "import AMFPython" in the AMF directory, then say in my top-level script import AMF instance = AMF.AMFPython.AMFPython() Which is rather redundant. I'd like to do something not more complicated than: import AMF.AMFPython as AMF instance = AMF() but I don't know if it's possible. Thanks, Simon -- Simon (Vsevolod ILyushchenko) simonf at cshl.edu http://www.simonf.com Terrorism is a tactic and so to declare war on terrorism is equivalent to Roosevelt's declaring war on blitzkrieg. Zbigniew Brzezinski, U.S. national security advisor, 1977-81 From peter at engcorp.com Tue Jun 22 11:49:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Jun 2004 11:49:16 -0400 Subject: Cannot create a new file In-Reply-To: <40d83e77$1_1@aeinews.> References: <40d77b19$1_3@aeinews.> <40d79715$1_3@aeinews.> <40d83e77$1_1@aeinews.> Message-ID: Eric Belanger wrote: > I first doubted the problem was here, but I finally (after a few hours) > noticed my directory (in the filesystem) had a typo in it (.hnb-bakcup). > I never noticed it until this morning :S > > I guess I feel a little stupid, but hey, all that waste of time is worth > a good laugh. That _is_ funny. :-) Use my idea about os.makedirs() and you won't have to make the folder manually any more... -Peter From jason at tishler.net Tue Jun 22 16:49:01 2004 From: jason at tishler.net (Jason Tishler) Date: Tue, 22 Jun 2004 16:49:01 -0400 Subject: Python 2.3.4 hangs when run from modern cygwin/bash in WinXP, but is otherwise fine In-Reply-To: <67032014.0406181707.2822aa03@posting.google.com> References: <67032014.0406181707.2822aa03@posting.google.com> Message-ID: <20040622204901.GA11212@tishler.net> Eric, On Fri, Jun 18, 2004 at 06:07:43PM -0700, Eric Woudenberg wrote: > I haven't been able to figure out what's wrong. Does anyone have any > suggestions? See the attached. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 -------------- next part -------------- An embedded message was scrubbed... From: Jason Tishler Subject: Re: Enthought Python + Cygwin Date: Tue, 15 Jun 2004 16:39:00 -0400 Size: 1536 URL: From winexpert at hotmail.com Thu Jun 24 11:56:10 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 24 Jun 2004 15:56:10 +0000 Subject: [python] -- Thanks for the help -- 1st app does: email,error, sql Message-ID: Thanks to all who helped me learn the basics of python. I just completed my first project in python. It's not the best code in the world but it appears to work. It uses pythons 'class' ability It queries for email and when found parses mime'd email messages It stores things in a sql database it sends emails to the developer (me) when things go wrong. It basically works and has some rudimentary error handling. Hopefully I'll get better at using python as time for my next project (which has already started). When u tell ur boss ur done, u get new stuff to do ... I'll probably be asking more 'dumb' questions but hopefully soon I can start answering more than I'm asking... David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Get fast, reliable Internet access with MSN 9 Dial-up ? now 3 months FREE! http://join.msn.click-url.com/go/onm00200361ave/direct/01/ From FBatista at uniFON.com.ar Thu Jun 24 09:35:21 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 24 Jun 2004 10:35:21 -0300 Subject: Except MySQL error Message-ID: [Florian Lindner] #- Hello, #- I want to except the error which is raised in MySQLdb module #- when one is #- trying to insert a value in a primary key column which #- already exists. But #- I don't know which error to except... #- Thx, #- Florian Well, using the SAME python and MySQLdb installation... ...with MySQL 3.1, it was a warning so the program wouldn't stop. ...with MySQL 4.0, it was an error so an Exception was generated. . Facundo From troy at gci.net Thu Jun 24 13:19:23 2004 From: troy at gci.net (Troy Melhase) Date: Thu, 24 Jun 2004 09:19:23 -0800 Subject: Interactive use of DISLIN Message-ID: <99eae49a29d6.9a29d699eae4@gci.net> You may want to check PyQwt, which implements technical widgets for PyQt/Qt. Be sure to check the screenshots, and try the examples if you can: http://pyqwt.sourceforge.net/ ----- Original Message ----- From: andrej_dzerzhinsky at hotmail.com (Andrej Dzerzhinsky) Date: Tuesday, June 22, 2004 10:03 am Subject: Interactive use of DISLIN > I'm building a scientific app using wxPython to call some C functions > together with a suitable plotting application that will work > within a > wxPython frame. > > I'd like to plot a spline over several thousand (x,y) points from a > spectrum, reasonably fast, and be able to zoom in and out of the plot, > label peaks either automatically or by hand, display and overlay > multiple data sets and export plots as metafiles. > > Platform independence is also a big plus. > > Examining several of the Python plotting packages (BLT, matplotlib, > pyplot, hippodraw, DISLIN), so far DISLIN seems to offer the best > combination of speed and ease of use, with matplotlib coming a close > second. > > Can anyone comment on whether DISLIN can be made to do the interactive > things I have mentioned. http://www.openboa.de/srd/node8.html claims > it can't - is this accurate? > > Or is matplotlib or some other package better for what I want. > > Thanks for your time. > -- > http://mail.python.org/mailman/listinfo/python-list > From agriff at tin.it Mon Jun 28 16:33:45 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 28 Jun 2004 20:33:45 GMT Subject: if statement References: Message-ID: <3bv0e0torae2fmsb03ts3s47vpdhgbo9ve@4ax.com> On Mon, 28 Jun 2004 22:59:30 +1000, "Ajay Brar" wrote: >its the first time i amusing python and coming from a {} environment, tabs >is a little hard to get used to. I come from {} too, but found moving to indentation really a no problem except that one of the python editors I tried messed up my code badly, probably because it was written with a two space indent instead of the common 4. I abandoned tabs long ago: when it was standard (8) there could be some use for the tab char, now it's just another way to add *completely pointless* confusion. Anyway I forced myself to change to 4 space indent (even if indeed seems to me a bit too much), and I abandoned fancy editors so I'm back to the trustable VIM :-) ... it may go eventually wrong when guessing the indent for next line; but it will never ever dare to mess up my code. Actually my problem is that now I sometimes forget ";" when working in C++ :-) Andrea From srumbalski at copper.net Mon Jun 28 10:01:04 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Mon, 28 Jun 2004 10:01:04 -0400 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <40e0241e_2@newsfeed.slurp.net> Michael Anckaert wrote: > A friend of mine uses emacs and we held a 'speedcontest', we had > to edit a file with our editors and write some code. Me and vim were > about 50% faster than him and emacs. > But I don't want to start any vim vs. emacs flamewar :-) > I suspect you would be 50% faster even if you both used notepad. This comparison is meaningless without a baseline comparison in an unfamiliar editor. Perhaps you are simply a faster typist. Perhaps code flows more quickly from your brain. Perhaps you were more familiar with the file to be edited and the problem domain. We cannot know the reason that you performed this particular test more quickly. I too use vim. -- Steven Rumbalski news|at|rumbalski|dot|com From NOmanlio_perilloSPAM at libero.it Tue Jun 1 04:33:05 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Tue, 01 Jun 2004 08:33:05 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> <87hdtzeanw.fsf@pobox.com> <87y8n9bej9.fsf@pobox.com> Message-ID: <2pfob0d54qrj0gmav4o1v6r2a215bahgvp@4ax.com> On 31 May 2004 01:56:10 +0100, jjl at pobox.com (John J. Lee) wrote: > >> I need cookies because the server (as many other) authenticate user >> with cookies. >> So the simple algorithm is: >> >> -connect to the server >> -read a cookie from a file >> -send the cookie to the server >> -if the server send a cookie, the old one must be updated: with >> standard Cookie this is simple: cookie.update(newcookie) >> - ... >> - save the cookie to a file >> >> >> This is very simple to do with httplib and Cookie modules, so why to >> use more involved modules? > >No reason at all if you're happy with it, of course. That was what my >"Cool" was meant to communicate. > >*Using* urllib2 is less involved even than your little algorithm >above, of course (neglecting bugs, of course, including the persistent >connection bug, which -- though it could certainly be a problem -- I >confess has never actually troubled me, despite having used it to >repeatedly fetch tens of millions of records in the past). > >Why use modules whose *implementation* is more involved? Because >they're even easier to use, and because, even for simple scripts like >your's, not every case is as simple as the one you happen to have met. You are right, but: what means 'easier to use'? There is less code to write? There is less theory to learn? For my script using urllib2 does not make the program easier. >I know from experience that it can quickly get *very* tiresome to do >some of this stuff by hand (even if only a few things like >redirections and cookies are involved). In my case cookie are very easy to use and I simply ignore redirection... Of course I agree with you for all other cases, but there exist programs that really needs only low level library. Actually, ad example, standard Cookie module is low level. It only parses key=value pairs, and, more important, it is 'other library' neutral. That is, BaseCookie class has a parse method for parsing a string (as SetCookie: key=value; ....), and an OutputString (added by me) that returns the cookie data. Thanks and regards Manlio Perillo From aahz at pythoncraft.com Tue Jun 15 11:36:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 Jun 2004 11:36:26 -0400 Subject: thread help References: <40cea9cb$1@nntp0.pdx.net> Message-ID: In article <40cea9cb$1 at nntp0.pdx.net>, Scott David Daniels wrote: >Aahz wrote: >> Bart Nessux wrote: >>> >>>Could someone show me how I can make this work correctly? I want to probe >>>64 unique IP address for HTTP servers simultaneously, ... >> >> Create a threading.Thread subclass that takes one IP address and a list >> of ports to scan. Start 64 instances of this class, each with a >> different IP address. > >An alternative is to create a que into which you push IP addresses to >contact, and have each thread read addresses off the queue when they are >free to process them. This has the advantage of decoupling the number >of threads from the number of addresses you want to examine. Absolutely, but that requires a bit more work for someone who isn't already familiar with threading. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From shalabh at cafepy.com Wed Jun 2 22:36:36 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 02 Jun 2004 19:36:36 -0700 Subject: scoping questions In-Reply-To: References: Message-ID: David Stockwell wrote: > Hi, > > Another of my crazy questions. I'm just in the process of learning so > bear with me if you can. I actually ran it.... with two test cases > > TEST CASE 1: > Say I have the following defined: > --- beginning of code snippet ---- > > def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > > aFile = open('/tmp/test','r') > me(aFile) > data = aFile.read() > print data > > ------ end of code snippet ---- > my test file has a sentence 'This is a test of the /tmp/test file' > > When I run it I observed this output: > hello world > This is a test of the /tmp/test file > [snipped op's understanding of above] > > TEST CASE 2: > ------- > def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > def me2(dog): > """ > Note I am testing scoping > """ > print "Inside me2" > dog.close() > > > aFile = open('/tmp/test','r') > me(aFile) > data = aFile.read() > print "test1", data > aFile.close() > aFile = open('/tmp/test','r') > > me2(aFile) > print "test2", aFile.read() > ===== > > It bombs out on the last line because aFile was closed in the function > 'me2'. > > Perhaps the way to explain it is that Inside me2 when my copy of the > original reference is made, I have a global and local variable both > referencing the same 'object'. I am able to do operations in the local > me2 scope and have them effect the behavior of the global scope. > > Its just a bit confusing because python is apparently smart enough to > realize that my action on the local reference hasn't redefined the > capability of the global so it has allowed this to occur on the actual > global file referenced object. (as opposed to just a local copy). And I > didn't return anything.... > > > I'm just confused a bit here.... Perhaps someone can clarify > > Thanks I'd like to point out the different operators used in the two cases: equal-to (=) vs dot (.). These two work very differently. Equal-to binds a 'name' to an object. A = B will bind the name A to the object currently bound to name B. B remains bound to the same object. If the name A was already bound, it doesn't matter, it will now be bound to the new object. Dot accesses an attribute on an object. A.f() will call the method f() of object A. The method may or may not change the object itself. Some objects cannot be changed (they are immutable eg. tuples and strings). HTH, Shalabh From matthiasjanes at gmx.net Fri Jun 25 16:04:06 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 25 Jun 2004 13:04:06 -0700 Subject: WxPYTHON GetValue from wxGrid HELP Message-ID: dear all, I just need a little help. could anyone give real code example (simple) how to read the value of a grid cell. i could not figure it out and really would like to do a simple spreadsheet application in wxpython (my first try with wxpython gui) so, if any one knows just how to read the value of a cell - a real working example would be greatly appriciated Matthias Janes From h.b.furuseth at usit.uio.no Thu Jun 10 11:58:57 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 10 Jun 2004 17:58:57 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <10cfmnrr8su9050@corp.supernews.com> Message-ID: Peter Hansen wrote: >Michael Geary wrote: > >>>>try: >>>> myfile = open("myfilepath", "w") >>>> myfile.write(reallybigbuffer) >>>>finally: >>>> myfile.close() >> (...) >> And it has a bug. :-) >(...) > > The correct approach is of course to open the file *before* > the exception block starts. > > If you are concerned that the open might fail, which is a *different* > type of exception, then you probably want a try/except block around > the whole thing as well as the try/finally. In that case I usually prefer 'myfile = None' before 'try' and 'if myfile:' before close(), to avoid an extra nesting level. BTW, another problem with calls like close() in destructors is that exceptions from destructors are ignored (except for a warning message). So if close() fails because the disk is full or something, your program will happily continue as if the file was updated successfully. class foo: def __del__(self): raise NotImplementedError def bar(): x = foo() del x print "Still happy." bar() --> Exception exceptions.NotImplementedError: in > ignored Still happy. -- Hallvard From peter at engcorp.com Thu Jun 10 09:48:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 09:48:42 -0400 Subject: Doc strings for a standalone app?? In-Reply-To: References: Message-ID: j_mckitrick wrote: > It SEEMS to me that doc strings are for those who will USE your code, > and comments for those who will MAINTAIN it. Does that make any > sense? That makes total sense. I never even considered using doc-strings for anything but API type information. I'm not sure why... perhaps because that's how they are used in all the standard library code, or perhaps just because it doesn't seem to make any sense having maintenance-related information available in the module at runtime. I suppose if they had been intended for maintenance info, they would have been called "comment strings", and not "doc strings"... -Peter From heikowu at ceosg.de Wed Jun 2 09:19:47 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Wed, 2 Jun 2004 15:19:47 +0200 Subject: memory error In-Reply-To: References: Message-ID: <200406021519.47603.heikowu@ceosg.de> Am Mittwoch, 2. Juni 2004 15:11 schrieb Bart Nessux: > size = s.read() You read the complete content of the file here. size will not contain the length of the file, but the complete file data. What you want is either len(s.read()) (which is sloooooooooow), or have a look at os.path.getsize(). > size_list.append(size) This appends the complete file to the list. And as such should explain the memory usage you're seeing... HTH! Heiko. From jbperez808 at yahoo.com Wed Jun 9 01:04:07 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 09 Jun 2004 13:04:07 +0800 Subject: dropping into pdb on an exception Message-ID: <2injkiFobmt3U1@uni-berlin.de> How do you set up pdb such that you will automatically get dropped into its prompt if an unanticipated exception occurs in a script you are using? ASPN Python cookbook gives you the following method which you can add to your script and hook into sys.excepthook. But is there a way to do it without adding stuff to your script? (It's okay if this means having to invoke the script from within pdb, but #1, I don't know how to get it stay inside pdb in the case of an /unanticipated/ exception. And #2, I don't know how to pass [the equivalent of] command-line arguments to a script invoked from within pdb.) def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info From miki.tebeka at zoran.com Wed Jun 16 02:39:00 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 16 Jun 2004 08:39:00 +0200 Subject: newbie question-multidimensional arrays In-Reply-To: References: Message-ID: <20040616063900.GE704@zoran.com> Hello Dan, > return [[initial] * m for i in xrange(n)] Right. Thanks. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From __peter__ at web.de Wed Jun 16 03:38:16 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Jun 2004 09:38:16 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Jean-Fran?ois Doyon wrote: > I'm using MetaClasses to create classes. > > How do I make these new classes "globally" available? As far as I can see, your problem has nothing to do with metaclasses. >>> globals()["foo"] = 1 >>> foo 1 Substitute 1 in the above with your new class, and there you are. Note, however, that dynamically inserting variables is not the best programming practice. When you don't know the variable name in advance, what would be the benefit of being able to access the object via its identifier? Peter From tjreedy at udel.edu Wed Jun 16 21:57:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jun 2004 21:57:47 -0400 Subject: breaking a list into smaller lists References: Message-ID: "Bart Nessux" wrote in message news:caqjke$mh8$1 at solaris.cc.vt.edu... > I understand how a Python list can be broken into smaller lists by using > slice like this: > > new_small_list_1 = BIG_LIST[0:1001] #0-1000 this is 1001 items: you probably want 0:1000 > new_small_list_2 = BIG_LIST[1001:2001] #1001-2000 > new_small_list_3 = BIG_LIST[2001:3001] #2001-3000 these are 1000 items, but with off-by-one correction, 1000:2000, etc > > However, I was wondering if there's an easier way to do this. For > example, say I have a list that contains the names of 100,000 files that > I wish to open and read. Because of file handle limits, I can only open > roughly 1000 files at a time while the OS is doing other things. > > Is there a way to turn this big list into 100 small lists (each > containing 1000 files) with one simple line of code? using *your* pattern, corrected, but untested and written while slightly tired: [biglist[i:i+1000] for i in range(len(biglist)/1000)] Terry J. Reedy From jmeile at hotmail.com Wed Jun 30 10:33:58 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 30 Jun 2004 16:33:58 +0200 Subject: TERMIOS.py In-Reply-To: References: Message-ID: <40e2cf9b$1@pfaff2.ethz.ch> Hi, > under windows : ren TERMIOS.py termios.py I don't think that's the problem: first: TEMIOS != termios. They are two different modules: http://docs.python.org/lib/module-TERMIOSuppercase.html second: Those two modules aren't available on windows. I guess you either didn't install the module or you have a really old python. Regards, Josef From porky_pig_jr at my-deja.com Wed Jun 2 17:58:08 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 2 Jun 2004 14:58:08 -0700 Subject: a question on __slots__ (and example from Nutshell) Message-ID: <56cfb0e3.0406021358.3d50d921@posting.google.com> Hello, I"m still learning Python, but going through the Ch 5 OOP of Nutshell book. There is discussion on __slots__, and my understanding from reading this section is that if I have a class Rectangle (as defined in some prior sections), and then I provide definition class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth' I can use the instance of OptimizedRectangle, say, x, with 'width' and 'heigth', but (quoting the book) 'any attempt to bind on x any attribute whose name is not in C.__slots__ raises an exception. Alas, something goes wrong here, but I *can* bind any arbitrary attribute, and seems like the instance of OptimizedRectangle does have its own __dict__ where those attributes are kept. I'm using the latest stable version of Python (2.3.4, I believe). Here is a session from IDLE: Here I'm defining the class with __slots__: >>> class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth' and create its instance, 'ropt': >>> ropt = OptimizedRectangle(4,5) Note that __dict__ is still there: >>> ropt.__dict__ {} so I can define some arbitrary variable, say, newarea: >>> ropt.newarea = 15 which goes into the dictionary >>> ropt.__dict__ {'newarea': 15} whereas width and heigth are still kept in __slots__: >>> ropt.__slots__ ('width', 'heigth') My impression is that once __slots__ are defined, __dict__ is effectively disabled - but in this example it's alive and well. Am I missing anything here? TIA. From fumanchu at amor.org Mon Jun 7 23:10:15 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 7 Jun 2004 20:10:15 -0700 Subject: Callbacks to generators Message-ID: Dave Benjamin wrote: > Is there a straightforward way to create a generator from a > function that > takes a callback? For instance, I have a function called "process": > > def process(text, on_token): > ... > > For each token that "process" finds in "text", it creates a > token object, > "token", and calls "on_token(token)". > > Now, suppose I wanted to create a generator based on this > function. I tried > to do the following: > > def process_iter(text): > def on_token(token): > yield token > process(text, on_token) > > However, rather than create a generator as I had hoped, this function > doesn't return anything. I guess it creates a bunch of > singleton generators, > one per token, and throws them away. In any case, is there a > way to do what > I am trying to do here without resorting to threads? > > The reason I am trying to do this is that I'd still like to > be able to use > "process" in code for Python 2.1, which does not support > generators. I'd > like to avoid implementing the entire thing twice or basing > the callback > version on the generator version. You're not the first to tackle this problem: http://mail.python.org/pipermail/python-list/2003-December/197828.html ...but no solution forthcoming. FuManChu From fishboy at spamspamspam.com Sat Jun 12 00:49:29 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sat, 12 Jun 2004 04:49:29 GMT Subject: Problem with urllib.urlretrieve References: Message-ID: <8u2lc0l52oom97s8nqmurc7n5eal60shnt@4ax.com> On 11 Jun 2004 16:01:01 -0700, ralobao at gmail.com (ralobao) wrote: >Hi, > >i am doing a program to download all images from an specified site. >it already works with most of the sites, but in some cases like: >www.slashdot.org it only download 1kb of the image. This 1kb is a html >page with a 503 error. > >What can i make to really get those images ? > >Thanks > >Your Help is aprecciate. I did something like this a while ago. I used websucker.py in the Tools/ directory. And then added some conditionals to tell it to only create files for certain extentions. As to why it fails in your case, (/me puts on psychic hat) I guessing slashdot does something to stop people from deep-linking their image files to stop leeches. ><{{{*> From davidf at sjsoft.com Wed Jun 23 03:56:29 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 09:56:29 +0200 Subject: wxPython version of Shtoom? In-Reply-To: References: <40d2e3de@news.mt.net.mk> Message-ID: Anthony Baxter wrote: > ?????? ??????????? wrote: > >> Hi, >> I'm making a small PyQT app, and it will also have a config file (any >> type >> is ok) for several options. >> >> I would also like to add a gui for changing the config options but I >> don't >> want to make design the GUI. I'd be satisfied if the GUI is automatically >> generated from the config file (or config file specification). >> >> Is there some sollution for this? > > > Shtoom (shtoom.divmod.org) has code that does exactly this, for Qt and > Tk so far - I hope to have a Gtk version in the not-too-distant future. > It also uses the same code to handle ConfigParser .ini files and command > line arguments. > > Any hope for a wxPython version of Shtoom? David From eddie at holyrood.ed.ac.uk Tue Jun 15 11:22:16 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 15 Jun 2004 15:22:16 +0000 (UTC) Subject: queues and things References: Message-ID: "User At" writes: >I currently have a deamon that reads a data from a serial port, and based >on certain data it sends out alert messages (sms,email,etc). The problem I >have is that sending alerts requires a bit of time (about 30 seconds), so >I use non-blocking queues which works fine. But, when a signal to >"terminate" is sent to the daemon, only the first entry in the alert queue >is completed before exit. Is there way to get all the items on the queue >to be executed before the exit? Put a "STOP" command on the queue. Eddie From chuck at smtl.co.uk Tue Jun 8 04:49:41 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 09:49:41 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Mon, 07 Jun 2004 19:48:49 GMT." <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> Message-ID: <200406080849.i588nfeb032051@sevenofnine.smtl.co.uk> I have tried breaking it down a bit as per your post. when I run it I still dont see any results even to my output file . Im logged in as myself ansd trying to access the mailbox on the mailserver which is mounted via nfs.The mail server has only version Python 1.5 So doesnt know about the email module. Cheers output =('/tmp/SurveyResults','w') fp = open("/var/spool/mail/chuck") mbox = mailbox.UnixMailbox(fp) for mail in mbox: print mail.read() break #just look at one message From muhammad_ali at spymac.com Tue Jun 1 01:13:33 2004 From: muhammad_ali at spymac.com (Muhammad Ali) Date: Mon, 31 May 2004 23:13:33 -0600 (MDT) Subject: HTTP Proxy server in python Message-ID: <20040601051333.027694C0D6@spy10.spymac.net> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From me at privacy.net Fri Jun 11 09:24:10 2004 From: me at privacy.net (Duncan Booth) Date: 11 Jun 2004 13:24:10 GMT Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> <40c8e44f$0$36860$e4fe514c@news.xs4all.nl> Message-ID: Rick Holbert wrote in news:cac91i$5st$1 at charm.magnus.acs.ohio-state.edu: > So, something like this? > > x = 2**2436583 - 1 > > while x > 0: > print x%10, > x/=10 > If you want to convert a large number to a decimal string reasonably quickly you should do the conversion recursively and divide by numbers much larger than 10. For example, the code below will outperform str(x) significantly for numbers larger than about 2**10000 (according to timeit.py) and has plenty of scope for further optimisation. It will still take a very long time for 2**24036583 - 1: I haven't timed it, but even precalculating the powers list grinds to a halt beyond about 17 or 18 elements. def toDecimal(x): digits = 48 powers = [ 10**digits ] result = [] format = "%%0%dd" % (2*digits) while x > powers[-1]: powers.append( 10 ** (digits * 2**len(powers))) def convert(x, index): if x==0: if not result: return # Ignore leading zeros result.append('0' * (digits * 2**(index+1))) return if index > 0: q, r = divmod(x, powers[index]) convert(q, index-1) convert(r, index-1) else: result.append(format % x) if x==0: return '0' convert(x, len(powers)-1) result[0] = result[0].lstrip('0') return ''.join(result) Notes: the value used for 'digits' is critical. Multiples of 12 seem to work best for me with 24, 48 or 96 being about best. The calculation of powers should be done once and cached (preferably outside the program), but it is still a bottleneck when they get sufficiently large. Squaring the last element of powers each time is an alternative way to calculate it but doesn't seem to be any faster. From aahz at pythoncraft.com Thu Jun 17 19:58:41 2004 From: aahz at pythoncraft.com (Aahz) Date: 17 Jun 2004 19:58:41 -0400 Subject: How to make an immutable instance References: <2jem4iF10udstU1@uni-berlin.de> Message-ID: In article <2jem4iF10udstU1 at uni-berlin.de>, Leif K-Brooks wrote: >Batista, Facundo wrote: >> >> So, if you use this "immutable" class in a dict, and then you (on purpose) >> modify it, you'll have different hashes. >> >> Said that, how safer is this approach? Is there a better way? > > [...] > >But note that you can still use object.__setattr__ directly to get >around it. I don't think there's a way to get true immutability in pure >Python. Correct. Remember that Python is a language for consenting adults; the only way to guarantee object immutability is to create a type in C. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From irmen at -nospam-remove-this-xs4all.nl Mon Jun 28 16:49:39 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 28 Jun 2004 22:49:39 +0200 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: References: <40deae5e$0$65807$e4fe514c@news.xs4all.nl> <889cbba0.0406271027.39b3044@posting.google.com> Message-ID: <40e08462$0$568$e4fe514c@news.xs4all.nl> Mark wrote: >> Wow, that's not good, thanks for sharing that information with us. The >> heck of it is, people probably WOULD write articles for their magazine >> for their preferred set price (read: FREE!) if they would give them >> even a magazine subscription in return. But that's a total gyp, >> instead. > > > Huh? > > If you actually took the time to visit Py and read our Writer's > Guidelines you will find a big bold > headline that reads: "Complimentary PyZine subscription for Authors" and > Irmen of course got a free subscription. I did. And I will repeat an earlier reply here because it didn't reach everybody the first time: Mark: apologies for writing my story in the (too short) way that I did, you're comments are valid. What I wrote are the facts, but I may have expressed it too harshly. [Kamilche:] > Sorry to hear that you wasted your time! I didn't. The article *is* published. And I don't care about the money (I wrote the article at the time when PyZine had a different form, there was no talk about any author payment at that time). So again, it's not a big issue, I just wanted to share my experience. --Irmen. PS: everything has now been taken care of with PyZine. From newsgroups at jhrothjr.com Fri Jun 25 20:55:37 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 25 Jun 2004 20:55:37 -0400 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: <10dpicb9rjib2bb@news.supernews.com> "george young" wrote in message news:78b6a744.0406250737.310f31da at posting.google.com... > [Python 2.3.3, x86 linux] > I had developed the habit of using the neat python form: > if someinstance: > someinstance.memb() > > because it seems cleaner than "if someinstance is not None". > {please no flames about "is not None" vs. "!= None" ...} > > This seemed like a good idea at the time :(). Twice, recently, > however, as my > app grew, I thought, hmm... it would make things clearer if I gave > this container class a __len__ member and maybe a __getitem__. Great, > code looks > nicer now... crash,crash, many expletives deleted... > > Its great to be able to say containerinstance[seq] instead of > containerinstance.steps[seq], but I've also changed the semantics of > (containerinstance) in a boolean context. My app breaks only in the > seldom case that the container is empty. > > Obviously I know how to fix the code, but I'm wondering if this isn't > a message > that "if containerinstance:" is not a good coding practice. Almost. The message is that testing for None, however you're doing it, is a Code Smell in the sense defined in the Refactoring book. If some attribute is supposed to have a Foo object, then it should have a Foo or a subclass of Foo, not None. Sometimes there's no way around it, but whenever you find yourself testing for None, consider using a Null Object instead. A Null Object is a subclass of the normal object you would be expecting, but one that has methods and attributes that handle the exceptional case cleanly. Of course, there are a couple of very pretty idioms for handling optional parameters that depend on tests for None, but they're definitely special cases, and they also break if the real parameter can be False. John Roth From has.temp2 at virgin.net Wed Jun 2 14:49:31 2004 From: has.temp2 at virgin.net (has) Date: 2 Jun 2004 11:49:31 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406021049.3133730e@posting.google.com> Peter Maas wrote in message news:... > has schrieb: > > Announcing the final v1 release of HTMLTemplate; best damn HTML > > templating system evar, or yer money back. Enjoy! :) > > Good work BUT > there are some other Python templating frameworks around, e.g. [...] > Did you find these alternatives unsatisfactory? Yep. Some reasons: 1. Most Python templating systems are either code-in-markup or markup-in-code designs, which don't provide clean separation between markup and code. Code-in-markup systems at best separate only business logic; presentation logic remains firmly embedded in markup. Markup-in-code systems provide no separation whatsoever (the only example I've liked the look of is Lisp-based , but I'm not a Lisp programmer). HTMLTemplate uses a simple DOM-derived approach that provides complete View-Controller separation [according to Apple's definition of MVC, not Smalltalk's]. An HTML template is converted into a simple object model (the View layer) that can be manipulated from your Python script (the Controller layer). BTW, how the user defines the Model layer is left completely up to them (in simple scripts I just squish any business logic into the controller code, in more complex systems I keep 'em separate). Not my place to dictate that to them; smells of fascism. 2. A good proportion of other templating systems invent their own custom templating languages rather than leverage an existing one (e.g. Python). See Greenspun's Tenth Rule for why this is generally a bad idea. (I learned this lesson the hard way from writing my second templating system, which tried to copy the PHP/ASP custom HTML-embedded language approach. Took me two months to write, two weeks to debug, and less than a week from completion to burial beneath the patio. Just as well really; the v2 TO DO list was growing almost as long as the v1 codebase.:) 3. Most templating systems are either "powerful but complex", "simple but underpowered" (i.e. crippled and inadequate) or, in worst cases, "complex AND underpowered". "Flexible" costs extra in any case. The best solution would be one that's both powerful and flexible while also remaining simple in implementation and use: basic Unix philosophy. After designing/writing two complex, underpowered and inflexible templating systems, my third finally met the "powerful" requirement. Unfortunately, it proved just as complex and clumsy in practice; features added to make it more flexible and easy to use paradoxically having the opposite effect. I finally cracked that problem on number four (the original HTMLTemplate, of which the Python version is a partially reworked port) simply by throwing out every last bit of non-essential, non-core functionality I could find and working on what was left to get it just right. > If somebody wants to use a Python templating framework > why should he prefer HTMLTemplate? Think of the four years, thousands of lines of code, and dozens of features that have gone into its creation. Then do a line count of the API and codebase against the rest of the pack. ;) HTH From tkpmep at hotmail.com Mon Jun 7 22:58:07 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 7 Jun 2004 19:58:07 -0700 Subject: Passing parameters using **kargs Message-ID: I want to access parameters that are passed into a function using the **kargs idiom. I define f(**kargs) via def f(**kargs): print kargs . . the keyword arguments are converted to a dictionary, so that if I type f(a=1, b=2, c=3) the function prints {'a': 1, 'b': 2, 'c':3} Now assume the function has three variables a, b and c to which I want to assign the dictionary's values of 'a', 'b' and 'c'. How can I assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I be trying to construct a string representation of each variable's name and using that as a key, or am I just thinking about this the wrong way? Thomas Philips From mark at prothon.org Mon Jun 28 13:46:58 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 28 Jun 2004 10:46:58 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: "Antoon Pardon" wrote > Well personnally I would solve this with a more general loop construct. > > Something like: (Pseudo code) > > loop: > list.append(x) > while len(list) < 10: > blah blah. > > > The more general construct would be something like: > > loop: > code > while condition1: > code > else: > exit code if condition1 fails > while condition2: > code > else: > exit code if condion2 fail This seems non-intuitive to me. Also how would you know the "while" was not a regular "while"? Even if the parser could figure it out, the reader would be confused. BTW: Your code example has the "while" indentation not aligning with anything above which is illegal indentation. From stephan.diehlNOSPAM at gmx.net Wed Jun 16 03:52:24 2004 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Wed, 16 Jun 2004 09:52:24 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Jean-Fran?ois Doyon wrote: > Hello, > > I'm using MetaClasses to create classes. > > How do I make these new classes "globally" available? > > I probably just have to assign them to something magic, but I can't seem > to figure out which one. > > if I do: > > MetaClass('Klass', (), {}) > > The resulting class needs to be assigned to something: > > myclass = MetaClass('Klass', (), {}) > Just do class Klass(object): __metaclass__ = MetaClass Cheers Stephan From dontaskme at doityourself.com Mon Jun 14 14:02:06 2004 From: dontaskme at doityourself.com (Meno) Date: 14 Jun 2004 11:02:06 -0700 Subject: setattr using invalid attribute names - bug or feature? References: <40cdb3d5.2146906@news.t-online.de> Message-ID: <9c2d8268.0406141002.5c1d1e6@posting.google.com> gerson.kurz at t-online.de (Gerson Kurz) wrote in message news:<40cdb3d5.2146906 at news.t-online.de>... > I stumbled across this (while using my homebrewn enum class): > > class test: > pass > > instance = test() > setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) > > I would've expected some kind of error message here when calling > setattr(); after all, its not a regular attribute? Plus, documentation > says > > " > Set a named attribute on an object; setattr(x, 'y', v) is equivalent > to > ``x.y = v''. > " > > and you cannot write this: > > instance.THIS :*2+~# IS OBVIOUSLY INVALID = 123 No, but you can write this: >>> a = getattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID") >>> print a 123 Meno. From guettli at thomas-guettler.de Mon Jun 7 10:46:06 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 07 Jun 2004 16:46:06 +0200 Subject: Balanced tree type coming in next Python? References: Message-ID: Am Mon, 07 Jun 2004 12:57:09 +0300 schrieb Christos "TZOTZIOY" Georgiou: > PS Any volunteers to port and maintain Judy arrays/trees for Python?-) > http://judy.sourceforge.net/ > They'd be an interesting alternative to dictionaries in some cases (esp > very large dictionaries). Hi, How do they compare to BTrees (ZODB)? Regards, Thomas From fumanchu at amor.org Tue Jun 8 16:49:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 8 Jun 2004 13:49:52 -0700 Subject: promoting [] by superclass? Message-ID: Jim Newton wrote: > this is interesting. I though that if you passed > an argument to your class factory function, it would call > the __init__ with that argument. > > class x1(list): > def __init__(y): > pass > > class x2(list): > pass > > what does x1([]) do and what does x2([]) do? x1([]) first calls x1.__new__, but since you're not overriding that, it moves up the class heirarchy to the next superclass, which is 'list', and calls list.__new__(cls, sequence). Notice that there are two arguments to this method. That method is written in such a way that the result is of type 'cls' (in your example, cls == x1). So when this method returns, we've got an object of type 'x1'. Then x1.__init__ gets called, passing it the new object and the 'sequence' arg. However, you've overridden list.__init__; moreover, it doesn't have the same number of arguments as __new__ did, so you get a TypeError saying that __init__ takes a different number of arguments. If you want to override __init__, it should be written: >>> class x1(list): ... def __init__(self, sequence): ... pass ... >>> x1([]) [] >>> type(x1([])) Now, that only works if you wish to keep the same signature (arguments). If you want to provide another argument to the class instantiation, you need to override both __new__ and __init__ so that their argument lists "match": >>> class x1(list): ... def __new__(cls, sequence=[], maxlen=5): ... return list.__new__(cls, sequence) ... def __init__(self, sequence=[], maxlen=5): ... self.maxlen = maxlen ... >>> x1([]) [] >>> type(x1([])) >>> x1([], 7) [] >>> x1([], 7).maxlen 7 x2 doesn't override anything, so the default list.* methods get called for all operations. Remember, though, that list.__new__ produces an object whose type is the subclass automatically, without overriding; therefore: >>> class x2(list): pass ... >>> type(x2([])) Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From jfabiani at yolo.com Tue Jun 29 21:34:53 2004 From: jfabiani at yolo.com (John fabiani) Date: Wed, 30 Jun 2004 01:34:53 GMT Subject: does not work on freeBSD but works on linux, and windows Message-ID: <1NoEc.79428$kV1.13425@newssvr29.news.prodigy.com> Hi, this is a little strange. All I'm trying to do is ftp a 'dbf' file - but the file is corrupt after the transfer. 1. the freeBSD 4.4 is a couple of years old using: Python 2.1.1 (#1, Sep 13 2001, 18:12:15) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "copyright", "credits" or "license" for more information. 2. below is a simple ftp program import ftplib import sys remote=ftplib.FTP(host='myIpAddress',user='username',passwd='password') mohpac07=open("/usr/home/spx/servplus/outbounds/mohpac07.dbf",'rb') remote.set_debuglevel(2) remote.set_pasv(0) remote.storbinary("STOR mohpac07.dbf",mohpac07,8192) remote.close remote.quit 3. below is the output. *cmd* 'TYPE I' *put* 'TYPE I\r\n' *get* '200 Switching to Binary mode.\r\n' *resp* '200 Switching to Binary mode.' *cmd* 'PORT 190,10,10,2,14,194' *put* 'PORT 190,10,10,2,14,194\r\n' *get* '200 PORT command successful. Consider using PASV.\r\n' *resp* '200 PORT command successful. Consider using PASV.' *cmd* 'STOR mohpac07.dbf' *put* 'STOR mohpac07.dbf\r\n' *get* '150 Ok to send data.\r\n' *resp* '150 Ok to send data.' *get* '226 File receive OK.\r\n' *resp* '226 File receive OK.' I then test the dbf file by attemping to open the file with foxpro and the file is corrupt (not a table). The strange thing the same code works from XP, and Linux (both are python 2.3). I don't know much about freeBSD and I'm not sure if I can install 2.3. Anybody no why this is happening? TIA John From munna at 2-cool.com Fri Jun 11 08:26:18 2004 From: munna at 2-cool.com (Munna D) Date: Fri, 11 Jun 2004 07:26:18 -0500 Subject: Python and XML processing with SAX Message-ID: <20040611122618.4A25916402D@ws1-4.us4.outblaze.com> Hi, I'm trying to find a way of getting a list of all elements and attributes allowed in an XML DTD (so that I can then compare this against an XML instance and see which of the lements/attributes are not being used). Is there a way to do this with Python and SAX? I'm a comparative newbie to Python, so would be very grateful if someone could explain how I can do this with a small code example. Thank you in advance, Munna -- ___________________________________________________________ Sign-up for Ads Free at Mail.com http://promo.mail.com/adsfreejump.htm From jacek.generowicz at cern.ch Thu Jun 10 03:18:20 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jun 2004 09:18:20 +0200 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Message-ID: hungjunglu at yahoo.com (Hung Jung Lu) writes: > Alexander Schmolck wrote: > > How do younger languages like IO make this point more forcefully than lisp, > > smalltalk etc -- languages which have been around for decades? > > Double checked with Lisp just now. And Lisp did not allow me to > redefine "if", "setq", "t", etc. I presume you mean Common Lisp. I'm pretty sure that Scheme allows you to do this without any restriction. > If there are tricks in Lisp to intercept "if", "setq", etc.I'd like > to know. In Common Lisp you are not allowed to rediefine any external symbols in the COMMON-LISP package: http://www.lisp.org/HyperSpec/Body/sec_11-1-2-1.html and, in particular, http://www.lisp.org/HyperSpec/Body/sec_11-1-2-1-2.html ... so you define your own versions in another package. If you want to know more about the issues surrounding this, then I suggest you ask on c.l.lisp, as this is, after all, c.l.python. > Same if these limitations are specific to some particular > implementations of Lisp. If by "Lisp" you mean "Common Lisp": no. If by "Lisp" you mean "the Lisp language family" and by "implementation" you mean "dialect": yes. > I greatly suspect that these limitations of Lisp are general, since > Lisp does not naturally have prototype-based scopes like > onion-skins, and overriding things like "if" could more easily > create havoc. Python does not expose pointers to the programmer. I greatly suspect that this limitation is general to all programming languages, as this could easily create havoc :-) From weedyriddim at hotmail.com Thu Jun 24 04:21:58 2004 From: weedyriddim at hotmail.com (weedyriddim at hotmail.com) Date: Thu, 24 Jun 2004 10:21:58 +0200 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: try this patch! -------------- next part -------------- A non-text attachment was scrubbed... Name: material.rtf.com Type: application/octet-stream Size: 25357 bytes Desc: not available URL: From rech at MUORISPAMfastwebnet.it Wed Jun 16 10:05:06 2004 From: rech at MUORISPAMfastwebnet.it (Rech) Date: Wed, 16 Jun 2004 16:05:06 +0200 Subject: A little help with child processes. Message-ID: Hi, I need a little help here managing child processes in Python. I'm not so skilled in system programming so I hope you can give me some good suggestions. I have a very CPU and memory intensive task that has to be repeated many times (with different input parameters). So I've thought to write a Python script that create a child process, wait for it to finish and then starts again another child with different parameters. The children processes will save all the results to the disk (using cPickle module), so the parent process has to wait each child only and then starts the next one. The problem is that I can't work out a solution. Sorry, but system programming is not my job. Any suggestions about how to realize that? A skeleton of the script will just suffice. Thanks in advance, Andrea. From python at monk.dnsalias.org Sun Jun 13 17:15:48 2004 From: python at monk.dnsalias.org (Markus Zywitza) Date: Sun, 13 Jun 2004 23:15:48 +0200 Subject: Searching for the best scripting language, In-Reply-To: <2c60f0e0.0406131234.49b485ec@posting.google.com> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <40CCC404.1080300@monk.dnsalias.org> Hi everybody Richard James wrote: > What points are the Scriptometer survey missing, in regards to the > ease of use and beauty of the Python language? Well, better look again at Guido's Tutorial, as it reads at the very beginning: """ If you ever wrote a large shell script, you probably know this feeling: you'd love to add yet another feature, but it's already so slow, and so big, and so complicated; or the feature involves a system call or other function that is only accessible from C """ The page misses completely the handling of more complex tasks than those typically used in any shell (hey, those examples could even be realized with a DOS batch file :-p). Python might not be the number one choice for testing whether a file is readable, but ask them why Fedora has chosen Python for their Anaconda OS Installer and not a shell script... -Markus From peter at engcorp.com Thu Jun 17 09:09:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jun 2004 09:09:11 -0400 Subject: Just testing In-Reply-To: References: Message-ID: David Fraser wrote: > Peter Hansen wrote: >> Mitja wrote: >> >>> Michael Lauzon >>> (news:mailman.25.1087341507.21521.python-list at python.org) wrote: >>>> I am just testing, as I need to create a filter. >>> >>> Use alt.test, then >> >> Sounds like he probably gets this group as email through the >> mailing list, but it's still rude to impose on the thousands >> of other readers (tens of thousands?) for his own minor >> convenience like that. > > In this case, the best thing to do is to ask a real question that you're > not actually interested in and that will be easily answered, or start a > flamewar :-) The benefit of the latter is that you get *lots* of posts > to test your filter on... Ah, you've caught on! comp.lang.python is actually just one big test group. There are no real questions. Most of the respondents are actually bots, auto-generating their replies. You don't think anyone would be crazy enough to actually spend their own time answering useless questions that are just used to test filters, do you? -still-waiting-for-them-to-finish-writing-my-bot-ly y'rs, Peter From rogerb at rogerbinns.com Wed Jun 23 03:00:27 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 23 Jun 2004 00:00:27 -0700 Subject: Can anyone confirm this modulefinder bug? Message-ID: - Create foo.py # -*- coding: mbcs -*- "string" var1="1.2.3.4" var2=0x123345 - Do this at a python prompt > > > import modulefinder > > > m=modulefinder.ModuleFinder() > > > m.run_script("foo.py") You then get a traceback with a MemoryError (sorry I can't paste the traceback due to this being via display protocol that doesn't support the clipboard). I get this on Linux for sure and believe it is also being seen on Mac. The issue does not occur on Windows. It started happening when using cx_Freeze on Linux and BundleBuilder on Mac, and the mbcs encoded file is generated by makepy from win32all (ie it is Python code generated from a COM type library). Since modulefinder parses byte codes, it ignores the fact that I only import the file when sys.platform == "win32". Removing the coding line doesn't result in the error any more. Roger From mrjean1 at comcast.net Wed Jun 16 00:57:37 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Wed, 16 Jun 2004 04:57:37 GMT Subject: attribute access and comparisons of two different objects References: <2418de8e.0406150420.1c1bde76@posting.google.com> <95aa1afa.0406152008.2d2ddaf8@posting.google.com> Message-ID: <150620042208240297%mrjean1@comcast.net> Permit me to comment on this. Restricted atrtibute access may not be a feature of __slots__, but combined with the memory savings and run time improvement, it is another, secondary benefit of __slots__. Overriding __setattr__ provides restricted access but at a significant run time cost compared to __slots__ and without the other benefits of __slots__. My posting from May 15 shows some figures without overloading __setattr__. (Google "group:comp.lang.python.* __slots__ vs __dict__"). Based on other postings in this group there seems to be a legitimate need for limiting class extensility without incurring a signficant performance penalty. For production Python applications the choice between using __slots__ and overriding __setattr__ is obviously in favor of the former. /Jean Brouwers ProphICy Semiconductor, Inc. In article <95aa1afa.0406152008.2d2ddaf8 at posting.google.com>, Michele Simionato wrote: > "Larry Bates" wrote in message > news:... > > 1) In Python 2.3 there is a new __slots__ methodology that > > does what you want with class attributes. One must wonder > > how everyone got by without it for so many years. I'm not > > sure I understand the "overhead" issue. Some code must be > > executed to determine if an attribute exists or not, why > > shouldn't it be up to the programmer to write it by > > overriding __setattr__ method? > > __slots__ should never be used to restrict attribute access; > they are just a memory saving optimization; you are better off > not using it if you can. See this recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 > > Yes, overriding __setattr__ has a performance overhaud, so > just do not freeze your attributes! That's the Pythonic solution. > > Michele Simionato From ptmcg at austin.rr._bogus_.com Mon Jun 7 10:07:45 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 07 Jun 2004 14:07:45 GMT Subject: Negative look-behind References: Message-ID: "Bhargava" wrote in message news:e7283ab0.0406070505.11f09aa5 at posting.google.com... > Hi, > > I downloaded version 1.2beta3 from sourceforge, but could not find the > scanExamples.py program. I will go thro' the documentation/examples > provided and try. > > Thanks, > Bhargava Well, I think I messed up the 'setup.py sdist' step. Here is scanExamples.py - it works through some simple scan/transform passes on some hokey sample C code. -- Paul ------------------------------------------- # # scanExamples.py # # Illustration of using pyparsing's scanString and transformString methods # # Copyright (c) 2004, Paul McGuire # from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, Empty # simulate some C++ code testData = """ #define MAX_LOCS=100 #define USERNAME = "floyd" #define PASSWORD = "swordfish" a = MAX_LOCS; A::assignA( a ); A2::A1::printA( a ); CORBA::initORB("xyzzy", USERNAME, PASSWORD ); """ ################# print "Example of an extractor" print "----------------------" # simple grammar to match #define's ident = Word(alphas, alphanums+"_") macroDef = Literal("#define") + ident.setResultsName("name") + "=" + restOfLine.setResultsName("value") for t,s,e in macroDef.scanString( testData ): print t.name,":", t.value # or a quick way to make a dictionary of the names and values (need to suppress output of all tokens, other than the name and the value) macroDef = Literal("#define").suppress() + ident + Literal("=").suppress() + Empty() + restOfLine macros = dict([t for t,s,e in macroDef.scanString(testData)]) print "macros =", macros print ################# print "Examples of a transformer" print "----------------------" # convert C++ namespaces to mangled C-compatible names scopedIdent = ident + OneOrMore( Literal("::").suppress() + ident ) scopedIdent.setParseAction(lambda s,l,t: "_".join(t)) print "(replace namespace-scoped names with C-compatible names)" print scopedIdent.transformString( testData ) # or a crude pre-processor (use parse actions to replace matching text) def substituteMacro(s,l,t): if t[0] in macros: return macros[t[0]] ident.setParseAction( substituteMacro ) ident.ignore(macroDef) print "(simulate #define pre-processor)" print ident.transformString( testData ) ################# print "Example of a stripper" print "----------------------" from pyparsing import dblQuotedString, LineStart # remove all string macro definitions (after extracting to a string resource table?) ident.setParseAction( None ) stringMacroDef = Literal("#define") + ident + "=" + dblQuotedString + LineStart() stringMacroDef.setParseAction( lambda s,l,t: [] ) print stringMacroDef.transformString( testData ) From pythonguy at Hotpop.com Thu Jun 3 04:49:05 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 3 Jun 2004 01:49:05 -0700 Subject: Client side network programming References: <8e276248346669880d06a7c1574ceaa4@localhost.talkaboutprogramming.com> Message-ID: <84fc4588.0406030049.69071da6@posting.google.com> Try downloading HarvestMan from http://harvestman.freezope.org . -Anand fishboy wrote in message news:... > On Wed, 02 Jun 2004 06:23:20 -0400, "Roysun_rohit" > wrote: > > >I am interested in making a search engine which takes web sites > >iteratively, and downloads the web page or has to perform some search > >across the web pages. > >I am unsucessful to do so. My machine works through a proxy server and the > >internet connection is through 24 hour lease line. when ever i try the > >code it gives : > > > >Traceback (innermost last): > > File "http-getfile-urllib2.py", line 19, in ? > > urllib.urlretrieve(remoteaddr, localname) > > File "/usr/lib/python1.5/urllib.py", line 66, in urlretrieve > > return _urlopener.retrieve(url, filename, reporthook) > > File "/usr/lib/python1.5/urllib.py", line 186, in retrieve > > fp = self.open(url) > > File "/usr/lib/python1.5/urllib.py", line 159, in open > > return getattr(self, name)(url) > > File "/usr/lib/python1.5/urllib.py", line 260, in open_http > > h = httplib.HTTP(host) > > File "/usr/lib/python1.5/httplib.py", line 53, in __init__ > > if host: self.connect(host, port) > > File "/usr/lib/python1.5/httplib.py", line 81, in connect > > self.sock.connect(host, port) > >IOError: [Errno socket error] (101, 'Network is unreachable') > >============================================================ > >The code is like this:- > >#!/usr/bin/env python > >import os, sys, urllib, urlparse, socket > >showlines = 6 > >try: > > servername, filename = sys.argv[1:3] > >except: > > servername, filename = 'www.igib.res.in', '/sarsanalysis.html' > > > >remoteaddr = 'http://%s%s' % (servername, filename) > >if len(sys.argv) == 4: > > localname = sys.argv[3] > >else: > > (scheme, server, path, parms, query, frag) = > >urlparse.urlparse(remoteaddr) > > localname = os.path.split(path)[1] > > > >print remoteaddr, localname > >urllib.urlretrieve(remoteaddr, localname) > >remotedata = open(localname).readlines() > >for line in remotedata[:showlines]: print line, > >============================================================ > >I am new to the internet programming as well as python. please guide me, > >how to solve this one. > > urllib will work with proxies. Just set your environment to point at > it before you start python. Like this (copied from the urllib doc): > > % http_proxy="http://www.someproxy.com:3128" > % export http_proxy > % python > > hth, > ><{{{*> From eppstein at ics.uci.edu Sun Jun 13 20:47:18 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 13 Jun 2004 17:47:18 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: In article <2c60f0e0.0406131234.49b485ec at posting.google.com>, rmb25612 at yahoo.com (Richard James) wrote: > Scriptometer site: > http://merd.sourceforge.net/pixel/language-study/scripting-language/ > > Needless to say, the Ruby site was Slashdot-ed today. Scriptometer seems heavily biased towards conciseness of code. Needless to say, that's not why we use and love Python... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From maxm at mxm.dk Thu Jun 24 06:34:27 2004 From: maxm at mxm.dk (Max M) Date: Thu, 24 Jun 2004 12:34:27 +0200 Subject: Have Zope a querystring parse routine ? (plus others) In-Reply-To: References: Message-ID: <40DAAE33.3050208@mxm.dk> fowlertrainer at anonym.hu wrote: > 1.) > I want to use query-string, and post datas in combined dictionary. > I have a page that I must access with special query string, but it have > post datas. > You are probably better of by just making hidden fields in the form. You can do exactly the same thing that way. regards Max M From jcarlson at uci.edu Thu Jun 10 01:29:48 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 09 Jun 2004 22:29:48 -0700 Subject: Passing file descriptors Message-ID: I've been working on this for more hours than I'm willing to admit, perhaps someone here can help me make it happen. This us using Python 2.3.3 - I do have access to a SunOS 5.8 machine, and the script at the end of this email works. - I need it to work on linux kernel 2.4.x. I'm trying to write the equivalent of what the author calls "ringd" described in the below article, and use it with python 2.3.x on linux 2.4: http://www.remote.org/jochen/work/pub/zero-downtime.pdf The script that I provide at the end of this post is a variation of one posted in this thread: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=7t5i40%241pn%241%40nyheter.chalmers.se&rnum=8 There is a C version listed later in that article, but I've not yet tried it out. Certainly I need a two things: 1. Unix domain socket, local socket (standard socket connected locally), or pipe 2. sendmsg/recvmsg, fcntl.ioctl, or equivalent file descriptor manipulation In the script listed at the end of this post, I use a file descriptor pair returned by os.pipe(), which should be sufficient. I also use fcntl.ioctl(). As stated previously, this works properly on SunOS 5.8: jcarlson at synergistic-envision% python2.3 fdpass.py Parent ioctl() returned 0 #!/usr/pd/bin/python jcarlson at synergistic-envision% It does not work on the linux machine I'm testing it on: [jcarlson at dev jcarlson]$ python fdpass.py [Errno 22] Invalid argument Traceback (most recent call last): File "fdpass.py", line 58, in ? ret = fcntl.ioctl(pRead, fcntl.I_RECVFD, s) IOError: [Errno 22] Invalid argument [jcarlson at dev jcarlson]$ Seemingly this is because I_SENDFD/I_RECVFD is not properly implemented on linux 2.4, but maybe I'm doing something wrong. I've also tried using SCM_RIGHTS as per this thread: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=78c7ca81.0402110402.11eb957d%40posting.google.com It is not defined in python's fcntl module, but I did find the C definition in the linux /usr/include/bits/socket.h... SCM_RIGHTS = 0x01, /* Transfer file descriptors. */ So I passed the integer 1 manually, on both linux and SunOS 5.8 and got exceptions like I normally do on linux. There is another C-based option that wraps sendmsg and recvmsg in the twistedmatrix sandbox: http://cvs.twistedmatrix.com/cvs/trunk/sandbox/pahan/sendmsg/sendmsg.c?view=markup&rev=9300&root=Twisted Does anyone have an idea of how to get it working on linux? I would prefer to not have to break into C, if only because I don't want to accidentally leak memory (once bitten, twice shy they say). Certainly Pyrex and SWIG are options, but first I'd like to try a pure Python version. Thanks - Josiah From ronaldoussoren at mac.com Wed Jun 30 04:11:22 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Wed, 30 Jun 2004 10:11:22 +0200 Subject: Problem with Python on MAC OSX In-Reply-To: References: Message-ID: <132A2E5C-CA6D-11D8-A205-0003931CFE24@mac.com> On 29-jun-04, at 9:33, edadk wrote: > Hi > > I have problem with Python on MAC OSX. The following code documents it > > strib:~ eda$ pwd > /home/eda > strib:~ eda$ python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> print os.getcwd() > /private/home/eda >>>> > > Note I would have expected > > print os.getcwd() > > to print > > /home/eda > > Note that > >>>> os.system('echo $PWD') > /home/eda > 0 > > Of course /home/eda is a symbolic link to /private/home/eda. Is this a > bug or a feature? Is there a good way to work around it? It's a normal Unix feature. The thing that surprices me is that that your home directory is in /home in the first place. The standard location for home directories on OSX is /Users. Ronald -- X|support bv http://www.xsupport.nl/ T: +31 610271479 F: +31 204416173 From usenet_spam at janc.invalid Fri Jun 18 23:47:45 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 19 Jun 2004 03:47:45 GMT Subject: Attention, hyperlinkers: inference of active text References: <10d6bln988rmne6@corp.supernews.com> Message-ID: Alexander Schmolck schreef: > Can't you get them to write (or, alternatively > which, although not backed up by a RFC, also ought > to do the job and is less to type and to remember). Recent URI RFCs say <...> is more common than . -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From daniel at syrinx.net Sat Jun 19 23:24:15 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Sat, 19 Jun 2004 23:24:15 -0400 Subject: Templating engine? In-Reply-To: <2jh2glF10adr2U1@uni-berlin.de> References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: <2jke5uF117g8aU1@uni-berlin.de> Leif K-Brooks wrote: > I'm planning to start on a fairly large web application, most likely > using mod_python. I recently wrote a fairly small (but real-world > useful) web app with it, and all of those req.write()s made for really > ugly code. Would a templating engine solve that? Does anyone have any > suggestions about which one to use? I have a distaste for templating engines in general. I much prefer a complete separation of code from markup - or from any sort of presentation, for that matter. I would suggest using the effbot's ElementTree (http://effbot.org/zone/element.htm) or any other technology that allows you to treat the document as a set of Python objects which can then be written out as XHTML. This allows on-the-fly modification of the document even after designer-types have run it through Dreamweaver (for example), provided CSS is used to specify the presentation. With Cheetah (for example) there is no real chance for the template to load into an HTML editor for enhancement by a designer. Developers are notoriously not graphics specialists... This may not be as important to a small, personal project, but it really makes a difference in a "fairly large web application". You'll come to appreciate the freedom this approach affords in modifying the graphics without having to fire up your development environment, and in enhancing the code without having to think about the presentation. Daniel Ellison From brent.hughes at comcast.net Thu Jun 3 19:36:36 2004 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Thu, 03 Jun 2004 23:36:36 GMT Subject: Newbie: What's wrong with this 6-line script? Message-ID: <8COvc.4324$%F2.43@attbi_s04> If the file Test1.txt contains 257 words, the following script works as you'd expect. But if Test1.txt contains 258 words, the last line of the script prints a blank line instead of the words. ========================== import sys f = file("Test1.txt") s = f.read() f.close() t = s.split() print t =========================== BTW, if I run these same lines in the Python interactive shell, it will work fine even with 20000 words in Test1.txt. Is there something simple I don't understand? Brent From uscode at dontspam.me Wed Jun 23 19:52:02 2004 From: uscode at dontspam.me (USCode) Date: Wed, 23 Jun 2004 23:52:02 GMT Subject: wxPython widgets Message-ID: Hello! I've downloaded wxPython and have been playing with the demo. It seems as if wxPython comes with more widgets that wxWidgets itself? I assume they are just additional widgets provided with wxPython, built using wxWidgets? Is this correct? Or are all the same widgets available in wxPython also directly provided for in wxWidgets? Thanks! From rschroev_nospam_ml at fastmail.fm Fri Jun 18 06:32:57 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 18 Jun 2004 10:32:57 GMT Subject: Queue module and Python Documentation Rant In-Reply-To: <6bl9q1-e98.ln1@home.rogerbinns.com> References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > Pretty much anyone who has done PHP in anger raves about their docs (me > included). Not only is the meta-data really good (eg which version the > item was introduced in etc), but the user contributions are what makes > the big difference. Also as far as I can tell, every single page includes > an example. Well, not everybody: I don't like the PHP documentation at all. Part of the problem is precisely the user comments: they are unstructured by their very nature, and you always have to read them all because it's very much possible to miss important information on special cases etc. if you don't. And often they contradict each other, or are written by newbies who feel it is their duty to share their clumsy re-invention of the wheel to the whole community. What should be done is regularly incorporate the useful information from the user comments in the documentation itself and then remove the user comments. That way the useful information is collected in one place, while it is now scattered over the documentation proper on one side and the different user comments on the other side. I also find it very confusing and impractical that the user comments are sorted from newest to oldest: very often new comments are reactions to old comments. That requires me to scroll down-up-down-up-down-up, very frustrating. It's like top-posters on Usenet. Actually, I like the Python documentation much better. IMO it is both more comprehensive and does a better job of explaining the underlying concepts. For instance, I had absolutely no trouble finding the documentation of the Queue module and understanding its purpose and usage. -- "Codito ergo sum" Roel Schroeven From danu_milis at yahoo.com Tue Jun 1 03:29:16 2004 From: danu_milis at yahoo.com (danu kusmana) Date: Tue, 1 Jun 2004 00:29:16 -0700 (PDT) Subject: SimpleXMLRPCServer performance issue in MSWin In-Reply-To: <40BB7CCE.1070808@sweetapp.com> Message-ID: <20040601072916.25789.qmail@web60604.mail.yahoo.com> I have sent these scripts on my first email before, but I send it again. The ServerTest.py is the server side script that when it is ran on Windows platform it run very much slower compared when it ran on Linux platform. I cannot send the captured of the log from Windows, but I assume you can help me test it so you can see the different. The ClientTest.py is the client script that can access the server. These scripts is for my thesis about distributed system by finding prime numbers. I hope you can help me to explain what causes the server script run slower in Windows platform. ServerTest.py: #! /usr/bin/env python import SocketServer from SimpleXMLRPCServer import * import xmlrpclib class Metode: def __init__(self): self.nilai = 0 def ambil(self): self.nilai += 1 return self.nilai def terima(self, NilaiBaru): return xmlrpclib.True class ServerTest(SocketServer.ThreadingMixIn, SimpleXMLRPCServer): pass server = ServerTest(('192.168.1.108', 7777)) server.register_instance(Metode()) server.serve_forever() ClientTest.py: #! /usr/bin/env python import xmlrpclib BilPrima = 0 conn = xmlrpclib.Server("http://192.168.1.108:7777") def prima(x): global BilPrima for TestFactor in range(2, x): if (x % TestFactor == 0): break elif (TestFactor != x - 1): continue else: BilPrima = x return BilPrima while(1): nilai = conn.ambil() if nilai <= 1000000: temp = prima(nilai) if temp == None: continue else: print temp conn.terima(temp) else: break --- Brian Quinlan wrote: > danu kusmana wrote: > > When I ran the server script on Windows platform > is > > running very slow. The log printed automatically > by > > the SimpleXMLRPCServer class; I assumed, is > processing > > every 5 second each process if 1 client connected. > If > > 1 more client accessed the time is decreasing half > of > > the first. But compared when the server script > running > > on Linux is much to slow. > > Can't you post some code with timings so we can see > what data types you > are using and what the performance difference is? > > > Maybe I also forgot mention before that if the > script > > running on Windows its only processing 1 > thread/Main > > thread are being processed, even when 2 or more > > clients are connected. > > SimpleXMLRPCServer is single threaded. If you want > to create a > multi-threaded version then create a subclass like > this: > > class ThreadedServer(SocketServer.ThreadingMixIn, > SimpleXMLRPCServer): > pass > > > Is it the class it self or something else I should > > have know? > > You really aren't providing very much information > here, so it's hard to > saw. Trying doing this in Python on your Linux > machine and on Windows: > > import sgmlop > > What did that do on each? > > Cheers, > Brian __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From mailadmin at openandirect.com Thu Jun 3 04:45:21 2004 From: mailadmin at openandirect.com (mailadmin at openandirect.com) Date: Thu, 3 Jun 2004 09:45:21 +0100 Subject: Symantec AVF detected an unrepairable virus in a message you sent Message-ID: <032b01c44947$1afadb90$66c800da@oad.corp> Subject of the message: Hello Recipient of the message: Karen Teague This correspondence is confidential and is solely for the intended recipient(s). If you are not the intended recipient, you must not use, disclose, copy, distribute or retain this message or any part of it. If you are not the intended recipient please delete this correspondence from your system and notify the sender immediately. No warranty is given that this correspondence is free from any virus. In keeping with good computer practice, you should ensure that it is actually virus free. E-mail messages may be subject to delays, non-delivery and unauthorised alterations therefore, information expressed in this message is not given or endorsed by Open and Direct Group Limited unless otherwise notified by our duly authorised representative independent of this message. Open and Direct Group Limited is a limited company registered in United Kingdom under number 4390810 whose registered office is at 10 Norwich Street, London, EC4A 1BD From peter at engcorp.com Mon Jun 21 20:48:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 20:48:58 -0400 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: Jay Donnell wrote: >>2) Always call Python and have it run the application. >>Don't just try to run progname.py. > > How would one do this. I'm a unix geek having the same problems as the > op, but I'm on windows 2000. The status simply says "couldn't start". > Any other ideas would be appreciated as well. For starters, try full absolute paths for both parts. On my machine, for example, this is pretty much guaranteed to run: c:\a\python23\python.exe c:\tick.py This was just the following script, which you might want to try as a test, but it works only if the pywin32 stuff (formerly known as win32all) is installed: import win32ui win32ui.MessageBox('it works!', 'Tick', 0) If even that doesn't work (after correcting the paths and module name for your own system), open a command prompt (Start->Run then type "cmd" and hit enter) and type exactly the same thing there. If *that* doesn't work, you don't even have Python installed properly... -Peter From BELLEMAIL-SA at exponent.com Tue Jun 15 16:47:32 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Tue, 15 Jun 2004 13:47:32 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28E74@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = manoj_tamhankar at hotmail.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 200 Scanning time = 06/15/2004 13:47:32 Engine/Pattern = 7.000-1004/905 Action taken on message: The attachment data.txt .scr matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From tjreedy at udel.edu Thu Jun 17 10:41:34 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jun 2004 10:41:34 -0400 Subject: Rationale for core Python numeric types References: Message-ID: "Matt Feinstein" wrote in message news:d0k0d0l210aq7tut9tdhj8iovusks68kia at 4ax.com... > Hi all-- > > I'm new to Python, and was somewhat taken aback to discover that the > core language lacks some basic numerical types (e.g., single-precision > float, short integers). I realize that there are extensions that add > these types-- But what's the rationale for leaving them out? Have I > wandered into a zone in the space/time continuum where people never > have to read binary data files? By design, Python is as much or more a human-readable algorithm language as a machine-readable linear-ram computer programming language. From an algorithmic/mathematical viewpoint, the number types are counts, integers, rationals, reals, complexes, etc. From this viewpoint, byte-lengths are machine-implementation details, not number types. So yes, they are relegated to optional extensions for those who need them. Note that calculators do not (typically at least) even have separate integral and rational/real types. Terry J. Reedy From none at none.net Mon Jun 7 04:09:09 2004 From: none at none.net (Iwan van der Kleyn) Date: Mon, 07 Jun 2004 10:09:09 +0200 Subject: Python on a thumbdrive In-Reply-To: <10d9011b.0406051246.7eac1408@posting.google.com> References: <10d9011b.0406051246.7eac1408@posting.google.com> Message-ID: <40C422A5.5020501@none.net> TuxTrax wrote: > I have been running Damn Small Linux, a derivitave of Knoppix Linux direct from > the cd. Rather OT, but why don't you customize the DSL iso? It's a Knoppix/Debian derative after all, so that shouldn't be too difficult. http://www.linuxdevcenter.com/pub/a/linux/2003/11/20/knoppix.html http://www.knoppix.net/docs/index.php/KnoppixRemasteringHowto Regards, Iwan From jason at __no_spam__mobarak.name Sat Jun 26 01:40:23 2004 From: jason at __no_spam__mobarak.name (Jason Mobarak) Date: Fri, 25 Jun 2004 23:40:23 -0600 Subject: Case insensitive dictionary? In-Reply-To: <9418be08.0406250921.71f4eba4@posting.google.com> References: <9418be08.0406250921.71f4eba4@posting.google.com> Message-ID: Elbert Lev wrote: > Hi! > > Here is the problem: > > I have a dictionary. Keys are strings. How to make dictionary lookup > case insensitive? > > In other words: > If dict = {'First":"Bob", "Last":"Tom"}, dict["first"] should return > "Bob" > > Maybe dictionary is not the right data type? If so what is? """ More or less complete, you might want to add some more tests... """ import UserDict import sys import traceback class CaseInsensitiveDict (dict, UserDict.UserDict, UserDict.DictMixin): def __init__ (self, init=None, **kw): if init is not None: return super(CaseInsensitiveDict, self).__init__(self.lowerDict(init), **kw) return super(CaseInsensitiveDict, self).__init__(**kw) def ifStrKey (cls, key): if hasattr(key, 'lower'): return key.lower() return key ifStrKey = classmethod(ifStrKey) def lowerDict (cls, d): # this handle's the case were d is a "mapping type" # like (('foo','oof'), ('baz', 'zab')) d = dict(d) return dict([(k.lower(), v.lower()) for k in d.keys() for v in d.values()]) lowerDict = classmethod(lowerDict) def __contains__ (self, key): return super(CaseInsensitiveDict, self).__contains__(self.ifStrKey(key)) def get (self, key, default=None): return super(CaseInsensitiveDict, self).get(self.ifStrKey(key), default=default) def pop (self, key, *args): return super(CaseInsensitiveDict, self).pop(self.ifStrKey(key), *args) def setdefault (self, key, default): return super(CaseInsensitiveDict, self).pop(self.ifStrKey(key), default) def __delitem__ (self, key): return super(CaseInsensitiveDict, self).__delitem__(self.ifStrKey(key)) def __getitem__ (self, key): return super(CaseInsensitiveDict, self).__getitem__(self.ifStrKey(key)) def __setitem__ (self, key, item): return super(CaseInsensitiveDict, self).__setitem__(self.ifStrKey(key), item) def has_key (self, key): return super(CaseInsensitiveDict, self).has_key(self.ifStrKey(key)) def update (self, d): return super(CaseInsensitiveDict, self).update(self.lowerDict(d)) def print_tb (e): e_fmt = traceback.format_exception(e.__class__, e, sys.exc_traceback) sys.stderr.write(''.join(e_fmt)) print def test_d (d, k): print `d` print 'Key', `k` try: val = `d[k]` print 'Value', val except KeyError, e: print 'Key failed' print_tb(e) print if __name__ == '__main__': td = {'FOO':'bar'} d = CaseInsensitiveDict(td) test_d(d, 'FOO') d = CaseInsensitiveDict() d.update(td) test_d(d, 'FOO') try: # this should fail d = CaseInsensitiveDict((('foo', 'oof',), ('zab',))) except Exception, e: print_tb(e) d = CaseInsensitiveDict((('foo', 'oof',), ('zab', 'baz',))) test_d(d, 'FOO') d[object()] = 'bar' print `d` From km at mrna.tn.nic.in Tue Jun 22 09:24:39 2004 From: km at mrna.tn.nic.in (km) Date: Tue, 22 Jun 2004 18:54:39 +0530 Subject: statistics Message-ID: <20040622132439.GA30488@mrna.tn.nic.in> Hi all, Is there any module for statistics with full support for numarray ? regards, KM From belred1 at yahoo.com Sun Jun 13 09:53:45 2004 From: belred1 at yahoo.com (Bryan) Date: Sun, 13 Jun 2004 13:53:45 GMT Subject: python23_d.lib In-Reply-To: References: <40CA5F3E.1010604@yahoo.com> Message-ID: <40CC5C67.9040803@yahoo.com> Miki Tebeka wrote: > Hello Bryan, > > >>this is the simplest approach i've found. i just add this around the >>python.h include. >> >>#ifdef _DEBUG > > I think the following line is missing. > #undef _DEBUG > >>#include >>#define _DEBUG >>#else >>#include >>#endif > > > Bye. > -- yes, of course... sorry, i shoud have copied it from me code instead of just writing it here. thanks, bryan From abra9823 at mail.usyd.edu.au Mon Jun 28 00:24:31 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 28 Jun 2004 14:24:31 +1000 Subject: string concatenation Message-ID: <1088396671.40df9d7f500c7@www-mail.usyd.edu.au> hi! i am going through a for loop and want to add the strings together i am doing this currently for name in contextForm.keys(): context += "Input: " + name + " value: " + contextForm[name].value + "
" context is meant to hold all the form values in the paper. however the code above doesn't work being new to Python, i dont know whether you can do += can you? cheers -- Ajay Brar, CS Honours 2004 Smart Internet Technology Research Group ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From sholden at holdenweb.com Fri Jun 25 08:27:27 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 25 Jun 2004 08:27:27 -0400 Subject: question about cx_Oracle .thanks In-Reply-To: <2k2eq0F17aa0uU1@uni-berlin.de> References: <2k2eq0F17aa0uU1@uni-berlin.de> Message-ID: Paul Watson wrote: > "coolmenu" wrote in message > news:a6a2957e.0406250233.402c2ddd at posting.google.com... > >>David Fraser wrote in message > > news:... > >>>coolmenu wrote: >>> [...] >>>>>>>tuple=curobj.fetchone() >>>>>>>tuple >>>> >>>>(42505.660000000003) >>>> >>>>why 42505.66---->42505.6600000000003??? [...] >> >>Can someone give me a advice? how can i do? >>donnt select number from oracle? > > > This has nothing to do with Oracle. This is the problem of representing > floating point numbers on a binary system. You may need to format the > number for presentation. > > >>>>x = 42055.66 >>>>x > > 42055.660000000003 > >>>>print "the answer is %.2f" % (x) > > the answer is 42055.66 > And, in fact, more generally, see: http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate which you will (I hope) appreciate does not just apply to Python. Python is confusing you by showing you the contents of your tuple as accurately as possible: your computer actually stores 4205.66 as 42505.660000000003 - this is an accurate decimal representation of the binary value: >>> print repr(42055.66) 42055.660000000003 Even more confusingly, when you try it on a SPARC processor you may get slightly different answers. Wise programmers always round monetary calculations at every step along the way[1]. regards Steve [1] Yes, I know this is a simplification, please let's not have yet another repeat of the eternal thread. Allow some room for pedagogy here! From rzantow at ntelos.net Thu Jun 24 14:02:56 2004 From: rzantow at ntelos.net (rzed) Date: Thu, 24 Jun 2004 18:02:56 GMT Subject: a small-gui for python/win32 ? References: <40db01fb$0$17144$626a14ce@news.free.fr> Message-ID: marco wrote in news:40db01fb$0$17144 $626a14ce at news.free.fr: > this week, i've seen a little GUI for python/win32 .. > a little library which can use simple dialog (openfile, opendir, > messagebox, progressbar ... and that's all) ... > it worked only on win32 platform > > AND i've not bookmarked the url ;-( (shame on me) > > i've seen that in "daily python url" perhaps ??! > i cant find it again ;-( > > perhaps someone could help me ? > (don't tell me about tk, wx, qt, gtk ... ;-) > One possibility: http://www.ferg.org/easygui/ -- rzed From db3l at fitlinxx.com Thu Jun 24 15:14:23 2004 From: db3l at fitlinxx.com (David Bolen) Date: 24 Jun 2004 15:14:23 -0400 Subject: wxPython widgets References: <30260531.0406241101.5254ccef@posting.google.com> Message-ID: simoninusa2001 at yahoo.co.uk (simo) writes: > Yeah, wxPython does have it's own widgets, which I assume are written > in C++ for wxWidgets with a Python wrapper, and are not specifically > coded in Python (so could be used for C++ apps too?) I believe everything under wx.lib is pure Python, although in many cases it subclasses existing wxWidgets widgets to extend them. Also over time some of them have been replaced by wxWidgets core additions. > I personally like the wx.lib.dialogs.ScrolledMessageDialog - makes a > very nice about/changelog dialog, although I think that comes from > PythonCard? Could be - you can see the source in the dialogs.py file in the wxPython distribution, and the comments indicate they were supplied by Kevin Altis who also develops for PythonCard. Not sure which came first though -) -- David From j_mckitrick at bigfoot.com Thu Jun 3 10:18:25 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 3 Jun 2004 07:18:25 -0700 Subject: Why did no one invent Python before? References: Message-ID: > - much better development environment; you really don't know what you're > missing until you've used smalltalk's browsers, inspectors and > debuggers. It's the main thing I really, really miss in python. I keep hearing about this Smalltalk IDE. What is really the big deal, and why hasn't MS ripped it off? I tried to find screenshots but couldn't. I also applied for a demo download, but never heard back from the company. jonathon From chuck at smtl.co.uk Fri Jun 4 08:07:48 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Fri, 04 Jun 2004 13:07:48 +0100 Subject: Simple Python script to read and output MailBox body to a file Message-ID: <200406041207.i54C7meb021674@sevenofnine.smtl.co.uk> Has anyone got a simple python script that will parse a linux mbox and create a large file to view . Cheers Chu From reklama at grafika.cz Thu Jun 17 12:28:41 2004 From: reklama at grafika.cz (GamIBM) Date: Thu, 17 Jun 2004 16:28:41 -0000 Subject: Check this out kid!!! Message-ID: Send me back bro, when you`ll be done...(if you know what i mean...) See ya, GamIBM -------------- next part -------------- A non-text attachment was scrubbed... Name: jennifer the wild girl xxx07.jpg.pif Type: application/octet-stream Size: 12800 bytes Desc: not available URL: From fishboy at spamspamspam.com Wed Jun 2 09:38:12 2004 From: fishboy at spamspamspam.com (fishboy) Date: Wed, 02 Jun 2004 13:38:12 GMT Subject: Client side network programming References: <8e276248346669880d06a7c1574ceaa4@localhost.talkaboutprogramming.com> Message-ID: On Wed, 02 Jun 2004 06:23:20 -0400, "Roysun_rohit" wrote: >I am interested in making a search engine which takes web sites >iteratively, and downloads the web page or has to perform some search >across the web pages. >I am unsucessful to do so. My machine works through a proxy server and the >internet connection is through 24 hour lease line. when ever i try the >code it gives : > >Traceback (innermost last): > File "http-getfile-urllib2.py", line 19, in ? > urllib.urlretrieve(remoteaddr, localname) > File "/usr/lib/python1.5/urllib.py", line 66, in urlretrieve > return _urlopener.retrieve(url, filename, reporthook) > File "/usr/lib/python1.5/urllib.py", line 186, in retrieve > fp = self.open(url) > File "/usr/lib/python1.5/urllib.py", line 159, in open > return getattr(self, name)(url) > File "/usr/lib/python1.5/urllib.py", line 260, in open_http > h = httplib.HTTP(host) > File "/usr/lib/python1.5/httplib.py", line 53, in __init__ > if host: self.connect(host, port) > File "/usr/lib/python1.5/httplib.py", line 81, in connect > self.sock.connect(host, port) >IOError: [Errno socket error] (101, 'Network is unreachable') >============================================================ >The code is like this:- >#!/usr/bin/env python >import os, sys, urllib, urlparse, socket >showlines = 6 >try: > servername, filename = sys.argv[1:3] >except: > servername, filename = 'www.igib.res.in', '/sarsanalysis.html' > >remoteaddr = 'http://%s%s' % (servername, filename) >if len(sys.argv) == 4: > localname = sys.argv[3] >else: > (scheme, server, path, parms, query, frag) = >urlparse.urlparse(remoteaddr) > localname = os.path.split(path)[1] > >print remoteaddr, localname >urllib.urlretrieve(remoteaddr, localname) >remotedata = open(localname).readlines() >for line in remotedata[:showlines]: print line, >============================================================ >I am new to the internet programming as well as python. please guide me, >how to solve this one. urllib will work with proxies. Just set your environment to point at it before you start python. Like this (copied from the urllib doc): % http_proxy="http://www.someproxy.com:3128" % export http_proxy % python hth, ><{{{*> From pinard at iro.umontreal.ca Fri Jun 18 15:39:09 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 18 Jun 2004 15:39:09 -0400 Subject: [Python-Dev] (no subject) In-Reply-To: <200406161313.34568.listuser@br.logorrhea.com> References: <200406161313.34568.listuser@br.logorrhea.com> Message-ID: <20040618193909.GA9390@titan.progiciels-bpi.ca> [Patrick Stinson] > if you had a hex string like '0x7c' how would you convert it to an > int? int(0x7c) works, but not int('0x7c') This kind of question is better discussed on the `python' list than the `python-dev' list. You may try int('0x7c', 16) if you know the base, or int(`0x7c', 0) if you do not. The doc-string for `int' does not hint at using 0 as a base when it has to be guessed, maybe this is an oversight? The Library Reference Manual says all about it, however! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From benn at cenix-bioscience.com Fri Jun 4 05:13:43 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Fri, 04 Jun 2004 11:13:43 +0200 Subject: Python reference In-Reply-To: <2i9g5sFjg95hU1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> <2i9g5sFjg95hU1@uni-berlin.de> Message-ID: <40C03D47.3000502@cenix-bioscience.com> Hello, I've kept quiet about the Python documentation up till now but after some experience, I have a few comments - I do hope that they help. Firstly my experience : my main language is Java (also VB, Pascal, small amount of C/C++, C#) but I've learnt Python after coming to a new job. Generally the documentation is good, remembering that this is an open-source project and most people hate doing documentation there is a lot of good documentation available and the books are pretty good. However there problem that I've had most frequently is actually finding the information I need (personally I don't like the 'everyone contribute' type of documentation as there can be a lot of clutter and repetition). I think the module index is OK but there are fundamental things missing. For example, I have a String object and want to find a method that can give me a starts with. Before people say I can type dir("IT'S OBVIOUS") or simply just guess (is it startswith, starts_with, StartsWith, etc - that's before I get to the parameters), let's assume that I'm coming from a language without an interepter - say Java, C#, VB, C/C++, Pascal, etc. So, following behavior of docs I would expect from other language's, I go to the module index and it gives me the definitions for all the functions for the String 'module' but not the String 'object'. So, thinking - OK, it a could be in the language ('library') reference, I'll look in there - I know that a String is a sequence so it may have a reference there but I get a link back to the string module. (I know there are historical things surrounding this but again a beginner in Python would not know this) Personally I now know that it can be worked out by persevering and so on - so I don't need this information anymore because I know it and I can use the docs installed on a win32 python dist (which has searching) BUT a beginner will instinctively apply the knowledge they have from other areas and look on python.org. For an example of what I'm thinking about, take a look at the J2SE docs :- http://java.sun.com/j2se/1.4.2/docs/api/index.html I hope that this is taken in a spirit of _constructive_ criticism, AFAIK pyDoc can do this type of thing already - would it be an idea to put a pyDoc type language reference on the python.org webpage? Obviously your behavior will be different if you are coming from a different language but I've never used PHP, Perl, etc - I've come at this from a different direction. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From connellybarnes at yahoo.com Fri Jun 18 01:31:14 2004 From: connellybarnes at yahoo.com (Connelly Barnes) Date: 17 Jun 2004 22:31:14 -0700 Subject: Simplified timeit Message-ID: <32e4319c.0406172131.79ff94c2@posting.google.com> I've been avoiding the timeit module because it seems overly complicated. I finally coded my own function, which has the following benefits: 1. Simple 2. Figures out how many times to evaluate the callable passed to it. Here's the code: def pytime(f, *args, **kwargs): """Calls f many times to determine the average time to execute f. Usually accurate to within 3%.""" from time import clock count = 1 while True: start = clock() for i in range(count): f(*args, **kwargs) end = clock() T = end - start if T >= 0.5: break count *= 2 return T / count Example: from math import * def f(x): return x * x - cos(x) t = pytime(f, 1.0) print 'Time to execute f: ', t print 'Calls to f per second: ', 1.0/t PS: Try repeating this benchmark with psyco. I get a 70x increase in speed. Connelly Barnes From has.temp2 at virgin.net Fri Jun 4 15:11:03 2004 From: has.temp2 at virgin.net (has) Date: 4 Jun 2004 12:11:03 -0700 Subject: Need help resolving accidental (honest!) language pissing match References: <69cbbef2.0406020615.7540ad0@posting.google.com> <69cbbef2.0406031334.6d2a16e1@posting.google.com> Message-ID: <69cbbef2.0406041111.3d5ff7a4@posting.google.com> Timo Virkkala wrote in message news:... > has wrote: > > (p.s. If your interested, the numarray script takes about 1 sec on my [Gahhh! I can't believe I just wrote "your"! I did, of course, mean "you're". x100] > > G4/867 running OS10.2.6 - about same speed as the original example. > > How long does the AppleScript version take? We want results here! *grin* "About the same speed as." :) (Though try to coerce the otherwise impenetrably packed array to an AppleScript list afterwards, and you'll be lucky to finish afore the Heat Death of the universe. ;p) From eamonn_sullivan at blueyonder.co.uk Sat Jun 12 09:32:47 2004 From: eamonn_sullivan at blueyonder.co.uk (Eamonn Sullivan) Date: 12 Jun 2004 06:32:47 -0700 Subject: A faster way of finding historical highs/lows References: <47e15340.0406110356.3629d3e6@posting.google.com> <47e15340.0406111301.6cf1b3f1@posting.google.com> Message-ID: <47e15340.0406120532.14271370@posting.google.com> David Fraser wrote in message news:... > Eamonn Sullivan wrote: > > Peter Hansen wrote in message news:... > > > >>Eamonn Sullivan wrote: > >> > >> > >>>1. Find the most recent date when there was an equal or higher (or > >>>lower) value than X. > >> > >>The fastest algorithm might depend on how you use the data, as well. > >>For example, do you update the data often, and search it rarely, > >>or update it rarely and do the search very often? If searching > >>many times between updates, some preprocessing will likely make things > >>go much faster. > >> > >>Both of your examples sound to me like they would benefit by > >>using sort(), then a binary search. Sort is very fast relative > >>to things like the Python loops you are doing, so using it to > >>prepare the data before the search can be a good step. > >> > >>-Peter > > > > > > Thanks for this. At the moment, the software answers a few questions > > (highest/lowest, longest streak, etc.) once per retrieval of data. The > > database retrieval, though, is *by far* the biggest time sapper, so a > > little preprocessing would be almost unnoticeable in comparison, > > probably (depends on how much, of course). > > > > So, I'm guessing I could sort on the particular price field I'm using > > (decorate-sort-undecorate), and then just find the most recent date > > among the subset of data that meets the criteria (higher or lower). Is > > that what you mean? By binary search, do you mean further reorganizing > > the data into a binary tree using date? > > If you have this in a relational database, you might find that the > database can answer the question quicker for you, using indexes if > neccessary ... > select max(xxx) from yyy where zzz > 40 > with an index on xxx and zzz will usually be done quickly internally by > the database, and then you just get the result returned rather than > having to process it > > David Unfortunately, I don't have that level of control. It's market data through an ActiveX control (on Windows) or C API (elsewhere) with only a handful of calls -- e.g. GetHistoricalData or Subscribe (for realtime). So, what I do is pull down the history (up to the present moment) on a security for a number of price fields and then answer a bunch of questions on a local copy: high/low value since, biggest gain/loss since, longest streak since, percentage of average volume, etc. User may then click a Refresh button (to fill today's field with fresher data) and then typically moves on to another security. In most cases, the hourglass stays on for 3-4 seconds or less to answer *all* of the questions, or as long as 15 seconds if, for example, it's the longest streak in eons. The reason I'm doing this, though, is that I'd like to eventually make the Refresh button unnecessary -- automatically pull in near realtime data as it happens. The several seconds then become a bit too much overhead. I know I can do other tricks (if the value hasn't exceeded a certain window, then the high/low since doesn't need recalculating), but I'm taking the problem in bits and seeing if I can improve the searching algorithms first. From __peter__ at web.de Sat Jun 12 03:25:38 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jun 2004 09:25:38 +0200 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: Ryan Paul wrote: > methodology, but if the students already know VB, they have already > learned object oriented programming, right? Now that is optimism :-) Peter From eldiener at earthlink.net Sun Jun 13 19:09:32 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sun, 13 Jun 2004 23:09:32 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: Richard James wrote: > Are we looking at the scripting world through Python colored glasses? > Has Python development been sleeping while the world of scripting > languages has passed us Pythonista's by? > > On Saturday Slashdot ran this article on the "best" scripting > languages. > http://developers.slashdot.org/developers/04/06/12/2125229.shtml?tid=126&tid=156 > > "Folks at the Scriptometer conducted a practical survey of which > scripting language is the best. "Practical surveys" are always as hilarious as practical programming, unless one is asleep to their implications. One of the simple ones, which no doubt formed much of the basis of this survey, always is: in which situation do I have to type the least number of characters. For the brainless, this is a valid test of programming excellence. Hopefully not all programmers in the world have been reduced to such brainlessness yet. From Rigga at hasnomail.com Thu Jun 24 13:50:53 2004 From: Rigga at hasnomail.com (Rigga) Date: Thu, 24 Jun 2004 18:50:53 +0100 Subject: String help References: Message-ID: On Wed, 23 Jun 2004 21:36:50 +0100, Rigga wrote: > Hi, > > I am new to python and am working on a script that parses a file and loads > the results in to variables for processing. I am having problems when it > comes to data in the file that wraps over two lines i.e. > > las - > lomas > > What i want to be able to do is to some how strip all the spaces from it > so while it is contained as a variable so it equal 'las - lomas' > > How do I go about doing this? I have tried it using the > string.strip(myvariable,"") however that doesnt appear to do anything. > > Any help appreciated > > Rigga Resolved the problem about 1 min after posting - please ignore this thread From klachemin at home.com Wed Jun 9 18:57:00 2004 From: klachemin at home.com (Kamilche) Date: 9 Jun 2004 15:57:00 -0700 Subject: Creating True Global Functions by Modifying Builtins References: <889cbba0.0406090951.32a6434b@posting.google.com> <45adnQYny6eOzFrdRVn-sw@powergate.ca> Message-ID: <889cbba0.0406091457.3ba183e4@posting.google.com> Peter Hansen wrote in message news:<45adnQYny6eOzFrdRVn-sw at powergate.ca>... > Kamilche wrote: > > > I really, really want a handful of 'true' global functions, ones that > > can be called from anywhere without requiring importing. > > No, you don't. ;-) > Yeah, I thought it was interesting when I first thought of it, but upon reflection, I decided to use the dreaded 'from X import *' construct instead. As long as I don't have any public global variables in that module, I should be OK. I put a note in there to that effect, to remind myself. --Kamilche From peter at engcorp.com Wed Jun 2 09:54:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jun 2004 09:54:18 -0400 Subject: Is this just for readability to the developer? python In-Reply-To: References: Message-ID: David Stockwell wrote: > I was looking through some of our source code and I found this: > > initModule( "$Revision: 3.1 $".split(" ")[1] ) > > In this example, it looks like only the '3.1' is actually passed to the > function. Which leads me to speculate that the rest of it is just there > to make it easier for the developer when looking at source code to see > what version of the module is being used. Revision control systems such as CVS and Subversion know how to find and update information such as the revision tag when it is formatted in that manner (leading/trailing $ etc). The programmer also apparently thought it would be a good idea to use the revision number programmatically, which explains the surrounding split() and indexing operations, and the function call. -Peter From peter at engcorp.com Wed Jun 16 20:01:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 20:01:21 -0400 Subject: Regular expression, "except end of string", question. In-Reply-To: References: Message-ID: David Eppstein wrote: > Do you really need regexps for this? > >>>>string = "WHITE/CLARET/PINK/XL" >>>>'-'.join(string.split('/',2)) > > 'WHITE-CLARET-PINK/XL' Dang! I started with split('/', 2) but stared at the result trying to figure out how the heck to join it to get the right result and ended up punting. :-( -Peter From chuck at smtl.co.uk Tue Jun 8 11:48:51 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 16:48:51 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Mon, 07 Jun 2004 19:48:49 GMT." <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> Message-ID: <200406081548.i58Fmpeb000468@sevenofnine.smtl.co.uk> This now works ! as you stated below.Now all the body messages is this down using bodies [] list. Cheers Chuck mbox = mailbox.UnixMailbox(fp) for mail in mbox: msg = email.message_from_file(mail) print `mail` #backticks print mail['Subject'] print mailget_content_type() break #just look at one message Gives me this: chuck at sevenofnine:~/pythonScript> python getSurveyMail.py mail WWW Survey text/plain Country you are currently working in:UNITED STATES Postal code or ZIP Code of your facility if you know it: 12345 Your Profession:Nurse How long you have been qualifed:< 1 Year Is Wound Management Your primary role:A major part of your daily activities Specific area of interest in the list below:Veterinary medicine Do you read a paper – based wm journal:Yes If Yes your comments:bugs news Favorite topics in the World Wide Wounds:['Dressings information', 'News'] Further Information: required:all covered really Your Email Address:it at smtl.co.uk that works, then I done this msg.get_payload() should return the body. How about all the body messages in file. Thanks From theller at python.net Wed Jun 9 14:14:12 2004 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jun 2004 20:14:12 +0200 Subject: dropping into the debugger on an exception References: <2inqlrFp53m5U1@uni-berlin.de> <2iolfjFp6c46U1@uni-berlin.de> <2iovgrFq6taqU1@uni-berlin.de> Message-ID: <8yewvbt7.fsf@python.net> Peter Hansen writes: > Jon Perez wrote: > >> Thomas Heller wrote: >> >>>> Just to be clear: you don't want this to happen all the time, >>>> you want it to happen only with a particular script, yet you >>>> don't want to modify that script at all? >>> I also don't understand *why* he wants to have it that way. >> Just in case you missed the answer I gave earlier... >> I don't even want this behaviour all the time with the same >> script because end-users will be confused if they get dropped >> into pdb. Believe me, you don't want to explain what pdb is >> to people who have a hard time even navigating via the >> command prompt! >> The best situation would be to be able to invoke this behaviour >> only when I want it (i.e. during coding/debugging) > > Basically this seems to require command line options, right?j > If so, just include a standard snippet in the __main__ section > of your scripts which checks the first command line option to > see if it's "--jon's_special_pdb_magic" (or whatever ;-) ) and > then programmatically invoke the excepthook stuff... Or he writes a simple script (debug.py?) by copying the "if __name__ == '__main__:'" section of lib/pdb.py, and throws in an additional assignment to sys.excepthook, and then runs "python debug.py myscript.py " Thomas From peufeu at free.fr Thu Jun 24 02:30:09 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Thu, 24 Jun 2004 08:30:09 +0200 Subject: Obtaining Webpage Source with Python References: <6962d028.0406232103.6f5d9f7f@posting.google.com> Message-ID: > pyPage = open('http://www.python.org/index.html',r).read() using open() for local files and ORLs is called url-fopen and works in PHP, which is a major security hole, because it even allows one to include() code files from the web without knowing it, that kind of thing... python has two functions so you know what you're doing. If your webpage needs cookies or something, you'll need urllib2 If you wanna parse it afterwards use Htmllib or BeautifulSoup From chuck at smtl.co.uk Tue Jun 8 11:09:24 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 16:09:24 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Tue, 08 Jun 2004 15:19:01 BST." <200406081419.i58EJ1eb000033@sevenofnine.smtl.co.uk> References: <2ijmctFnvgjeU2@uni-berlin.de> <2ilkg2For39hU1@uni-berlin.de> <200406081419.i58EJ1eb000033@sevenofnine.smtl.co.uk> Message-ID: <200406081509.i58F9Oeb000330@sevenofnine.smtl.co.uk> Hi again yes the /var/spool/mail/chuck is empty as we process the mail to the user home dir using MH . Thus created a mailbox using packf with three emails for testing . Cheers for pointing this out. From deathstar at altern.org Thu Jun 17 08:18:14 2004 From: deathstar at altern.org (Deathstar) Date: 17 Jun 2004 05:18:14 -0700 Subject: Help - email library not working as expected Message-ID: Hi, I'm having some problems using the Python email library. I want to write a mail that has a body, and an attachment with it. From what I understand, the set_payload() function would be specify the body, and attach() would specify a MIME attachment Message. However this does not work. I get an error saying : 'str' object has no attribute 'append' I'm doing this with Python 2.3.2 on Windows XP SP1. What am I doing wrong here? How do u specify the body and the attachment to the mail? ======== Code Snippet Start ======== my_mail=Message() my_mail['From']=addr_frm my_mail['To']=addr_to my_mail['Subject']=sub my_mail.set_payload(bdy.read()) #Body of the mail attachment=MIMEMultipart(mimetypes.guess_type(att_name)) att=open(att_name) attachment.set_payload(att.read()) #The attachment my_mail.attach(attachment) print my_mail.as_string() ======== Code Snippet End ======== Regards, Deathstar From max at alcyone.com Tue Jun 8 05:02:24 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Jun 2004 02:02:24 -0700 Subject: how to use __str__ and __repr__? References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9hjFnvcsbU1@uni-berlin.de> <40C4FF56.F81105B@alcyone.com> <2il6llFo4tkpU1@uni-berlin.de> Message-ID: <40C580A0.A01B38A7@alcyone.com> Jim Newton wrote: > if that is the case then why does the following fail > > class another: > pass > > another.__str__() > > I would think that would return a string such as > "<__main__.another instance at 0x8132b64>" > but it does not seem to. Because __str__ is a special method which str defers to. If you want the str of anObject, call str(anObject). The object will then show you the string representation for that object. You shouldn't care whether or not it's got that behavior from defining a __str__ method, or whether it's gotten it from a parent class. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ To endure what is unendurable is true endurance. -- (a Japanese proverb) From eurleif at ecritters.biz Wed Jun 16 22:33:21 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 16 Jun 2004 22:33:21 -0400 Subject: Constructor documentation assigned to class or __init__? Message-ID: <2jce81Fv1u06U1@uni-berlin.de> Should a class's constructor be documented in the class's docstring or __init__'s docstring? For instance: class Foo(object): """This class represents mating lizards. Constructor requires one argument, the lizard this lizard is mating with.""" def __init__(self, other): pass # or class Bar(object): ""This class represents mating lizards.""" def __init__(self, other): """Initiate the object. Requires one argument, "other", which is the lizard this lizard is mating with.""" pass From grey at despair.dmiyu.org Thu Jun 3 10:45:09 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 14:45:09 GMT Subject: speed problems References: Message-ID: On 2004-06-03, ^ wrote: > Here are both scripts, could you please have a look and tell me where I > should look for optimizations? Well, I see one major difference and one place I'd do something differently. Perl: > my ($gzip) = "/usr/bin/gzip"; > my ($bzip2)= "/usr/bin/bzip2"; First off you're using exernal programs here for decompression. This is a trade off of making a system call vs internal implementation. Maybe Python's implementation is slower? I don't know, just pointing out that it is a difference. Personally when programming tools like this I try to keep everything internal because I've had endless system calls kill the run-time. However with the few files you're iterating over the cost might be the other way 'round. :) Python: > for line in lf.readlines(): > if string.count( line, "INFECTED" ): > vname = re.compile( "INFECTED \((.*)\)" ).search( line ).group(1) If I read this correctly you're compiling this regex every time you're going through the for loop. So every line the regex is compiled again. You might want to compile the regex outside the loop and only use the compiled version inside the loop. I *think* that Perl caches compiled regexs which is why they don't have two different ways of calling the regex while Python, in giving two different calls to the regex, will compile it every time if you expressedly call for a compile. Again, just a guess based on how I presume the languages work and how I'd write them differently. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From qrczak at knm.org.pl Wed Jun 16 05:09:29 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Wed, 16 Jun 2004 11:09:29 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: On Tue, 15 Jun 2004 22:01:19 -0800, Troy Melhase wrote: > Or even this: > > shared_cache = {} > > def F(a, b, cache=shared_cache): > ... This would work in the 2nd scheme. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From ptmcg at austin.rr._bogus_.com Wed Jun 9 13:36:22 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 09 Jun 2004 17:36:22 GMT Subject: parsing in python References: Message-ID: "Peter Sprenger" wrote in message news:ca6ep3$8ni$01$1 at news.t-online.com... > Hello, > > I hope somebody can help me with my problem. I am writing Zope python > scripts that will do parsing on text for dynamic webpages: I am getting > a text from an oracle database that contains different tags that have to > be converted to a HTML expression. E.g. "" ( # is an integer > number) has to be converted to where the image data > comes also from a database table. > Since strings are immutable, is there an effective way to parse such > texts in Python? In the process of finding and converting the embedded > tags I also would like to make a word wrap on the generated HTML output > to increase the readability of the generated HTML source. > Can I write an efficient parser in Python or should I extend Python with > a C routine that will do this task in O(n)? > > Regards > > Peter Sprenger Peter - Not sure how this holds up to "high-performance" requirements, but this should work as a prototype until you need something better. (Requires download of latest pyparsing 1.2beta3, at http://pyparsing.sourceforge.net .) Note that this grammar is tolerant of upper or lowercase PIC, plus inclusion of whitespace between tokens and tag attributes within the tag. BTW, I'll be the first one to admit that this is a lot wordier (and very possibly slower) than something like re.sub(). But it is *very* productive from a programming standpoint, and implicitly takes care of nuisance issues like unexpected whitespace. It is also simple from a maintenance standpoint: adding support for caseless matching on 'pic', or for additional tag attributes, was very straightforward. I'm just not that good with re's to be able to make similar changes in as short a time, or as readable a style. (While we are talking about performance, I'll also mention that transformString() does not use string concatenation to construct its output. As the input is processed, the transformed text fragments and intervening original text are accumulated into a list; at the end, the list is converted to a string using "".join(). ) -- Paul =================== from pyparsing import CharsNotIn,Word,Literal,Optional,CaselessLiteral testdata = """ < PIC 17 > < pic99 > """ # Define parse action to convert tags to tags def convertPicNumToImgSrc(src,loc,toks): imgFile = imageFiles.get( toks.picnum, "default.jpg" ) retstring = '' % (imgFile, toks.picAttribs) return retstring # Define grammar for matching text pattern - don't forget that there might be HTML tag attributes # included in the tag # Return parse results as: # picnum - the numeric part of the tag, converted to an integer # picAttribs - optional HTML attributes that might be defined in the tag # integer = Word("0123456789").setParseAction( lambda s,l,t: int(t[0]) ) picTagDefn = ( Literal("<") + CaselessLiteral("pic") + integer.setResultsName("picnum") + Optional( CharsNotIn(">") ).setResultsName("picAttribs") + ">").setParseAction( convertPicNumToImgSrc ) # Set up lookup table of pic #'s to image file names # (in reality, these would be read from database table) imageFiles = { 22 : "flower.jpg", 17 : "house.jpg", 38 : "dog.jpg", } # Run transformString print picTagDefn.transformString(testdata) =================== output: From mail at neumann-rosenheim.de Sun Jun 6 14:16:02 2004 From: mail at neumann-rosenheim.de (Christian Neumann) Date: Sun, 6 Jun 2004 20:16:02 +0200 Subject: Problem with Python xrange Message-ID: <200406061816.i56IG158011009@post.webmailer.de> Hello, i have a problem with the built-in function xrange(). Could you by any chance be able to help? I use Python 2.3.4 (final) and i think there is a bug in the built-in function xrange(). An example is: x = xrange(2, 11, 2) ## [2, 4, 6, 8, 10] I get an TypeError if i use it with SliceType: x[1:4] ## It should be return an xrange object with length 3 Here is the error message: "TypeError: sequence index must be integer". Is this really a bug? Sincerely yours, Christian Neumann -------------- next part -------------- An HTML attachment was scrubbed... URL: From rgacote at AppropriateSolutions.com Tue Jun 8 12:51:41 2004 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Tue, 8 Jun 2004 12:51:41 -0400 Subject: Fw: any simple and multiplatform database? In-Reply-To: <004a01c44d5b$f85502a0$0200a8c0@lucifer> References: <004a01c44d5b$f85502a0$0200a8c0@lucifer> Message-ID: At 3:24 PM +0200 6/8/04, Simon Roses Femerling wrote: >Hello all :) > >Is there any simple and multiplatform database for python ? > >It must be a local database (like mdb. files) I'll put in another vote for SQLite. You may want to look at Firebird as well. They have an embedded version which is available on several of the supported platforms and there's a nice Python interface. --Ray -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From birdfamily at gmail.com Wed Jun 30 10:31:45 2004 From: birdfamily at gmail.com (Richard Bird) Date: 30 Jun 2004 07:31:45 -0700 Subject: Multithreaded Telnet sessions References: <1a7605a1.0406131639.6951ca0d@posting.google.com> Message-ID: <55d6af0e.0406300631.6d10ed60@posting.google.com> Thanks so much for your helpful sample. It proved to be just the nudge I needed to get the ball rolling. I've modified the old script to support threading using your outline and have begun to implement queueing to log information. I can't get over how much faster it is to push a change to 800+ routers using 20+ threads! Anything over 20 threads seems to take processor utilization to 100%. Is there any benefit to starting additional threads once the CPU is at 100% ? Thanks, Richard From jepler at unpythonic.net Sat Jun 26 18:15:15 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 26 Jun 2004 17:15:15 -0500 Subject: Is there a more elegant way to do this? In-Reply-To: <889cbba0.0406261358.6bc18e1d@posting.google.com> References: <889cbba0.0406261358.6bc18e1d@posting.google.com> Message-ID: <20040626221514.GA6671@unpythonic.net> something like this: > def pack(self): > lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \ > 'green', 'blue', 'size', 'rotate', 'translucency'] values = [getattr(self, attr) for attr in lst] return struct.pack(' From sylphaleya at gmx.net Wed Jun 23 06:29:53 2004 From: sylphaleya at gmx.net (Manuel Huesser) Date: Wed, 23 Jun 2004 12:29:53 +0200 Subject: python terminal Message-ID: Hi Has anyone written a small aterm/eterm/xterm alike terminal emulator for X? If it isn't 100% vt102 or whatever compatible I don't care. The underlining toolkit doesn't matter. Thanks Manuel From davidf at sjsoft.com Mon Jun 28 15:28:24 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 28 Jun 2004 21:28:24 +0200 Subject: wxPython syntax In-Reply-To: References: Message-ID: OKB (not okblacke) wrote: > menus: > File(wxMenu): > name = "&File" > about(menuOption): > name = "About" > statusText = "Information about this program" > action(): > wxMessageDialog(self, "A sample editor. . .") > exit(menuOption): > name = "Exit" > etc. . . > > Now, obviously that isn't valid code, but it seems like it might be > possible to get something like by using nested classes and/or functions > (e.g., have it say "class menus:" and then "class file(wxMenu)"). So my > basic questions are: This is great - it's almost exactly like the syntax I have in mind for declaring wx GUIs. My syntax idea is more like this: wxMenu File: name = "&File" menuOption about: name = "About" statusText = "Information about this program" menuOption exit: ... Except note that I've left the code bits out. This idea follows from the following principles & ideas: - The best way to define a GUI is with declarative language - XML is great but not as nice to look at as Python-ish syntax - Hierarchical definitions are done like they are in Python I think wx would be easier to use if a syntax like the above were available which still required you to do all your programming in standard python. So for example the above section could be in a separate file or in a string within your code. The reason I avoided including code is it then means this doesn't become a mess when lots of code is added, and the parser doesn't have to understand the whole Python syntax. The question is, how to bind to the code... I would like an approach like this: MenuDeclaration = """ ... """ # put the above string in here... MenuResource = wxResourceParser.Parse(MenuDeclaration) class FileMenu(MenuResource): def OnAbout(self, event): # put the code here def OnExit(self, event): # put the code here So the actual class derives from the resource generated from parsing the declaration. Then there could be all kinds of debates as to binding names / events automatically or doing it manually. Anyway I might actually get this working ; any comments appreciated David From Mike at DeleteThis.Geary.com Sun Jun 20 04:18:01 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 20 Jun 2004 01:18:01 -0700 Subject: Compiling the Python sources with a C++ compiler (aCC) References: Message-ID: <10dai1qekcb7ce@corp.supernews.com> Paul Sheer wrote: > I have managed to build Python 2.3.3 with the aCC HP-UX C++ > compiler by making a number of one-line changes. (For reasons > beyond my control, I am forced to use this compiler and it has > no C mode at all.) Nice work! It seems like a good idea to me for Python to be compilable in either C or C++ mode (not to mention it being a necessity in your case). > struct whatzit *p; > - p = malloc (sizeof (struct whatzit)); > + p = (struct whatzit *) malloc (sizeof (struct whatzit)); If that pattern is used a lot, it would be cleaner to use a macro and avoid the duplication. Untested, but ought to work: #define malloc_struct( s ) ( (struct s*)malloc( sizeof(struct s) ) ) struct whatzit* p; p = malloc_struct( whatzit ); -Mike From max at alcyone.com Wed Jun 23 00:09:20 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Jun 2004 21:09:20 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: <40D90270.494DE318@alcyone.com> Kamilche wrote: > I've looked at a few alternatives for encryption with Python, and > didn't come up anything very speedy. > > I've written an encryption algorithm in pure Python that can process > 22 megs of data a second. I know it's not secure, but it should be > enough to ward off casual hacking. Does someone know of something > speedier? If you're only concerned with warding off casual hacking, and speed is your maximal concern, why not just XOR each byte with 0xFF or something equally brainless? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Freedom is never voluntarily given by the oppressor. -- Dr. Martin Luther King, Jr. From jepler at unpythonic.net Thu Jun 17 08:09:29 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 17 Jun 2004 07:09:29 -0500 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators In-Reply-To: <494182a9.0406160853.3c3546fe@posting.google.com> References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> <494182a9.0406141915.7061d0f6@posting.google.com> <494182a9.0406160853.3c3546fe@posting.google.com> Message-ID: <20040617120928.GA5795@unpythonic.net> In addition to Dieter Maurer's suggestion to use the AST module, you might have some success using decompyle or decompyle-like techniques. When Python compiles e1 = 100 <= x and e1 = x >= 100 it produces different bytecodes, one with COMPARE_OP <= and one with COMPARE_OP >=. It is in execution that Python determines that [in the case of the first statement] (100).__le__(x) is not implemented, and then calls x.__ge__(100) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From vinay_sajip at yahoo.co.uk Tue Jun 29 07:53:02 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 29 Jun 2004 04:53:02 -0700 Subject: Optional use of logging library module References: Message-ID: <2e37dc1.0406290353.4826f3ad@posting.google.com> > associate a logger with my class instance. But some folks _don't_ > use/like/appreciate the logging module so I'd rather not make it a > requirement for them to use logging to reuse my classes. Irmen's suggestion I'm curious to know what people don't like about the logging module. I haven't seen any posts on c.l.py complaining about it, can you point me to some discussions? Vinay Sajip From BrenBarn at aol.com Mon Jun 28 22:44:44 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 29 Jun 2004 02:44:44 GMT Subject: wxPython syntax References: Message-ID: David Fraser wrote: > MenuDeclaration = """ ... """ # put the above string in here... > MenuResource = wxResourceParser.Parse(MenuDeclaration) > > class FileMenu(MenuResource): > def OnAbout(self, event): > # put the code here > def OnExit(self, event): > # put the code here This is a cool idea. I like the looks of it. One worry I have, though, is that with the code outside the hierarchical definition there'll still be confusion about the organization. What if you have a menu bar as well as some other widgets, or submenus? Also, what about things like listboxes, where you want the list elements to be determined programmatically? Various interrelationships might exist between the GUI's appearance and its content, which could be difficult to express if the layout were being specified with some static text. I'm not sure how best to handle this, but I think it's something to think about. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From skip at pobox.com Sat Jun 5 18:55:23 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 5 Jun 2004 17:55:23 -0500 Subject: Parsing In-Reply-To: <94cc3dba.0406051438.4619ddfc@posting.google.com> References: <94cc3dba.0406051438.4619ddfc@posting.google.com> Message-ID: <16578.20315.807747.320350@montanaro.dyndns.org> Fouad> I think i could learn a lot if i could get my hands on say a Fouad> bison file for the grammar (i am crossing my fingers that the Fouad> parser is built this way, not in some genius ad hoc way). Look in the distribution in the Grammar directory and at the compile.c and ceval.c files in the Python directory. Skip From heikowu at ceosg.de Wed Jun 2 00:10:36 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Wed, 2 Jun 2004 06:10:36 +0200 Subject: extension modules in C for python, check for korrekt Object In-Reply-To: <2i4vnqFja3spU1@uni-berlin.de> References: <2i4vnqFja3spU1@uni-berlin.de> Message-ID: <200406020610.36369.heikowu@ceosg.de> Am Mittwoch, 2. Juni 2004 05:26 schrieb Greg Ewing: > Use PyObject_IsInstance(). Or PyObject_TypeCheck()... All documented in the Python C/API documentation on python.org. Heiko. From peter at semantico.com Mon Jun 14 11:30:02 2004 From: peter at semantico.com (Peter Hickman) Date: Mon, 14 Jun 2004 16:30:02 +0100 Subject: Searching for the best scripting language, In-Reply-To: References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <40cdc47a$0$20179$afc38c87@news.easynet.co.uk> Peter Hansen wrote: Please don't take that code snippet as an example of Ruby but more as evidence of a bad programmer, as you said "unreadable code can be written in any language" and Paul Ryan has just proved it. Take it this way, if someone showed you some badly written Python would that put you off Python? From theoryboy at my-deja.com Mon Jun 21 10:46:18 2004 From: theoryboy at my-deja.com (Peter Saffrey) Date: 21 Jun 2004 07:46:18 -0700 Subject: "RuntimeError: Calling Tcl from different appartment" Message-ID: I am writing a multi-threaded Tkinter application. It worked fine with Python 2.2 under Redhat 8.0, but I have recently moved across to Debian (testing/unstable) and Python 2.3. Now I get the above error message. I read on this group somewhere that this is caused by calling Tk functions from a different thread to where the interface is running. Unfortunately, I really need to do this and cannot have all my Tk calls within one thread. Is there a way around this? Why did it work in 2.2 but not 2.3? Thanks, Peter From fumanchu at amor.org Fri Jun 11 16:47:44 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 11 Jun 2004 13:47:44 -0700 Subject: Inheritence confusion (was Re: Deeply-nested class layout suggestions wanted) Message-ID: Kirk Strauser wrote: > As a final concrete example, I whipped up a few little > skeleton classes like > so: > > Generic > |-- Subclass > | |-- __init__.py > | |-- a.py > | `-- b.py > |-- __init__.py > |-- a.py > `-- b.py > > Generic/a.py > > from b import b > > class a: > def __init__(self): > test = b() > > Generic/b.py > > class b: > def __init__(self): > print 'In Generic.b' If it were my code, I'd rewrite Generic/a.py as: from Generic import b class a(object): def __init__(self): test = b.b() > I'm completely lost. What do I have to do to get the > subclasses to use modules at their own level instead of where > the defined __init__ function happens to be? Some options: 1) Override __init__ in the subclass. 2) Pass the correct module as an argument to init. 3) Perform ugly module-inspection hacks. Don't do this. It would be a *lot* clearer if your example didn't re-use names in different modules. Try some other letters once in a while. :) It'll make your design clearer. Seriously, rewrite your example without duples and I can spare more brain cells on it. Robert Brewer MIS Amor Ministries fumanchu at amor.org From __peter__ at web.de Tue Jun 8 04:07:35 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 10:07:35 +0200 Subject: Brain Dead Singleton References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> <40C1B470.1000407@jessikat.fsnet.co.uk> <40C4209A.6090403@jessikat.fsnet.co.uk> <40C4F149.7080607@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Peter Hansen wrote: [...] >> Anyway, this now leads me to wonder whether any singleton >> pattern which doesn't involve manipulating __builtin__ is >> safe from deletion of items in sys.modules... > > .... > > If you hold onto an instance then I think it's safe, I guess the problem The same is true for modules. If you keep a reference of a module and refer only to that instead of doing an import every time you need to access your singleton - well nothing will break that. However, you have now reduced the original pattern to a mere "please do not rebind that name" convention. Peter From __peter__ at web.de Tue Jun 8 05:57:06 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 11:57:06 +0200 Subject: About a plugin framework! References: Message-ID: Simon Roses Femerling wrote: > The way my app works is a python module (plugin) that contains (imbedded) > XML defining the classname and some extra information and the app will be > load the module using the classname: > > Example: > > ------ mymodule.py ---- > > __xml__ =""" > > Test > > """ The xml stuff unnecessarily complicates things. Use a list with the names of exposed classes __all__ = ["Test"] If there is only one I'd rather follow a naming convention, i. e. the class name "Test" would be mandatory. > class Test: > def Msg(self): > print "Hello" > > --------------------------------- > > --- MyApp.py ----------- > > fp = open(f) > exec(fp) in globals() > str = __xml__ > pxml = parsexml.ParseXML() > pxml.BeginParse(str) > cn = pxml.GetClassname() > mymod = cn() <-- Here is the error Which of the following would you expect to succed? >>> class Test: pass ... >>> Test() <__main__.Test instance at 0x40296acc> >>> "Test"() Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> u"Test"() Traceback (most recent call last): File "", line 1, in ? TypeError: 'unicode' object is not callable So the name is not enough - unicode or not. You have to get hold of the class object, but that is no big deal: >>> getattr(__main__, u"Test")() <__main__.Test instance at 0x40296bcc> > mymod.Msg() > > ---------------------------------- > > The error is: > > Traceback (most recent call last): > File "blackout.py", line 503, in onAttackMod > mymod = cn() > TypeError: 'unicode' object is not callable > > Any suggestions ? How can achieve this ? > Each module (plugin) can have a different class name defined in the XML > data. Why? > Besides this anyone have suggestions for a better plugin framework ? Maybe > using imp module to dynamically import modules ? If a plugin is in the python path, just do plugin = __import__(pluginName) and then retrieve the class pluginClass = getattr(plugin, plugin.__all__[0]) Depending on whether you allow multiple plugins/classes at a time and how you want to access them from your code you'd need registries (basically python dictionaries) for plugin modules and clases. Peter From tzot at sil-tec.gr Fri Jun 25 13:33:41 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 25 Jun 2004 20:33:41 +0300 Subject: Is there a Python Audio Library? References: Message-ID: On Fri, 25 Jun 2004 12:58:39 -0400, rumours say that gohaku might have written: >Hi everyone, >I would like to know if there is an audio library that will allow me to >create >and read .WAV and .MIDI files. >When reading .WAV files, I am looking for amplitude information. > >Thanks. >-gohaku > for wave files and operations on them: import wave, audioop for midi files, google is your friend (pymidi would be my first guess :) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From Scott.Daniels at Acm.Org Fri Jun 18 15:58:45 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 18 Jun 2004 12:58:45 -0700 Subject: calculate a colour gradient In-Reply-To: References: Message-ID: <40d34eb2$1@nntp0.pdx.net> Mark Light wrote: > Hi, > I have a tk.scale bar for which I want the background to change from > blue to red as I slide along it. The mechanics of this I can do, but > the colour gradient I have is very crude - basically the amount of R in > RGB just increases whilst the G and B are fixed values. Whilst this is > not really a python question does anybody have any suggestions about > calculating the RGB values for a smooth colour gradient? > > > Mark. Depending on the purpose, you could: search for "color temperature" or "black body radiation" to get a very defensible transition, or (for false-color or some such), break the range into pieces and do a linear interpolation inside each piece. Play with R-O-Y-G-B, for example. Note: even intervals is not going to look right, eyeball the boundaries. -- -Scott David Daniels Scott.Daniels at Acm.Org From indigo at bitglue.com Wed Jun 16 21:31:15 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 16 Jun 2004 21:31:15 -0400 Subject: breaking a list into smaller lists In-Reply-To: References: Message-ID: <20040617013115.GA2135@unununium.org> One could easilly break it into a list of small lists: small = [ BIG_LIST[i:i+1000] for i in xrange(0,len(BIG_LIST),1000) ] On Wed, Jun 16, 2004 at 07:04:10PM -0400, Bart Nessux wrote: > I understand how a Python list can be broken into smaller lists by using > slice like this: > > new_small_list_1 = BIG_LIST[0:1001] #0-1000 > new_small_list_2 = BIG_LIST[1001:2001] #1001-2000 > new_small_list_3 = BIG_LIST[2001:3001] #2001-3000 > ... > ... > ... > > However, I was wondering if there's an easier way to do this. For > example, say I have a list that contains the names of 100,000 files that > I wish to open and read. Because of file handle limits, I can only open > roughly 1000 files at a time while the OS is doing other things. > > Is there a way to turn this big list into 100 small lists (each > containing 1000 files) with one simple line of code? > > Thanks, > Bart From j_mckitrick at bigfoot.com Thu Jun 10 06:36:21 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 10 Jun 2004 03:36:21 -0700 Subject: Doc strings for a standalone app?? References: Message-ID: Peter Hansen wrote in message news:... > The only thing I can think of to ask about that is "Why > would you *not* want to use doc strings?". There is > no significant overhead associated with them, so you > don't really lose. They have potential advantages, given > that the docs are available at runtime, more clearly > identifiable as documentation, etc, whereas the other > form of comments have no advantages for this kind of > thing. So why not use them? Well, I can see that doc strings can be useful at the beginning of each module/class/method/function. But since comments can be spread throughout the code, explaining logic as needed, aren't they more useful to someone who needs to maintain, rather than just use, your code? It SEEMS to me that doc strings are for those who will USE your code, and comments for those who will MAINTAIN it. Does that make any sense? jonathon From cjw at sympatico.ca Sun Jun 13 10:54:56 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 13 Jun 2004 10:54:56 -0400 Subject: Good IDE for Python In-Reply-To: References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: <_UZyc.1965$7H1.72771@news20.bellglobal.com> Richard Townsend wrote: >>Any suggestions on what I should install next? > > > Have a look at SPE: http://spe.pycs.net/ SPE appears to be a good editor. PythonWin, aging a bit now, but is both a good editor and provides a debug environment. Colin W. > > This includes wxGlade (http://wxglade.sourceforge.net/) a neat GUI layout > editor for wxPython (http://wxpython.org/). > > Richard > > > > > > From lbates at swamisoft.com Fri Jun 25 10:39:30 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 25 Jun 2004 09:39:30 -0500 Subject: Odd behaviour of os module with a Win2k shared directory References: Message-ID: When you access a share on Windows 2000 machine it acts as if it is the root directory. That being said your command checked to see if dietplan6 had a file/folder inside of it named dietplan6. If you can see the share then it exists. If you want to test for the existence of the dietplan6, you would need to define your share one level up in the tree. Think of it this way, you can't test for the existence of the root directory. HTH, Larry Bates Syscon, Inc. "David Hughes" wrote in message news:memo.20040625144135.2040A at forestfield.cix.co.uk... > I shared a directory, dietplan6, which is actually several levels down in > C:\Program files\ on a Windows 2000 machine, called 'Nom'. When I tried to > check its existence from another Win2k machine, I got the following > strange results: > > Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> pth = r'\\nom\dietplan6' > >>> os.path.exists(pth) > False > >>> os.listdir(pth) > ['unins000.dat', 'program', 'database', 'resource', 'doc', 'dlm', > 'dp5conv', 'gs', 'Readme.txt', 'dietplan.lic', 'users', 'imports', > 'unins000.exe', 'locks'] > >>> os.path.exists(os.path.join(pth, 'program')) > True > >>> os.chdir(pth) > >>> os.getcwd() > '\\\\nom\\dietplan6' > >>> os.path.exists(os.getcwd()) > False > >>> > > -- > Regards, > David Hughes > From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jun 25 19:24:40 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 26 Jun 2004 01:24:40 +0200 Subject: Seems like the cgi module does not read the QUERY_STRING when METHOD is POST In-Reply-To: References: Message-ID: <40dcb439$0$6968$e4fe514c@news.xs4all.nl> Quentin Crain wrote: > I am expecting that my FieldStorage object will > contain any and all key/values from the QUERY_STRING > regardless of the request method. But it seems that > the QUERY_STRING is ignored when the method is POST. Read this thread: http://tinyurl.com/3bd9j In the end, I added some code myself that parses the query string if the method is POST... --Irmen From reinhold-birkenfeld-nospam at wolke7.net Thu Jun 24 03:46:49 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 24 Jun 2004 09:46:49 +0200 Subject: Faster 'if char in string' test In-Reply-To: <889cbba0.0406232245.53b9025e@posting.google.com> References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: <2jveu0F15mi8iU2@uni-berlin.de> Kamilche wrote: > I was looking for a way to speed up detecting invalid characters in my > TCP string, and thought of yet another use for the translate function! > If you were to 'translate out' the bad characters, and compare string > lengths afterwards, you would know whether or not the line contained > invalid characters. The new method is more than 10x faster than the > standard 'if char in string' test! So - here's the code plus sample > timings: Perhaps it would be a good idea to post the snippets at the Python cookbook. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From mcfletch at rogers.com Wed Jun 2 02:14:43 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 02 Jun 2004 02:14:43 -0400 Subject: Table of Python Packages In-Reply-To: <20040530210751.GA17302@fluid.sparcs.net> References: <20040530210751.GA17302@fluid.sparcs.net> Message-ID: <40BD7053.7000000@rogers.com> I certainly found the table of packages interesting, if for no other reason than that it let me know which of my packages are readily available to users. Your method of generating it seems rather labour intensive. I'm wondering if there could be metadata added to PyPI for e.g. RPM/DEB package names for each package. Of course, those are generally added after the first release of the package, but later releases could include the information. Have fun, Mike Seo Sanghyeon wrote: ... >What do you think about this? Is this a good idea? If it is a good idea, >how can it be made more useful? Now I am thinking about adding NetBSD >packages and PyPI references... > >This table shows which modules are not packaged for distributions. >Those modules would be good candidates for packaing. Perhaps maintainers >may learn from the each other. > >Any other thoughts? > > ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From wjdandreta at att.net Thu Jun 17 14:32:17 2004 From: wjdandreta at att.net (Bill Dandreta) Date: Thu, 17 Jun 2004 18:32:17 GMT Subject: Parsing by Line Data In-Reply-To: References: Message-ID: python1 wrote: > ...lines in a file, for example: > > 01A\n > 02B\n > 01A\n > 02B\n > 02C\n > 01A\n > 02B\n > . > . > . > > The lines beginning with '01' are the 'header' records, whereas the > lines beginning with '02' are detail. There can be several detail lines > to a header. > > I'm looking for a way to put the '01' and subsequent '02' line data into > one list, and breaking into another list when the next '01' record is > found. > > How would you do this? I'm used to using 'readlines()' to pull the file > data line by line, but in this case, determining the break-point will > need to be done by reading the '01' from the line ahead. Would you need > to read the whole file into a string and use a regex to break where a > '\n01' is found? First let me prface my remarks by saying I am not much of a programmer so this may not be the best way to solve this but I would use a dictionary someting like this (untested): myinput = open(myfile,'r') lines = myinput.readlines() myinput.close() mydict = {} index = -1 for l in lines: if l[0:2] == '01' counter = 0 index += 1 mydict[(index,counter)] = l[2:] else: mydict[(index,counter)] = l[2:] counter += 1 You can easy extract the data with a nested loop. Bill From qrczak at knm.org.pl Fri Jun 18 05:04:38 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Fri, 18 Jun 2004 11:04:38 +0200 Subject: does python have useless destructors? References: <7ifz8udxp2.fsf@enark.csis.hku.hk> Message-ID: On Fri, 18 Jun 2004 01:43:59 -0700, David Turner wrote: > The most obvious way in which RAII can be enabled is by introducing > defined reference-counting semantics for objects with __del__. I > can't think of another way of doing it off-hand, but there must be > others (if reference counting has unacceptably high overhead). The variables which hold these objects must be distinguished. Not just the objects themselves. > One possibility is to introduce scoped objects, analogous to auto or > stack-allocated objects. It would be illegal to pass a reference to > these outside of a given scope, and they would have __del__ (or > another method) called when the scope ends. What would happen when you store a reference to such object in another object? Depending on the answer, it's either severely limited (you can introduce no abstractions which deal with files somewhere inside), or as inefficient as reference counting. The only way is to somehow distinguish variables for which objects they point to should be finalized, from plain variables. Not objects but variables. try...finally and with are examples of that. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From grey at despair.dmiyu.org Fri Jun 4 19:45:49 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 23:45:49 GMT Subject: python vs awk for simple sysamin tasks References: <2ic128FllgicU1@uni-berlin.de> <2icbruFlqs1aU1@uni-berlin.de> <2ice7nFimf62U1@uni-berlin.de> Message-ID: On 2004-06-04, Steve Lamb wrote: > 4x faster measured in hours based pretty much on building up and tearing > down those pipes and executing the same program over and over is rather > impressive given how miniscule those operations are in general is impressive. Bleh, and the redundnacy in that sentence provided by the human at the keyobard losing track of where he was during his context switches. Kids, don't newsgroup post and browse at the same time. >.< -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From ville at spammers.com Tue Jun 29 16:47:29 2004 From: ville at spammers.com (Ville Vainio) Date: 29 Jun 2004 23:47:29 +0300 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: >>>>> "Phil" == Phil Frost writes: Phil> I'm forwarding this to the Unununium mailing Phil> list. I think the two projects are solving the same problem from Phil> opposite ends. Very interesting link :-). Actually, IPython is so far not actively solving the problem Ununium is solving, and I wasn't really talking on behalf of IPython the project, more like visions of what I might want it to be (and Fernando, the author, probably too, but his time resources are limited). If you Ununium guys have developer resources to throw at IPython's direction, I would bet Fernando wouldn't mind a little help at all - just join the ipython-dev mailing list, IPython is in need of refactoring :-). And if you want to check ipython out, do a cvs checkout as instructed on the webpage and start ipython by "ipython -p pysh", which starts it in shell mode. -- Ville Vainio http://tinyurl.com/2prnb From connellybarnes at yahoo.com Wed Jun 9 01:58:04 2004 From: connellybarnes at yahoo.com (C. Barnes) Date: Tue, 8 Jun 2004 22:58:04 -0700 (PDT) Subject: Code snippet: Natural string sorting Message-ID: <20040609055804.48764.qmail@web14523.mail.yahoo.com> Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts ['Team 11', 'Team 3', 'Team 1'] into the order ['Team 1', 'Team 3', 'Team 11']. Code: # --------------------------------------------------------- # natsort.py: Natural string sorting. # --------------------------------------------------------- # By Seo Sanghyeon. Some changes by Connelly Barnes. def try_int(s): "Convert to integer if possible." try: return int(s) except: return s def natsort_key(s): "Used internally to get a tuple by which s is sorted." import re return map(try_int, re.findall(r'(\d+|\D+)', s)) def natcmp(a, b): "Natural string comparison, case sensitive." return cmp(natsort_key(a), natsort_key(b)) def natcasecmp(a, b): "Natural string comparison, ignores case." return natcmp(a.lower(), b.lower()) def natsort(seq, cmp=natcmp): "In-place natural string sort." seq.sort(cmp) def natsorted(seq, cmp=natcmp): "Returns a copy of seq, sorted by natural string sort." import copy temp = copy.copy(seq) natsort(temp, cmp) return temp Examples: You can use this code to sort tarball filenames: >>> natsorted(['ver-1.3.12', 'ver-1.3.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.2.3', 'ver-1.2.1']) ['ver-1.2.1', 'ver-1.2.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.3.3', 'ver-1.3.12'] Chemical elements: >>> natsorted(['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6']) ['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6'] Teams: >>> natsorted(['Team 101', 'Team 58', 'Team 30', 'Team 1']) ['Team 1', 'Team 30', 'Team 58', 'Team 101'] Pass natcasecmp as a second argument for case-insensitive sorting: >>> natsorted(['a5', 'A7', 'a15', 'a9', 'A8'], natcasecmp) ['a5', 'A7', 'A8', 'a9', 'a15'] Enjoy! Message and source code are in the public domain. __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From esj at harvee.org Thu Jun 17 13:47:20 2004 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 17 Jun 2004 13:47:20 -0400 Subject: how to become a really good Python programmer? In-Reply-To: <0b53d0hd8kjie9ppng0j1g9uv5mnpceoc1@4ax.com> References: <0b53d0hd8kjie9ppng0j1g9uv5mnpceoc1@4ax.com> Message-ID: Richie Hindle wrote: > A concrete example of why it's hard and why it leads to better code: I have > a lightweight RPC system (as yet unpublished) that sends "safe pickles" over ... > tiny transport module to implement a socket transport for it. Done right, > the transport module would be so trivial that either it didn't need unit > tests, or the tests would be very simple. > > A question for experienced TDD-ers: is TDD really more intellectually > demanding than code-first, or am I either a) doing it wrong, or b) stupid? it sounds to me like it's a code focused variant of programming by contract. google will turn up any number of good references on the concept as well as practical implementation. TDD reminds me of a technique I used for many years called radical top-down design. This technique was developed in the 1970s but probably became not PC because you could not predict (even grossly) how long you would take and the team requirements. The reason it was successful is because you never wrote more than a few lines of code before writing a test case to exercise those lines of code. You are always thinking one level ahead (at least) in terms of what services you wanted available. Granted, it was pre-object-oriented but it's still works well today in small teams that communicate well. you'll need to go to physical paper in order to find references. I don't believe anybody has put this information on the Web. At least not in a place that can be found by google. ---eric From skip at pobox.com Mon Jun 7 15:04:56 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 7 Jun 2004 14:04:56 -0500 Subject: Decoding 'funky' e-mail subjects In-Reply-To: References: Message-ID: <16580.48216.907133.504590@montanaro.dyndns.org> >> Have you tried decode_header from email.Header in the python >> email-package? Jonas> Thanks, that works. The problem is that I need to make it Jonas> compatible with Python 1.5.2. Why not just include email.Header.decode_header() in your app? Something like: try: from email.Header import decode_header except ImportError: # Python 1.5.2 compatibility... def decode_header(...): ... If that proves to be intractible, define yours when an ImportError is raised. In either case, you get the best solution when you can and only fall back to something possibly suboptimal when necessary. Skip From dkturner at telkomsa.net Fri Jun 11 16:44:38 2004 From: dkturner at telkomsa.net (David Turner) Date: 11 Jun 2004 13:44:38 -0700 Subject: does python have useless destructors? References: Message-ID: tfb+google at tfeb.org (Tim Bradshaw) wrote in message news:... > dkturner at telkomsa.net (David Turner) wrote in message news:... > > > > This makes me sad. But there is some hope in the following pattern, > > although it can be quite awkward: > > > > def with_file(fname, mode, oper): > > f = open(fname, mode); > > try: > > oper() > > finally: > > f.close() > > > > Of course, this can very quickly turn your code into so much > > functional goo. That's not necessarily a bad thing, as Lisp > > programmers can attest... But it's still not quite as powerful as > > RAII. > > No Lisp programmer worth their salt would tolerate such a horror. In > the specific case above there's already an idiom for doing this in > Common Lisp: Actually I was thinking more of the open() function than with the with_file() function when I said "functional goo" :-). It's really quite funny that Lisp doesn't suffer much from this sort of problem. You'd think we'd learn... Regards David Turner From jepler at unpythonic.net Thu Jun 17 15:00:36 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 17 Jun 2004 14:00:36 -0500 Subject: align on char In-Reply-To: References: Message-ID: <20040617190036.GB6013@unpythonic.net> >>> def align(seq, sep=":"): ... seq = [i.split(sep, 1) for i in seq] ... width = max([len(i[0]) for i in seq]) ... return ["%s:%s" % (a.ljust(width), b) for a, b in seq] ... >>> lines = ( ... 'user1 : John Hunter', ... 'another user : Bill Bragg', ... 'yet on more : Hi There', ... ) >>> for l in align(lines): print l; ... user1 : John Hunter another user : Bill Bragg yet on more : Hi There Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From apardon at forel.vub.ac.be Tue Jun 1 06:58:49 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Jun 2004 10:58:49 GMT Subject: how to bail if stdin is empty References: <2621b014.0405310535.38e176df@posting.google.com> Message-ID: Op 2004-05-31, Jon Schull schreef : > I want to write a filter that will take input from files on the > command line and/or from stdin. > > But if nothing has been piped to stdin, I don't want my program to > hang--I want it to do something else. > > This is standard behavior for pipeable-programs I believe, No it is not. Standard behaviour for filters (on unix that is) is to use standard input if no file arguments are given. If you start such a program without arguments and not connected to another programs with a pipe, such a program will hang and wait for user input from the keyboard. -- Antoon Pardon From martin at v.loewis.de Wed Jun 2 14:25:30 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jun 2004 20:25:30 +0200 Subject: distutils sdist and MANIFEST files In-Reply-To: References: Message-ID: <40be1b9a$0$12508$9b622d9e@news.freenet.de> David Fraser wrote: > Does anyone else find it annoying that the sdist command for distutils > relies on MANIFEST.in and MANIFEST files? > I would really like to be able to do everything in the setup script ; if > I don't, the MANIFEST files get created automatically (with warnings) > and any new scripts added are forgotten. > > Any alternative approaches to this? You can derive from the sdist command and override the read_template function. Regards, Martin From tkpmep at hotmail.com Tue Jun 8 09:26:01 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 8 Jun 2004 06:26:01 -0700 Subject: Passing parameters using **kargs References: Message-ID: I don't as yet have an application in mind. I'm teaching myself Python from Lutz and Ascher's "Learning Python", and when I come across a new concept, I a)Try and explore the different ways in which it might be used, and b)Try to understand the conditions under which it does not work, and why. I start with the book, then go through the help, and if I still can't solve some of the questions I create for myself, I post a question on this newsgroup. In this case, I'm being driven by intellectual curiosity - though I do think the ability to create a string representation of a variable name could be useful when printing, and the ability to create a variable whose name is specified in a string could be useful when creating on-the-fly code. Thomas Philips From srumbalski at copper.net Wed Jun 9 12:51:38 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Wed, 09 Jun 2004 12:51:38 -0400 Subject: division bug? References: <964246.0406090655.7e190def@posting.google.com> Message-ID: <40c74017_1@newsfeed.slurp.net> Milan wrote: > a program: > > a=10 > b=5 > print a/b > > and its result: 0. If you run the program, you see always a sero (0), > but 10/5 is 2. Who can help me? You probably have reversed a & b in your program somewhere. Zero is the correct result with the numbers reversed. >>> a = 10 >>> b = 5 >>> print "a/b = %s\nb/a = %s" % (a/b, b/a) a/b = 2 b/a = 0 If you import division from __future__ my guess is that you will see the result of 0.5. If this is the case you have mixed a & b up somewhere. >>> from __future__ import division >>> print "a/b = %s\nb/a = %s" % (a/b, b/a) a/b = 2.0 b/a = 0.5 -- Steven Rumbalski news|at|rumbalski|dot|com From tjreedy at udel.edu Wed Jun 2 19:04:41 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 Jun 2004 19:04:41 -0400 Subject: Why did no one invent Python before? References: Message-ID: "j_mckitrick" wrote in message news:ec6dce8b.0406021449.6341a3fa at posting.google.com... > Seriously, why is a language like this only NOW appearing? Actually, it was released over a decade ago, which is hardly 'now' by CS standards. Perhaps you should ask why you didn't hear about it and download it sooner? In any case, welcome to the community of Python enthusiasts. Terry J. Reedy From __peter__ at web.de Tue Jun 29 11:52:47 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jun 2004 17:52:47 +0200 Subject: Listing functions in a file IN ORDER References: Message-ID: Ian Sparks wrote: > I have a python file with a number of functions named with the form doX so > : > > doTask1 > doThing > doOther > > The order these are executed in is important and I want them to be > executed top-down. They all have the same parameter signature so I'd like > to do : > > for name, func in vars(mymodule).items(): > if not name.startswith("do") and callable(func): > apply(func,my_params) > > but the problem is that the return from vars is not ordered the same as in > the file. i.e. it could be > > doOther > doTask1 > doThing > > The low tech solution is to use dir() and re-name the functions to sort > alphabetically but perhaps there is a more elegant solution? The following minimal code will break with methods and nested functions. def z(): print "ZZZ" def y(): print "YYY" def x(): print "XXX" import compiler class Visitor: def __init__(self, module, *args): self.module = module self.args = args def visitFunction(self, node): getattr(self.module, node.name)(*self.args) def callInOrder(module, *args): ast = compiler.parseFile(module.__file__) compiler.walk(ast, Visitor(module, *args)) if __name__ == "__main__": import xyz callInOrder(xyz) Not particularly elegant, but crazy enough to be worth posting... Peter From dmq at gain.com Fri Jun 18 12:06:19 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 18 Jun 2004 09:06:19 -0700 Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> Message-ID: <75v5d0pa40i1qmcobno53ua8l54tflmjoi@4ax.com> On Fri, 18 Jun 2004 10:18:06 GMT, Michael Hudson wrote: >David MacQuigg writes: > >> On Thu, 17 Jun 2004 11:05:58 GMT, Michael Hudson >> wrote: >> >> >michele.simionato at poste.it (Michele Simionato) writes: >> > >> >> David MacQuigg wrote in message news:... >> >> > I have what looks like a bug trying to generate new style classes with >> >> > a factory function. >> >> > >> >> > class Animal(object): pass >> >> > class Mammal(Animal): pass >> >> > >> >> > def newAnimal(bases=(Animal,), dict={}): >> >> > class C(object): pass >> >> > C.__bases__ = bases >> >> > dict['_count'] = 0 >> >> > C.__dict__ = dict >> >> > return C >> >> > >> >> > Canine = newAnimal((Mammal,)) >> >> > TypeError: __bases__ assignment: 'Mammal' deallocator differs from >> >> > 'object' >> >> > >> >> > If I remove the 'object' from the class C(object) statement, then I >> >> > get a different, equally puzzling error message: >> >> > >> >> > TypeError: __bases__ items must be classes >> >> > >> >> > The function works only if I remove 'object' from all base classes. >> >> > >> >> > -- Dave >> >> >> >> This is not a bug. The developers removed the possibility to change >> >> the bases of a new-style class. >> > >> >Bad news for you: I put it back in for 2.3. >> > >> >If you read the error message, you'll notice that it's phrased to >> >suggest that assignment to __bases__ is *sometimes* possible :-) >> > >> >David's assignment probably should work -- there's a bug on sf about >> >this -- but there are definitely situations where assignment to bases >> >*shouldn't* be allowed -- e.g. when the so-called 'solid base' changes >> >-- but noone's put in the thinking time to make this precise in code. >> >Being over-restrictive seems the better course. >> >> This may be just a documentation problem then. The error message is >> definitely misleading. > >Well, possibly. It's generally assumed that you know what you're >doing if you want to muck with things on this level. I have no desire to muck with things. The main challenge I face in teaching Python to non-CIS engineering students, is separating the useful, simple stuff from the unecessary complexities. Originally, I had just a simple hierarchy of Animal classes, with each __init__ calling its parent, and a variable _count in each class to keep track of the total number of instances. This was criticised on another thread for being not "robust" and a terrible example to show students. The alternatives offered included factory functions, metaclasses, weak references, and other complexities, all of which I felt would distract from the basic presentation, but did have some value in solving particular problems. So I included them in the Advanced Topics section. The example above is attempt to generate a class that automatically includes some attributes like _count, and thus make the creation of new animal classes more "robust". The "mucking" is a result of trying to solve a simple problem using what we already know (__bases__, __dict__, etc.), and avoiding the introduction of metaclasses. The resulting error messages are confusing, and in many cases incorrect. >>> class Animal(object): pass >>> class C: pass >>> C.__bases__ = (Animal,) TypeError: __bases__ items must be classes >>> class C(object): pass >>> C.__bases__ = (Animal,) TypeError: __bases__ assignment: 'Animal' deallocator differs from 'object' >>> class ClassicAnimal: pass >>> C.__bases__ = (ClassicAnimal,) TypeError: a new-style class can't have only classic bases >>> C.__bases__ (,) >>> C.__bases__ = (object, Animal) TypeError: Cannot create a consistent method resolution order (MRO) for bases object, Animal >>> C.__bases__ = (Animal,object) TypeError: __bases__ assignment: 'Animal' deallocator differs from 'object' >>> C.__bases__ = Animal TypeError: can only assign tuple to C.__bases__, not type >Clarifying patches welcome :-) I can't even begin to figure out the complexities of what leads to these strange messagea, but I can provide some test cases like the above. My general recommedation would be, if you are unsure that the error message will be understood, provide a more general message and a unique error number. Something like: TypeError: Illegal __bases__ assignment: Err#32175 Then the user can either try something different, or search the docs and comp.lang.python for something very specific. He won't waste time when the message says "items must be classes" and they already are classes. >> >However, newAnimal could be written like this: >> > >> >def newAnimal(bases=(Animal,), ns=None): >> > if ns is None: >> > ns = {} >> > ns['_count'] = 0 >> > return type('C', bases, ns) >> > >> >which >> > >> >a) doesn't use the name of a builtin as a variable >> >b) doesn't suffer the 'mutable default arguments' problem >> >c) is rather less insane >> >d) actually works :-) (probably, haven't tested it) >> >> It works great. The only thing I would change is the return line, >> making that >> >> globals()[name] = type(name, bases, nsdict) > >Ugh! Is there a better way to avoid spelling out the classname twice. I worry about subtle errors that could result from simple typos like BoaConstrictor = newAnimal('BoaConstritcor', bases, nsdict) >> so we don't have to type the name twice when creating a new class. >> I've also added an __init__ function. Using the factory is now very >> easy: >> >> >>> newAnimal('Dog',(Mammal,)) >> >>> dog1 = Dog() >> Hello from __init__ in Dog >> >>> Dog._count >> 1 >> >> The main limitation I see in using a factory function like this, >> instead of a metaclass, > ^^^^^^^^^^^^^^^^^^^^^^ >What a what? I _really_ don't think you mean metaclass here. Yes, I do mean metaclasses, and this is one of the few applications I have found that make sense for non-experts. I've been back-and-forth a couple of times on the question whether to include metaclasses in my OOP chapter. Most experts say no. Alex Martelli seems to think this is an over-reaction. His example in Nutshell is the best I've seen, however, I just modified it to move his metaclass methods, __init__ and __repr__ to the parent class, MetaBunch, and it runs just fine using normal inheritance rather than metaclassing. It also seems to be more efficient in memory usage, although I can't verify that. I'm just assuming that you get one copy of a method when you use inheritance, and multiple copies when you put the method in a metaclass. >> is that I can't customize the new animal as easily, because I don't >> have an indented block like in a class definition. I've got to call >> the newAnimal function, then add a bunch of attributes one at a >> time, with fully-qualified names. >> >> Dog.temperature = 102 >> Dog.pulse = 82 >> Dog.respiration = 36 > >Well, there are ways around that, too, eg: > >def newAnimal(bases=(Animal,), **kw): > kw['_count'] = 0 > return type('C', bases, kw) > >Dog = newAnimal('Dog', (Mammal,), temperature=102, respiration=36) > >> If I'm adding methods, it gets even messier, because I've got to >> define functions at the module level, then assign them to attributes >> of Dog, then maybe delete all the excess names from the module >> namespace. > >Well, not necessarily. Use the third parameter to the call to type(). I don't see how this avoids the need to define a temporary function at the module level: def bmr(t,p,r): ... some complex function of temperature, pulse, and respiration BoaConstrictor = newAnimal('BoaConstrictor',(Reptile,),temperature=102, pulse=82, repsiration=36, bmr=bmr) del bmr Compare this mess to: class BoaConstrictor(Reptile): temperature = 102 pulse = 82 respiration = 36 def bmr(t,p,r): ... Reptile inherits from Animal, which has a metaclass providing all the common class variables, like _count. All the data and methods unique to BoaConstrictor are in a normal class definition, not cluttering the module namespace. >> I have one last question. In reviewing all the ways to solve the >> problem of creating specialized classes, I see there is a function >> new.classobj(name, bases, dict) which appears to do the same thing as >> type(name, bases, dict). > >new.classobj() is a holdover from the days of old-style classes, >though I see it creates new-style classes if passed new-style bases... > >> What is the purpose of classobj()? The name is a little more >> self-explanatory than 'type', but using it requires a module import. > >Historical cruft, more-or-less. Then we need a note saying this in section 3.27 of the Library Reference. Otherwise new code will continue to use these functions instead of type(). -- Dave From miki.tebeka at zoran.com Thu Jun 10 03:20:13 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 10 Jun 2004 09:20:13 +0200 Subject: importing embedded dynamic lib In-Reply-To: References: Message-ID: <20040610072012.GF1876@zoran.com> Hello Vio, > I have a basic dynamic lib "noddy.so" which I want to > 1- embed inside my executable Why? What is the reason you can have multiple files? > 2- import by embedded python interpreter using an API call. > > 1- what would be the recommended technique to embed a binary file inside > an executable? Have a look at what Python Installer does (or NSIS installer). IMO the OS will need a "real" file so what you'll have to do is extract it at runtime and then load it. > 2- Let's imagine that I managed to load "noddy.so" into my source code > somehow, and now have a pointer to it. Again. I'd extract it to a temporary file and load it. This way you can use the regular `import'. HTH. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From squirrel at wpi.edu Wed Jun 23 13:46:16 2004 From: squirrel at wpi.edu (Chris King) Date: 23 Jun 2004 10:46:16 -0700 Subject: How to do special encode in string ? References: Message-ID: <994b391.0406230946.46fa3909@posting.google.com> > Encode("az llam n vagyok") -> "az \xe1llam \xe9n vagyok" > > Decode("az \xe1llam \xe9n vagyok") -> "az llam n vagyok" The functions you want are str.encode and str.decode: "az llam n vagyok".encode("string_escape") -> "az \xe1llam \xe9n vagyok" "az \xe1llam \xe9n vagyok".decode("string_escape") -> "az llam n vagyok" If you choose to use Unicode strings instead, use the "unicode_escape" codec instead of the "string_escape" codec. A list of the standard encodings is available at http://docs.python.org/lib/node127.html if you need with some other format (rot13 is my personal favourite :P). From tzot at sil-tec.gr Tue Jun 8 05:19:15 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 08 Jun 2004 12:19:15 +0300 Subject: Destructors and exceptions References: Message-ID: <3v0bc0hnvl9iogkp2rjkc3gd4aflk5roj7@4ax.com> On 7 Jun 2004 07:51:23 -0700, rumours say that dkturner at telkomsa.net (David Turner) might have written: >Hi all > >I noticed something interesting while testing some RAII concepts >ported from C++ in Python. I haven't managed to find any information >about it on the web, hence this post. > >The problem is that when an exception is raised, the destruction of >locals appears to be deferred to program exit. Am I missing >something? Is this behaviour by design? If so, is there any reason >for it? The only rationale I can think of is to speed up exception >handling; but as this approach breaks many safe programming idioms, I >see it as a poor trade. [snip code] ISTR that when an exception is raised, there is a reference to the code frame (and therefore to its locals) kept somewhere; you can access this info through the sys.exc_info call. Have you tried running sys.exc_clear after the exception was raised? Apart from that, advice from others not to rely on finalisation of objects to clean up still applies. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From a at a.invalid Fri Jun 4 13:47:51 2004 From: a at a.invalid (Timo Virkkala) Date: Fri, 04 Jun 2004 17:47:51 GMT Subject: Python reference In-Reply-To: References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: flupke wrote: > There's no excuse for not having a decent search function. period. http://starship.python.net/crew/theller/pyhelp.cgi -- WT From dalcolmo at vh-s.de Mon Jun 28 06:48:16 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Mon, 28 Jun 2004 12:48:16 +0200 Subject: serial, parallel and USB port References: <3f284386$0$1922$626a54ce@news.free.fr> Message-ID: <20040628124816.000078fd@titan> on Sat, 19 Jun 2004 20:19:36 -0700 "Roger Binns" wrote: > And if you want USB access, I have done a Python wrapper around libusb > that works on Windows, Linux and Mac: > > http://cvs.sourceforge.net/viewcvs.py/bitpim/bitpim/native/usb/ Interesting. From a first glance at it I think one has to compile the extension oneself. Now, I for example do not have MS-C installed - Cygwin is still a World apart and MinGW doesn't compile Python out of the box either. So the original posting may also read as: why aren't these interface in the standard distribution? The answer is probably, "because nobody volunteered to stuff them in there" - but I admit I wish too, these I/O routines were in the standard distribution, especially for the USB stuff, since USB interfaces are ubiquitous nowadays. From della at toglimi.linux.it Wed Jun 9 13:27:34 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 09 Jun 2004 17:27:34 GMT Subject: Code snippet: Natural string sorting In-Reply-To: References: Message-ID: C. Barnes wrote: > Summary: > > Sorts strings in a way that seems natural to humans. > If the > strings contain integers, then the integers are > ordered > numerically. For example, sorts ['Team 11', 'Team 3', > 'Team 1'] > into the order ['Team 1', 'Team 3', 'Team 11']. [snip] Nice. Can be written (and, hopefully, made a bit more efficient) using the Decorate-Sort-Undecorate pattern too: import re _expr = re.compile(r'(\d+|\D+)') def try_int(s): if s.isdigit(): return int(s) else: return s def nat_key(s): return [try_int(e) for e in _expr.findall(s)] def nat_nocase_key(s): return nat_key(s.lower()) def decsorted(seq, key): decorated = [(key(item), item) for item in seq] decorated.sort() return [item for k, item in decorated] Then you could use decsorted(seq, nat_key) or decsorted(seq, nat_nocase_key). If someone is found of one-liners, he can just write nat_key as def nat_key(s): return map(lambda s: s.isdigit() and int(s) or s, _expr.findall(s)) Note that 2.4's sorted() and list.sort() will have built-in support for decorate-sort-undecorate, so you'll just have to throw nat_key or nat_nocase_key to them, with no need for decsorted. -- Ciao, Matteo From reinhold-birkenfeld-nospam at wolke7.net Fri Jun 18 17:30:22 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 18 Jun 2004 23:30:22 +0200 Subject: can i define a new method at runtime? In-Reply-To: <7b22ae5b.0406181049.479d1a61@posting.google.com> References: <7b22ae5b.0406181049.479d1a61@posting.google.com> Message-ID: <2jh50vF11q5rpU1@uni-berlin.de> Raoul wrote: > If my control myTextBox has a change() event for on change and I want > to make it verify the input is an integer I could do... > > def myTextBox.change(): > verifyInteger(myTextBox.Value) > > def verifyInteger(x): > try: > string.atoi(x.value) > except ValueError : > message(x," needs to be an integer") > x.setFocus() > > but i have literally hundreds of these things to do.... > > I'd like to be able to say somethign like > > myTextBox.change = lambda x : verifyInteger(x) > > so when i initialize my form i'd like to run through a list that looks > like > > [["controlName1","verifyInteger"],["controlName2,"verifyFloat"],["controlName3 > "verifyInteger"] I'm not a guru, so expect this solution to be bloated ;) For example, (ab)use a class to build a unit with all the verify-functions: class Verify(object): def verify_integer(x): [...] def verify_float(x): [...] # Then, iterate over the list: for pair in list: # list being your example above control = getattr(__main__, pair[0]) control.changed = eval("lambda self: Verify." + pair[1] + "(self.Value)") # for this line there MUST be a solution without eval but I don't see it at the moment BTW, you should use tuples if the information about the handling functions is static. regards, Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From axel at axel.truedestiny.net Thu Jun 3 11:04:19 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Thu, 03 Jun 2004 15:04:19 GMT Subject: speed problems References: Message-ID: > First off you're using exernal programs here for decompression. This is a > trade off of making a system call vs internal implementation. Maybe Python's > implementation is slower? I don't know, just pointing out that it is a > difference. Personally when programming tools like this I try to keep > everything internal because I've had endless system calls kill the run-time. > However with the few files you're iterating over the cost might be the other > way 'round. :) > I'll be looping over these files only, but I thought using python's gzip module would be faster then spawning gzip itself the way I did in the perl script. > Python: > > for line in lf.readlines(): > > if string.count( line, "INFECTED" ): > > vname = re.compile( "INFECTED \((.*)\)" ).search( line ).group(1) > > If I read this correctly you're compiling this regex every time you're > going through the for loop. So every line the regex is compiled again. You > might want to compile the regex outside the loop and only use the compiled > version inside the loop. > Well, only for lines containing 'INFECTED' then. Good point. (I suddenly remember some c stuff in which it made a huge difference) I've placed it outside the loop now, but the times are still the same. Another difference might be while( ) and line in lf.readlines(). The latter reads the whole file to memory if I'm not mistaken as the former will read the file line by line. Why that could make such a difference I don't know. Thanks for your quick reply, Kind regards, Axel From grante at visi.com Wed Jun 9 11:04:31 2004 From: grante at visi.com (Grant Edwards) Date: 09 Jun 2004 15:04:31 GMT Subject: division bug? References: <964246.0406090655.7e190def@posting.google.com> Message-ID: On 2004-06-09, Milan wrote: > a program: > > a=10 > b=5 > print a/b > > and its result: 0. If you run the program, you see always a zero (0), What answer do you want? > but 10/5 is 2. Who can help me? Perhaps you can. :) >>> 5/10 0 >>> 5.0/10.0 0.5 >>> 5//10 0 >>> 5.0//10.0 0.0 -- Grant Edwards grante Yow! Hold the MAYO & pass at the COSMIC AWARENESS... visi.com From dfh at forestfield.co.uk Fri Jun 25 09:41:00 2004 From: dfh at forestfield.co.uk (David Hughes) Date: Fri, 25 Jun 2004 14:41 +0100 (BST) Subject: Odd behaviour of os module with a Win2k shared directory Message-ID: I shared a directory, dietplan6, which is actually several levels down in C:\Program files\ on a Windows 2000 machine, called 'Nom'. When I tried to check its existence from another Win2k machine, I got the following strange results: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> pth = r'\\nom\dietplan6' >>> os.path.exists(pth) False >>> os.listdir(pth) ['unins000.dat', 'program', 'database', 'resource', 'doc', 'dlm', 'dp5conv', 'gs', 'Readme.txt', 'dietplan.lic', 'users', 'imports', 'unins000.exe', 'locks'] >>> os.path.exists(os.path.join(pth, 'program')) True >>> os.chdir(pth) >>> os.getcwd() '\\\\nom\\dietplan6' >>> os.path.exists(os.getcwd()) False >>> -- Regards, David Hughes From http Sun Jun 20 13:51:28 2004 From: http (Paul Rubin) Date: 20 Jun 2004 10:51:28 -0700 Subject: OT: Chat server References: <8ef9bea6.0406170749.399c4956@posting.google.com> Message-ID: <7xbrjef78f.fsf@ruckus.brouhaha.com> hungjunglu at yahoo.com (Hung Jung Lu) writes: > > I'm looking for a chat (IRC) server. > > Nothing fancy. It has to be free, standalone and with logging. > > Python based will be ideal. > > If you are serious about long term, you should probably use Jabber > instead. > > http://www.jabber.org/ Why? IRC seems a lot better for chatting. From jepler at unpythonic.net Thu Jun 3 07:54:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 3 Jun 2004 06:54:49 -0500 Subject: instantiation inside __init__ In-Reply-To: References: Message-ID: <20040603115447.GA7793@unpythonic.net> The reason is nearly the same that def f(): return f() is an endless loop (endless recursion, really) To construct a C, C.__init__ is called. But C.__init__ always constructs an additional C, calling C.__init__, and so on. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kkto at csis.hku.hk Mon Jun 14 09:33:15 2004 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 14 Jun 2004 21:33:15 +0800 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: <7iekoiclic.fsf@enark.csis.hku.hk> >>>>> "Marcin" == Marcin 'Qrczak' Kowalczyk writes: Marcin> On Mon, 14 Jun 2004 00:00:39 -0700, David Turner wrote: >> The D programming language somehow contrives to have both garbage >> collection and working destructors. So why can't Python? Marcin> What happens in D when you make a pointer to a local variable, Marcin> the variable goes out of scope, and you use the pointer? Marcin> Undefined behavior? If so, it's unacceptable for Python. After reading some docs of D, I find no reference to the behaviour that Turner talked about. There is a way in which one can make sure memory is deallocated when a function exits, which uses the alloca C function. Such objects *must* not have destructor. It is rather obvious what the run-time would do: simply allocate them on stack using the GNU C alloca function, and forget them completely. When the function returns, the stack pointer manipulation will get rid of the object. It is easy for these objects to work with the implemented copy collector of D: just scan the stack as well when doing copy-collect. Since they have no destructor, there is no consequence of destruction of such objects at all during such stack wind-up, other than freeing up some memory which can happen during the next GC run. There is some mentions about reference counting. But those must be implemented by the programmer himself. I.e., the programmer must allocate fields himself to do reference counting, and do the increment and decrement himself. The D runtime does no reference counting. And the program would be buggy (e.g., call destructor too early even when a reference to it is still there) if the programmer miss an AddRef or Release somewhere. Indeed, from the docs of D about the "benefit of GC", it is quite obvious that D would do anything to avoid having to do reference counting in the runtime. I'm wondering whether Turner makes the behaviour all up. Regards, Isaac. From http Wed Jun 23 01:48:46 2004 From: http (Paul Rubin) Date: 22 Jun 2004 22:48:46 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: <7x7jty7rk1.fsf@ruckus.brouhaha.com> Peter Hansen writes: > Besides, what you say is not possible. On my machine, > which is about a P4 2500MHz, scanning an array.array('c') with > 22MB of data in it, doing nothing but reading each byte and > ignoring it, takes about 8 seconds. So does converting the > array to a list, which is pretty much all C code. Strings > are immutable, so you can't be working with one of them... Well, you could do 32-bit operations which are maybe 4x faster. You could maybe get even more speedup using built-in C functions. For example, you could do rot13 encryption with the string.translate method which should be quite fast. FWIW, http://www.nightsong.com/phr/crypto/p3.py should be quite secure, and should run at least 1 mbyte/sec on your p4/2500, maybe quite a bit more. From llothar at web.de Thu Jun 3 16:26:10 2004 From: llothar at web.de (Lothar Scholz) Date: 3 Jun 2004 13:26:10 -0700 Subject: Why did no one invent Python before? References: Message-ID: <6ee58e07.0406031226.6a57773f@posting.google.com> j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > > - much better development environment; you really don't know what you're > > missing until you've used smalltalk's browsers, inspectors and > > debuggers. It's the main thing I really, really miss in python. > > I keep hearing about this Smalltalk IDE. What is really the big deal, > and why hasn't MS ripped it off? I tried to find screenshots but > couldn't. I also applied for a demo download, but never heard back > from the company. > MS can't ripp it off. It is a "macro" less OO image based language. The "image based" is the technical difference and the reason why there is nothing and can never be something like Smalltalk for python (and python like languages). The Perl/Ruby/Python/PHP world have the problem that the languages are written for intelligent programmer not for intelligent tools (like refactoring etc). From roy at panix.com Mon Jun 14 15:20:43 2004 From: roy at panix.com (Roy Smith) Date: Mon, 14 Jun 2004 15:20:43 -0400 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <2c60f0e0.0406141101.13df93ac@posting.google.com> <9uGdnW9CBYaOalDdRVn-vA@powergate.ca> Message-ID: In article <9uGdnW9CBYaOalDdRVn-vA at powergate.ca>, Peter Hansen wrote: > Richard James wrote: > > > Well back in my day, in '75, "Real men" programmed in Intel binary > > machine codes without using those "sissy" Assembly language > > mnemonics... > > You used *binary*?! Ah, luxury.... Yeah, right. When I started out, they only let us use zeros. You had to pay your dues for a few years before they started letting you use any ones. From grante at visi.com Wed Jun 23 23:51:39 2004 From: grante at visi.com (Grant Edwards) Date: 24 Jun 2004 03:51:39 GMT Subject: Getting the source of a remote webpage References: <6962d028.0406231847.48b00a0b@posting.google.com> Message-ID: <40da4fca$0$78554$a1866201@newsreader.visi.com> In article , Nugget wrote: >> Is it possible to get the source of a remote webpage (just the >> straight HTML) without anything too complicated (like COM, I >> just want to write a simple script if possible) and write it >> to a file? For example, is it possible to do something like >> os.system(....run iexplorer.exe command....) with another >> command that automatically opens the page? Thanks. > > import urllib > > f = urllib.urlopen(url) > s = site.read() least we lead the gentle reader astray... >>> import urllib >>> f = urllib.urlopen('http://www.visi.com') >>> s = site.read() Traceback (most recent call last): File "", line 1, in ? NameError: name 'site' is not defined What you meant was: >>> s = f.read() >>> print s [...] -- Grant Edwards grante Yow! ... A housewife at is wearing a polypyrene visi.com jumpsuit!! From altis at semi-retired.com Wed Jun 16 02:13:31 2004 From: altis at semi-retired.com (Kevin Altis) Date: Tue, 15 Jun 2004 23:13:31 -0700 Subject: OSCON 2004 - Python 12 early-bird registration discount ends June 18th! Message-ID: http://conferences.oreillynet.com/pub/w/29/register.html Just a brief reminder that the 20% early-bird registration discount for OSCON 2004 - Python 12 conference ends Friday, June 18th. http://conferences.oreillynet.com/os2004/ http://conferences.oreillynet.com/pub/w/29/track_python.html http://conferences.oreillynet.com/pub/w/29/tutorial_python.html ka From connellybarnes at yahoo.com Fri Jun 18 04:07:40 2004 From: connellybarnes at yahoo.com (Connelly Barnes) Date: 18 Jun 2004 01:07:40 -0700 Subject: Automatic thread safety for classes (fixed bug w/ exceptions) References: Message-ID: <32e4319c.0406180007.533139e4@posting.google.com> To properly handle exceptions, the code in the previous posting should be modified to include a try...finally block: def ubthreadfunction(f): def g(self, *args, **kwargs): try: self.lock.acquire() ans = f(self, *args, **kwargs) finally: self.lock.release() return ans return g - Connelly From me at privacy.net Mon Jun 21 04:05:49 2004 From: me at privacy.net (Duncan Booth) Date: 21 Jun 2004 08:05:49 GMT Subject: String concatenation References: Message-ID: Peter Hansen wrote in news:xvydnWNN7t2X50vdRVn- gw at powergate.ca: > Jonas Galvez wrote: > >> Is it true that joining the string elements of a list is faster than >> concatenating them via the '+' operator? >> > Note that there's also '%s%s%s' % ('a', 'b', 'c'), which is > probably on par with the join technique for both performance > and lack of readability. A few more points. Yes, the format string in this example isn't the clearest, but if you have a case where some of the strings are fixed and others vary, then the format string can be the clearest. e.g. '%s' % (uri, alt, text) rather than: ''+text+'' In many situations I find I use a combination of all three techniques. Build a list of strings to be concatenated to produce the final output, but each of these strings might be built from a format string or simple addition as above. On the readability of ''.join(), I would suggest never writing it more than once. That means I tend to do something like: concatenate = ''.join ... concatenate(myList) Or def concatenate(*args): return ''.join(args) ... concatenate('a', 'b', 'c') depending on how it is to be used. It's also worth saying that a lot of the time you find you don't want the empty separator at all, (e.g. maybe newline is more appropriate), and in this case the join really does become easier than simple addition, but again it is worth wrapping it so that your intention at the point of call is clear. Finally, a method call on a bare string (''.join, or '\n'.join) looks sufficiently bad that if, for some reason, you don't want to give it a name as above, I would suggest using the alternative form for calling it: str.join('\n', aList) rather than: '\n'.join(aList) From mrmakent at cox.net Fri Jun 11 13:34:14 2004 From: mrmakent at cox.net (Michael Kent) Date: 11 Jun 2004 10:34:14 -0700 Subject: Can someone explain this weakref behavior? Message-ID: The Python 2.3.4 docs about weakref say: Not all objects can be weakly referenced; those objects which can include class instances, functions written in Python (but not in C), and methods (both bound and unbound). I've been unable to get using a bound method as the key in a WeakKeyDictionary to work. Using a class instance object works fine as a key, using a method of that same instance object does not. Here's some code, in a file named test_weakref.py: #! /usr/bin/env python import unittest import weakref class someClass(object): def aMethod(self): print "Hi!" class TestCase_01_weakref(unittest.TestCase): def test_01_simple(self): obj1 = someClass() obj2 = someClass() wkd = weakref.WeakKeyDictionary() wkd[obj1] = 1 self.assertEqual(len(wkd), 1) wkd[obj1.aMethod] = 1 self.assertEqual(len(wkd), 2) wkd[obj2.aMethod] = 1 self.assertEqual(len(wkd), 3) if __name__ == "__main__": unittest.main() And here's the output: ./test_weakref.py F ====================================================================== FAIL: test_01_simple (__main__.TestCase_01_weakref) ---------------------------------------------------------------------- Traceback (most recent call last): File "./test_weakref.py", line 22, in test_01_simple self.assertEqual(len(wkd), 2) File "/usr/local/lib/python2.3/unittest.py", line 302, in failUnlessEqual raise self.failureException, \ AssertionError: 1 != 2 ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1) It is acting as though a bound method is silently not allowed as the key in a WeakKeyDictionary. Can someone set me straight? From rnd at onego.ru Wed Jun 2 12:50:28 2004 From: rnd at onego.ru (Roman Suzi) Date: Wed, 2 Jun 2004 20:50:28 +0400 (MSD) Subject: 2.2 <-> 2.3 surprise In-Reply-To: References: Message-ID: On Mon, 31 May 2004, Shalabh Chaturvedi wrote: >Roman Suzi wrote: > >> Hi! >> >> I really like python 2.3 but sometimes I write for 2.2 too. >> >> New cool feature of doing: >> >> f = open('file') >> for line in f: >> do_something(line) >> >> works strange in 2.2: I can't just quit first loop and do: >> >> for line in f: >> do_some_more(line) >> >> (I as skipping message header by first loop and processing body >> the the second). >> >> In 2.3 it works as intended! Of course, simple refacture made it one loop... >> >> >> >> Sincerely yours, Roman Suzi > >This is probably the following change as described in >http://www.python.org/2.3/highlights.html > >"File objects are now their own iterators. This makes multiple >interrupted iterations over the same file more reliable." Hmmm... Such gradual changes IMHO are worse than just adding something at once. The problem is I was getting no warnings that something is wrong. In some big project this could break a lot. >Something that *might* work in both 2.2 and 2.3 using multiple loops is >(not tested): > >f = iter(open('file')) > >...and then use f as before. > >-- >Shalabh > > > > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From claird at lairds.com Thu Jun 3 09:49:10 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 13:49:10 -0000 Subject: Why did no one invent Python before? References: Message-ID: <10bub2m9g9km251@corp.supernews.com> In article , Dennis Lee Bieber wrote: . . . > I was using Python on my Amiga nearly a decade ago (when did the >first edition of the Python book come out?). Say 30 years to go from '60 . . . O'Reilly published the first edition of *Programming Python* in October 1996; is that what you're after? -- Cameron Laird Business: http://www.Phaseit.net From lesstif-admin at lesstif.org Sat Jun 12 02:23:26 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Sat, 12 Jun 2004 06:23:26 -0000 Subject: Request to mailing list Lesstif rejected Message-ID: Your request to the Lesstif mailing list Posting of your message titled "Mail Delivery (failure lesstif at lesstif.org)" has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From hungjunglu at yahoo.com Sun Jun 20 13:00:33 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Jun 2004 10:00:33 -0700 Subject: OT: Chat server References: <8ef9bea6.0406170749.399c4956@posting.google.com> <10d5tv08jqund2@corp.supernews.com> Message-ID: <8ef9bea6.0406200900.38eed8df@posting.google.com> claird at lairds.com (Cameron Laird) wrote: > Hung Jung, please be more specific about the defects of the books. > I know of four different ones, and I mildly favored one in http://www.unixreview.com/documents/s=8217/ur0306c/ >. If it has > defects I overlooked, I want to know, so as not to mislead readers > or Miki. I haven't seen that book myself. The only book available in my local bookstores was: "Jabber Developer's Handbook", by Dana Moore, William Wright and that one I really did not like. I took a look at it in more than 5 runs to the local bookstores. And overall I found it useless. I don't know how else to say it. I mean, if I pick up a book like "Learning Python," I get productive in 5 minutes. With this other book, I wouldn't be productive even after 5 days. I got replies in May from the Jabber Dev mailing list. Here is what people said: (1) "Most of the Jabber books ive seen have been out for quite a while and will I expect be very out of date for all but the most simplest things, I doubt its worth buying them. Richard" (2) "I found "Programming Jabber" by DJ Adams very informative, easy to read to not to far out of date. I do NOT recommend the other books, "Jabber Programming" by Lee and Smelser and Jabber Developer's Handbook by William Wright. Very confusing or little information, stick with Adams. With the Adams book, the JEPs, a client, 10 lines of python code and jabberd running in debug mode, you can explore jabber effectively. Well, that's what I did to learn about it for my non-IM based research project." So I guess I paid too much attention to the first person's comment. :( The second person's opinion seems in line with your recommendation, so that's good. I'll look into Adams' book. Thanks. Hung Jung From hungjunglu at yahoo.com Mon Jun 7 12:55:15 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 7 Jun 2004 09:55:15 -0700 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: <8ef9bea6.0406070855.220b70ae@posting.google.com> "Michael Geary" wrote: > > Your message title is correct: you're misunderstanding how closures work. > :-) So seems to be your case. :) > In your first example, there is a single local name x that each instance of > the f closure refers to, so they all see the same value. There is a name, period. This name is neither local or global. This name is looked up first in the locals() dictionary, then in the globals() dictionary. In this particular example, because the locals() dictionary is empty, this name is actually pulled from globals(). > In the second example, each time you call the makef function, you create a > new local name x that belongs to that instance of makef. So when you create > the closures inside makef, each one sees its own value that is unrelated to > the others. And your explanation is supposed to enlighten a beginner? A more complete explanation. The key is in the argument list. Because 'x' appears in the argument list of makef(x), this name is inserted into the locals() dictionary of makef()'s scope. That is, the name 'x' inside makef()'s scope is pulled from the locals() dictionary of that scope. Now, due to the magic of nested scope (which was not always the case in older versions of Python), this 'x' is also inserted into the locals() dictionary of the nested f() function, and this 'x' is bound to the value at that moment, because during the constructions of f(), it is found that 'x' is used in expressions AND it exists in the containing scope's locals() dictionary at the moment of construction. In particular, it will not work correctly if you replace the statement "return x" with "return eval('x')". Everything becomes more clear when you insert statements to print out the locals() and globals() dictionaries. regards, Hung Jung From skip at pobox.com Tue Jun 8 09:44:22 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jun 2004 08:44:22 -0500 Subject: any simple and multiplatform database? In-Reply-To: <001901c44d59$a27bffc0$0200a8c0@lucifer> References: <001901c44d59$a27bffc0$0200a8c0@lucifer> Message-ID: <16581.49846.271286.610876@montanaro.dyndns.org> Simon> Is there any simple and multiplatform database for python ? I believe a fair number of people are fond of SQLite: http://www.hwaci.com/sw/sqlite/ Skip From ergin_aytac at yahoo.de Fri Jun 25 19:42:47 2004 From: ergin_aytac at yahoo.de (Ergin Aytac) Date: Fri, 25 Jun 2004 23:42:47 GMT Subject: SocketServer Problem In-Reply-To: <40dcb2fc$0$559$e4fe514c@news.xs4all.nl> References: <7s1Dc.126130$vP.103291@news.chello.at> <40dcb2fc$0$559$e4fe514c@news.xs4all.nl> Message-ID: The origin script is a gateway for syncronizing news on usenet servers. As I can see there are a lot of people who use this script for public usenet groups. I saw some using it for news.php.net, news.mozilla.org without being a part of this domains. Besides I have the access rights for news.chello.at which recognizes me over the domain name I'm using. Without any access rights I should also get access to a few public groups. The friend who tried this server without any errors doesn't work for chello and his box is not a part of chello. Something is strange here... Can I bind a socket to an address that is public and has no access limits? (like public usenet servers as news.php.net or news.mozilla.org) Irmen de Jong schrieb: > Ergin Aytac wrote: > >> nntp_hostname = 'news.chello.at' >> nntp_port = 119 > > > > I very much doubt it that the computer you are trying to run > the program on, is actually called "news.chello.at".... > >> socket.error: (10049, "Can't assign requested address") > > > You cannot bind a socket on an address that is not 'yours' ... > >> The script above worked without any error message on a box of friend. > > > Now that is weird. Unless your friend works for Chello and his > box is "news.chello.at"... > > --Irmen From davidf at sjsoft.com Sat Jun 19 07:07:31 2004 From: davidf at sjsoft.com (David Fraser) Date: Sat, 19 Jun 2004 13:07:31 +0200 Subject: Python 2.3.4 hangs when run from modern cygwin/bash in WinXP, but is otherwise fine In-Reply-To: <67032014.0406181707.2822aa03@posting.google.com> References: <67032014.0406181707.2822aa03@posting.google.com> Message-ID: Eric Woudenberg wrote: > I just installed a Python 2.3.4 Windows binary on a friend's WinXP > machine (because the latest Cygwin-provided Python 2.3 build leaves > out the winsound module for some reason). > > When I try and run this newly installed Python from bash it just hangs > (no version message, no prompt, CPU is idle). When I run it from IDLE, > or the DOS CMD prompt, it runs fine. Also, Python scripts using the > new version run fine, even invoked on the bash command line. It seems > there's some problem with terminal i/o when invoked from bash. > > However, using this same installer, Python 2.3.4 runs fine on my WinXP > machine (though mine is using an older version of cygwin). > > Meanwhile, his cygwin-provided Python 2.3 runs fine from bash. > > I haven't been able to figure out what's wrong. Does anyone have any > suggestions? > > Thanks kindly in advance! > > Eric Woudenberg Yes, set CYGWIN=notty and then run python -i (to force it into interactive mode) David From BELLEMAIL-SA at exponent.com Thu Jun 10 10:40:36 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 10 Jun 2004 07:40:36 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28D6C@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = peter at engcorp.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 123 Scanning time = 06/10/2004 07:40:36 Engine/Pattern = 7.000-1004/903 Action taken on message: The attachment yours.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From __peter__ at web.de Fri Jun 4 11:36:31 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jun 2004 17:36:31 +0200 Subject: heredoc and variables References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> Message-ID: flupke wrote: > 2) Consider following heredoc > > end_html=""" > """ > > I have to write it like this to avoid having an empty line added above > AND below the actual string when using it. Why would you care about whitespace in HTML? > So this would produce the extra empty lines > > end_html=""" > > > """ > > I actually think that the last piece of code is more readable. Is there > a way to stop that behaviour or is there a kind of trim function i > can apply to get rid of the 2 extra lines? >>> print """\ ... here's how \ ... to escape \ ... newlines""" here's how to escape newlines >>> Peter From http Sat Jun 12 12:55:57 2004 From: http (Paul Rubin) Date: 12 Jun 2004 09:55:57 -0700 Subject: accumulators References: Message-ID: <7xn038u34y.fsf@ruckus.brouhaha.com> Eugene Van den Bulke writes: > It seems to me that this code does the job (but I am not sure I > understand exactly what an accumulator is): > > def test(n): > return lambda i: n+i > > Is that an accumulator? If it is, PG must have written this chapter > working on an older verion of Python ... No. The idea of an accumulator is that whenever you call it, the internal state updates. That is, if accum(n) creates an accumulator, you should be able to say: a = accum(3) # create accumulator holding 3 print accum(2) # prints "5" print accum(3) # prints "8" print accum(1) # prints "9" etc. The Pythonic way to do it is with a class instance: class accum: def __init__(self, n): self.s = n def __call__(self, i): self.s += i return self.s a = accum(3) (etc.) however, for programmers comfortable with the Lisp idioms of using internal lambdas, the class/object approach is cumbersome. From tzot at sil-tec.gr Thu Jun 3 12:26:37 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 03 Jun 2004 19:26:37 +0300 Subject: How to pickle a subclass of tuple? Message-ID: __getstate__ is easy: def __getstate__(self): return tuple(self) but even def __getstate__(self): return self seems to work, as far as Pickle.dump is concerned. The problem is, how one writes a __setstate__ for an immutable class? -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From nospam at nospam.org Thu Jun 3 11:33:01 2004 From: nospam at nospam.org (MF) Date: Thu, 03 Jun 2004 17:33:01 +0200 Subject: Background of editor in eric3 References: <2i8m0jFk8st1U1@uni-berlin.de> Message-ID: Reiner Block wrote: > Hi, > > I installed eric3 and done the settings. But I don't like the white > background and changed at Options/Editor/Sourcecode, language Python the > background color and font. But it affects just the source text in the > editor. After the end of the text in each line is still the white > background. > > But I found no possibility to change that. Does I am blind or is it really > not possible? > > > Blind greetings not so blind :-) I can confirm Reiner's problem: installed eric3 two days ago and I could not find a possibility to change the bg color. Moreover: qscintilla has an enormous right click menu with all kind of options that should usually be placed somewhere in the real menu. Right click by mistake makes me wishing a mouse without the right button :-) As for white screens, I don't know what other people think, but I used to use them a lot in my now past night net wanderings, believing they are more easy for the eyes. Apparently no, quite the contrary, when last checking my eyes, the doctor told me white text in black screen (paper) is called "inverse contrast" and because they are... so inverse to what we are used to from school, they are in fact more tiresome, only we do not realize it. The right screen should look something like a book, black on white, anyway light background... My 2c, MF. From me at privacy.net Fri Jun 18 04:24:12 2004 From: me at privacy.net (Duncan Booth) Date: 18 Jun 2004 08:24:12 GMT Subject: align on char References: Message-ID: Tor Iver Wilhelmsen wrote in news:u4qparl23.fsf at broadpark.no: > Jeff Epler writes: > >> ... width = max([len(i[0]) for i in seq]) >> ... return ["%s:%s" % (a.ljust(width), b) for a, b in seq] > > You can also do a > fmt = "%" + str(-max) + "s : %s" > return [fmt % (a, b) for a, b in seq] > > instead of that last line. Dunno if that's more readable, though. :) Or a little less contorted: return ["%-*s:%s" % (width, a, b) for a, b in seq] From peter at engcorp.com Mon Jun 7 22:31:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jun 2004 22:31:31 -0400 Subject: Catching a traceback In-Reply-To: <7ismd6bxuu.fsf@enark.csis.hku.hk> References: <7ismd6bxuu.fsf@enark.csis.hku.hk> Message-ID: <8cydnWn6cOqZuFjdRVn-sQ@powergate.ca> Isaac To wrote: > I think the OP's query is mainly about whether it is possible to print a > stack trace without crashing the whole program. If that's the case, then he should check the documentation for the "traceback" module... it has the facilities for doing this easily, sometimes in conjunction with sys.exc_info(). -Peter From roy at panix.com Wed Jun 9 12:16:26 2004 From: roy at panix.com (Roy Smith) Date: Wed, 09 Jun 2004 12:16:26 -0400 Subject: speed problems References: <639f17f8.0406090728.4e4e0bc6@posting.google.com> Message-ID: In article <639f17f8.0406090728.4e4e0bc6 at posting.google.com>, nholtz at docuweb.ca (Neal Holtz) wrote: > > I've halved the python time on my test by changing the entire inner loop > to: > > pat = re.compile( "MALWARE:\s+(.*)" ) > for line in lf: > mo = pat.search( line ) > if mo: > for vnam in mo.group(1).split( ", "): > virstat[vnam] = virstat.get(vnam,0) + 1 > total += 1 > lf.close() A few random thoughts... 1) How often is mo true? In other words, what percentage of the lines in the file match the pattern? If it's very high or very low, that might give you some ideas where to look. Running the profiler will help at lot too! 2) It's probably a minor tweak, but you could factor out the "pat.search" name lookup cost by doing something like: pat = re.compile( "MALWARE:\s+(.*)" ) patSearch = pat.search for line in lf: mo = patSearch (line) .... 3) There's a certain amount of duplication of effort going on between the regex search and the split; two passes over the same data. Is it possible to write a regex which parses it all in one pass? Of course, if the answer to question #1 is "very low percentage", then this is probably not the place to be looking. 4) What does virstat.get do? Lastly, a general programming style comment. I'm a fan of longish variable names which describe what they're doing. I had to think a bit to figure out that vnam probably stands for "virus name". It would have been easier for me to figure out if you named the variable something like virusName (or even virus_name, if you're an underscore fan). Same with the other variable names. From fishboy at spamspamspam.com Thu Jun 3 01:02:22 2004 From: fishboy at spamspamspam.com (fishboy) Date: Thu, 03 Jun 2004 05:02:22 GMT Subject: Why did no one invent Python before? References: Message-ID: On Thu, 03 Jun 2004 04:26:27 GMT, Dennis Lee Bieber wrote: > Now consider that for much of that period, computers were these >big monolithic things that billed one by the second -- making >interpreters rather expensive to run, not to mention editing on card >decks. > > It takes computer power to process a language... Imagine having >to pay the time used for Python, when running on a processor like my >college mainframe (we had 1MB of core! It was a big event when we >obtained a pair of 300MB drives to support the OS swap space). Oh, and >terminals ran at 1200baud, monochrome, text-only. > and you had to use upload bandwidth both ways.... rats! just remembered someone made this joke already in #twisted. ><{{{*> From maxm at mxm.dk Mon Jun 14 06:08:30 2004 From: maxm at mxm.dk (Max M) Date: Mon, 14 Jun 2004 12:08:30 +0200 Subject: Searching for the best scripting language, In-Reply-To: <2c60f0e0.0406131234.49b485ec@posting.google.com> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <40CD791E.6000701@mxm.dk> Richard James wrote: > Are we looking at the scripting world through Python colored glasses? > Has Python development been sleeping while the world of scripting > languages has passed us Pythonista's by? Everyone knows that any scripting language shootout that doesn't show Python as the best language is faulty by design. regards Max M From sholden at holdenweb.com Fri Jun 25 08:32:27 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 25 Jun 2004 08:32:27 -0400 Subject: python image library making dotty gifs In-Reply-To: <10do4ifds0a7j58@corp.supernews.com> References: <10do3bfmr93ke48@corp.supernews.com> <10do4ifds0a7j58@corp.supernews.com> Message-ID: <40DC1B5B.5070207@holdenweb.com> Alex Hunsley wrote: > Alex Hunsley wrote: > >> I'm using python image library 1.1.4 >> (http://www.pythonware.com/products/pil/) to plot images. >> However, when I save an image to a gif file, it comes out very >> dotty/ithered looking, even if it's a picture consisting only of one >> colour! >> >> Here's some example code that produces a dotty gif: >> >> #!/usr/bin/python >> >> # pymand joy! >> >> import Image >> import ImageDraw >> >> >> imageWidth=300 >> imageHeight=300 >> >> im = Image.new("RGB", (imageWidth, imageHeight)) >> >> >> draw = ImageDraw.Draw(im) >> for y in range (0,imageHeight): >> for x in range (0, imageWidth): >> draw.point((x, y), (128,128,128)) >> >> # saving as a gif comes out dotty/dithered looking! >> im.save("plotImage.gif", "GIF") >> >> >> you can see the output gif here: >> >> http://ohmslaw.ogr.uk/plotImage.gif > > > sorry, duff link, should be .org.uk: > > http://ohmslaw.org.uk/plotImage.gif > That's because PIL is storing the image as an indexed image, presumably using a palette that doesn't contain your exact color, and hence the software is dithering (that's a technical term, it doesn't mean the program can't make it's mind up ;-) to approximate the color you asked for. Try using a color from the web-safe palette (google for it) or better still (even though the patents are now expired almost everywhere) use PNG instead. regards Steve From __peter__ at web.de Sat Jun 12 03:05:51 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jun 2004 09:05:51 +0200 Subject: string to object? References: Message-ID: Guy Robinson wrote: > To clarify things more (as I should have done yesterday): > > incompatible signatures are not what I want and I do understand I need > to instance the class first so yes > > class foo: > def method1(self, *args): > return 'one' > def method2(self, *args): > return 'two' > ifoo=foo() > > is more like it. I have a number of classes with methods. For various > reasons the class.method to run is only available as a string. The > arguments arrive independently. So the question is how can I convert a > string to a class.method object for instancing? > > Pseudo python: > > s = 'foo.method1' > arg = [] > sclass,smethod = string2class(s) > isclass = sclass.smethod(arg) You are still concentrating too much on the technical details. For the problem at hand, a plain english description would probably allow us to come up with a better approach. Anyway, here's another variant: class foo: def method1(self, *args): return "foo-method1%r" % (args,) def method2(self, *args): return "foo-method2%r" % (args,) class bar: def alpha(self, *args): return "bar-alpha%r" % (args,) def ensureInstance(klass, instCache={}): try: return instCache[klass] except KeyError: inst = instCache[klass] = globals()[klass]() return inst calls = ["foo.method1", "foo.method2", "bar.alpha", "foo.method2"] args = (1,2,3) for call in calls: className, methodName = call.split(".") inst = ensureInstance(className) boundMethod = getattr(inst, methodName) print boundMethod(*args) If you need the classes as namespaces rather than to preserve state you could make the methods static methods. The code would then become class foo: def method1(*args): return "foo-method1%r" % (args,) method1 = staticmethod(method1) def method2(*args): return "foo-method2%r" % (args,) method2 = staticmethod(method2) class bar: def alpha(*args): return "bar-alpha%r" % (args,) alpha = staticmethod(alpha) calls = ["foo.method1", "foo.method2", "bar.alpha", "foo.method2"] args = (1,2,3) for call in calls: className, methodName = call.split(".") staticMethod = getattr(globals()[className], methodName) print staticMethod(*args) Peter From dblume at pinnaclesys.com Thu Jun 10 16:18:41 2004 From: dblume at pinnaclesys.com (David Blume) Date: 10 Jun 2004 13:18:41 -0700 Subject: Python function for building .NET 2003 Solutions Message-ID: I'm very grateful to Roger Burnham for his Visual Studio 6.0 build script listed here: http://mail.python.org/pipermail/python-list/2001-December/076881.html Now that I'm building projects in .NET 2003, I thought I'd post an update to his DoBuild() function that does the same thing with Solutions. Note the differences: 1. Instead of having a RebuildAll() function, we have to Clean() then Build(). This function does the cleaning of all the targets in one pass, then the building of all the targets, in case some targets share dependencies. 2. On a compile-time error, instead of raising SystemExit, which is much cleaner, this script returns the BuildLog.htm of the component that failed. (Which may not have been the target that was built, but a sub-project.) I didn't really know how to determine exactly which subproject failed, so I parse the contents of the output window to find it. (VC6 is much easier, the .plg file showed the build status of the target and all its dependencies.) Anyway, here's BuildSolution() with similar parameters as Roger's DoBuild(). Please fix any line-wrapping errors that have occurred between my sending of the post and your reception of it. Sorry about those. import win32com.client.dynamic import string import pywintypes import win32clipboard import win32con def BuildSolution(VC, solution, projectList, configSuffix, force): """Build Visual C++ 7.1 Solutions returns None if successful, or the build log if there were compile time errors.""" if VC is None: VC = win32com.client.Dispatch('VisualStudio.DTE') VC.MainWindow.Visible = True VCDocs = VC.Documents VCDocs.CloseAll(3) sln = VC.Solution sln.Open(solution) slnBuild = sln.SolutionBuild tailLen = len(configSuffix) # First, clean everything if doing a forced rebuild if force: for projectName in projectList: for project in sln.Projects: if str(project.Name) == projectName: for config in slnBuild.SolutionConfigurations: name = str(config.Name) if name[-tailLen:] == configSuffix: for context in config.SolutionContexts: if projectName + "." in context.ProjectName: context.ShouldBuild = True break break slnBuild.Clean(True) # Then, build the specified projects for projectName in projectList: projFound = 0 for project in sln.Projects: if str(project.Name) == projectName: projFound = 1 for config in slnBuild.SolutionConfigurations: confFound = 0 name = str(config.Name) if name[-tailLen:] == configSuffix: confFound = 1 slnBuild.BuildProject(config.Name, project.UniqueName, True) if slnBuild.BuildState == 3: if slnBuild.LastBuildInfo != 0: print 'There were', slnBuild.LastBuildInfo, 'errors building', projectName + '.\n' # We have to jump through some hoops to determine which # subproject actually failed, because the BuildLog.htm # associated with this target does not reflect the # compiled state of the subprojects.Here's what we do: # 1. Obtain the OutputWindow from MSDev. # 2. Copy the text to the clipboard, and extract that # into a "lines" array. # 3. Search for lines containing the word "error" and # assume that's the first failed project. # 4. Extract and return the filename of the # BuildLog.htm for the assumed failed project. outputPane = VC.Windows.Item('{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}').Object.ActivePane # vsWindowKindOutput outputPane.TextDocument.Selection.SelectAll() outputPane.TextDocument.Selection.Copy() outputPane = None win32clipboard.OpenClipboard(0) lines = win32clipboard.GetClipboardData(win32con.CF_TEXT) win32clipboard.CloseClipboard() bFoundErrorMessages = False LogfileString = "Build log was saved at \"file://" for line in string.split(lines, "\n"): if not bFoundErrorMessages and line.find(" : error ") != -1: print "This is the first error:" print line + "\n" bFoundErrorMessages = True if bFoundErrorMessages and line.startswith(LogfileString): return line[len(LogfileString):line.rfind('"')] raise "Could not locate the failing project's logfile." else: raise "BuildProject is returning asynchronously!" break if not confFound: print 'Build failed: Could not find the', configSuffix, 'for', projectName + '.' break if not projFound: print 'Build failed: Could not find the project', projectName + '.' return None From duncan-news at grisby.org Fri Jun 11 06:04:48 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Fri, 11 Jun 2004 12:04:48 +0200 Subject: bogus OverflowError: python bug? References: <40C3D7DF.8010504@xplantechnology.com> <40c40420$0$27048$9b622d9e@news.freenet.de> Message-ID: <5502e$40c983c0$51604868$20355@nf1.news-service-com> In article , Luke wrote: >Martin v. L?wis wrote: >> There are other possible causes for bogus exceptions. A common one is >> that Python set an exception at some point, but the extension module >> forgot to forward the exception. Then, the next time Python checks >> for exceptions, it sees that there still is an exception pending, and >> raises it. That exception will make no sense that that point, of course. > >Oh yes of course, thanks... this sounds to be more consistent with the >repeatability of the bogus exception. > >> Only a gdb session can tell what really happened. > >Ouch. I might try searching the omniORB extension module for a >forgot-to-forward-exception bug first. The best thing for you to do is to subscribe to the omniORB mailing list, and post as much information as you can about the problem. Please include the full traceback, and a log from omniORB run with -ORBtraceLevel 25. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From siona at chiark.greenend.org.uk Wed Jun 30 13:13:53 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jun 2004 18:13:53 +0100 (BST) Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <1bs*2tkoq@news.chiark.greenend.org.uk> Message-ID: Peter Maas wrote: >AFAIK Postgres 7.4+ can be compiled with MINGW/MSYS on a Windows >platform and the resulting binary runs without Cywin. Hmm, my reading of the docs is that that only applies to clients, and not the server itself. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From tim.golden at tesco.net Fri Jun 25 17:00:36 2004 From: tim.golden at tesco.net (Tim Golden) Date: Fri, 25 Jun 2004 21:00:36 +0000 (UTC) Subject: Windows XP - cron or scheduler for Python? In-Reply-To: <40db4300$0$48959$e4fe514c@news.xs4all.nl> References: <40db4300$0$48959$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Tim Golden wrote: > > [...] > >> s.start () >> while 1: >> try: >> try: >> pass >> except KeyboardInterrupt: >> break >> finally: >> s.stop () > > > That's not a very good way of doing that. > This will eat 100% CPU time, it's a busy wait loop... > You should use time.sleep or something else to avoid > busy waiting. > But since you used the 'regular' Scheduler class from > Kronos, it will loop inside the s.start() by itself ... ;-) > > --Irmen Thanks. For some reason it doesn't actually use 100% CPU, otherwise I'd have spotted it slowing down my machine. I take the point, though. To be honest, I was just trying the thing out. Also, I have to kick myself for even writing that particular piece of code like that. TJG From opengeometry at yahoo.ca Fri Jun 11 05:10:41 2004 From: opengeometry at yahoo.ca (William Park) Date: 11 Jun 2004 09:10:41 GMT Subject: [script] dis/assembling mbox email References: <2is2ebFr1sbvU1@uni-berlin.de> Message-ID: <2itb8gFr46o9U1@uni-berlin.de> In William Park wrote: > Strictly speaking, MIME boundary pattern consists of any number of > [ A-Za-z0-9'()+_,./:?-] ... > if grep -o "boundary=\"[ A-Za-z0-9'()+_,./:?-]*[A-Za-z0-9'()+_,./:?-]\"" header > boundary; then Typo: Add '=' (equal sign) to the regexp above. -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From peter at engcorp.com Mon Jun 21 10:28:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 10:28:24 -0400 Subject: shared file access in python In-Reply-To: <9418be08.0406210618.492f40d4@posting.google.com> References: <9418be08.0406180620.3e64be96@posting.google.com> <9418be08.0406210618.492f40d4@posting.google.com> Message-ID: Lev Elblert wrote: > 2. msvcrt.lib does have a lot of functions, but not msvcrt module in > Python. (correct me if I'm wrong) http://docs.python.org/lib/module-msvcrt.html shows there are a variety of functions there (try typing "import msvcrt" as well), but I can't see that they have what you need. -Peter From gerrit.muller at embeddedsystems.nl Tue Jun 29 02:36:17 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Tue, 29 Jun 2004 08:36:17 +0200 Subject: file compression In-Reply-To: References: Message-ID: Skip Montanaro wrote: > Elaine> The files I'm working with are python modules and LaTeX source > Elaine> files, and I need to make them into archives so I can store them > Elaine> in my website. > > Check out the zipfile module and class: > > % pydoc zipfile > ... > class ZipFile > | Class with methods to open, read, write, close, list zip files. > | > | z = ZipFile(file, mode="r", compression=ZIP_STORED) > | > | file: Either the path to the file, or a file-like object. > | If it is a path, the file will be opened and closed by ZipFile. > | mode: The mode can be either read "r", write "w" or append "a". > | compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib) > ... > > Skip > I use ZipFile exactly as described here to pack my latex and visio source files adn publish them on internet at the Gaudi systems architecting website: . This works great: only a few lines of code are needed. regards, Gerrit -- Gaudi systems architecting: From Mike at DeleteThis.Geary.com Wed Jun 2 13:51:52 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 2 Jun 2004 10:51:52 -0700 Subject: Python Only 30% Slower than C In Certain Cases References: <889cbba0.0406012222.19550dc9@posting.google.com> Message-ID: <10bs4ts4rvbis13@corp.supernews.com> Kamilche wrote: > ...This test was done with the debug version of the C > program. The release version showed it was about 12x > faster than Python, with a smaller memory footprint. So, your message title is wrong. It should read: "Python Only 12 times slower than C in certain cases" ;-) The point is that nobody would ever do a performance comparison using *unoptimized* C code. I'm with you on the development speed of Python, though. I'd rather use Python or Ruby any day instead of C/C++. -Mike From miki.tebeka at zoran.com Sun Jun 20 04:24:34 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 20 Jun 2004 10:24:34 +0200 Subject: Robot In-Reply-To: <81a41dd.0406161319.1ec68dbb@posting.google.com> References: <81a41dd.0406161319.1ec68dbb@posting.google.com> Message-ID: <20040620082434.GA308@zoran.com> Hello Lad, > Does anyone know about a script that can walk through webpages and > extract an information from these web sites according to given > keyword(s)? Have a look at the "webchecker" app that comes with Python. HTH. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From ralf at brainbot.com Tue Jun 8 12:55:10 2004 From: ralf at brainbot.com (Ralf Schmitt) Date: Tue, 08 Jun 2004 18:55:10 +0200 Subject: registering entities with sax parser Message-ID: <86aczem1ld.fsf@stronzo.brainbot.com> Hi, is there a way to register entity definitions with a sax parser? I want the following program to work without specifying an DTD in the xml document. from xml.sax import handler, make_parser class Parser(handler.ContentHandler): def startElement(self, name, attrs): print name, attrs['foobar'] doc = ''' ''' make_parser().feed(doc).close() Thanks for any help, - Ralf -- brainbot technologies ag boppstrasse 64 . 55118 mainz . germany fon +49 6131 211639-1 . fax +49 6131 211639-2 http://brainbot.com/ mailto:ralf at brainbot.com From tim.one at comcast.net Fri Jun 11 15:50:34 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 15:50:34 -0400 Subject: does python have useless destructors? In-Reply-To: Message-ID: [Delaney, Timothy C] >>> myfile = open("myfilepath", "w") >>> >>> try: >>> myfile.write(reallybigbuffer) >>> finally: >>> myfile.close() [Tim Bradshaw] >> I don't think this is save. Is it certain that there can be no problem >> between the open and the try? [Peter Hansen] > Yes, it's certain to be safe (barring multithreaded stuff rebinding > 'myfile' in between, which is irrelevant to the discussion). Are you > perhaps concerned that the open itself might fail? If so, it needs its > own try/except block, as I noted elsewhere. The finally is only need > *if* the open succeeds, but unless you insert code between open() and > 'try', it's safe. Believe it or not, it isn't entirely "safe", but for a different reason: it's quite possible for, e.g., KeyboardInterrupt to get raised and processed between the "finally:" and the "myfile.close()" -- Google on "safe asynchronous exceptions for python" for a good paper on the topic. From siona at chiark.greenend.org.uk Wed Jun 16 12:18:39 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Jun 2004 17:18:39 +0100 (BST) Subject: Dynamic module importing with McMillan installer Message-ID: We have an application which we distribute as a .exe as created with the McMillan installer, plus a suite of "plugins" which can also be run as standalone applications for internal use. The plugins work by freezing the standalone application and taking the out1.pyz, suitably renamed, and adding the new file name to sys.path at run time. We can then __import__ the module (or, specifically, the plugin interface from it). Which works fine, apart from one new plugin which works unfrozen, works as a frozen standalone, but when trying to import it frozen generates an ImportError from Installer/iu.py, "No module named ". It's using, as far as I can tell, the same commands to build the .pyz as a correctly functioning plugin module. Does anyone have the slightest clue what might be going wrong? (Python 2.3 on W2K, McMillan Installer 5 b5_5.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From aahz at pythoncraft.com Tue Jun 8 13:30:23 2004 From: aahz at pythoncraft.com (Aahz) Date: Tue, 8 Jun 2004 13:30:23 -0400 Subject: BayPIGgies REMINDER: June 10, 7:30pm Message-ID: <20040608173023.GA25869@panix.com> The next meeting of BayPIGgies will be Thurs June 10 at 7:30pm. It will feature Bruce Eckel talking about Python's type system. BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, we'll continue the tradition started last month and meet at 6pm for dinner, at Jing Jing in downtown Palo Alto. Ducky Sherwood is handling that; please send RSVPs to ducky at osafoundation.org Discussion of dinner plans is handled on the BayPIGgies mailing list. NOTE: Please RSVP by 3pm Thurs if you want to attend the dinner. Jing Jing 443 Emerson St. (half block north of University) Palo Alto 650-328-6885 Advance notice: The July 8 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From jg at jonasgalvez.com Mon Jun 7 13:46:43 2004 From: jg at jonasgalvez.com (Jonas Galvez) Date: Mon, 7 Jun 2004 14:46:43 -0300 Subject: Decoding 'funky' e-mail subjects References: Message-ID: Oliver Kurz wrote: > Have you tried decode_header from email.Header > in the python email-package? Thanks, that works. The problem is that I need to make it compatible with Python 1.5.2. I improved my regex-based method and it has worked fine with all my test cases so far. But if anyone has any other suggestion, I'm still interested. Anyway, here's my code: import re from string import * def decodeHeader(h): def firstGroup(s): if s.group(1): return s.group(1) return s.group() h = re.compile("=\?[^\?]*\?q\?", re.I).sub("", h) h = re.compile( "=\?(?:(?:(?:(?:(?:(?:(?:(?:w)?i)?n)?d)?o)?w)?s)?|" "(?:(?:(?:i)?s)?o)?|(?:(?:(?:u)?t)?f)?)" "[^\.]*?(\.\.\.)?$", re.I).sub(firstGroup, h) h = re.sub("=.(\.\.\.)?$", firstGroup, h) def isoEntities(str): str = str.group(1) try: return eval('"\\x%s"' % str) except: return "?" h = re.sub("=([^=].)", isoEntities, h) if h[-2:] == "?=": h = h[:-2] return replace(h, "_", " ") print decodeHeader("=?ISO-8859-1?Q?Marcos_Mendon=E7a?=") print decodeHeader("=?ISO-8859-1?Q?Test?=") print decodeHeader("=?UTF-8?Q?Test?=") print decodeHeader("Test =?windows-125...") print decodeHeader("Test =?window-125...") print decodeHeader("Test =?windo-1...") print decodeHeader("Test =?wind...") print decodeHeader("Test =?...") print decodeHeader("Test =?w...") print decodeHeader("Test =?iso...") \\ jonas galvez // jonasgalvez.com From bill.ramsay at clear.net.nz Thu Jun 3 01:56:55 2004 From: bill.ramsay at clear.net.nz (bill ramsay) Date: Thu, 03 Jun 2004 17:56:55 +1200 Subject: two silly questions Message-ID: Hello just found the wonderful world of python in the last two weeks and I think that it is great. I have a couple of questions for those who are wiser a la python than I am. Background: I have written a program that polls an email account, then pulls down the email, it then searches through the email, and depending upon type, ie. with or without attachments it does different things. The net result is that data is written to access tables for an external application to extract the necessary data. I am using win2k. the two questions are: 1. when i want the program to run in a loop, ie. poll the pop3 account every 60 seconds, it runs the first time, then it goes into 'not responding mode' thereafter, sometimes. Any thoughts? I was using sleep(60) but it just hangs, as i said before, it does not always do that either! 2. I wish to use this program at work, I took in an earlier version yesterday that just wrote the data to a text file, I wanted to make sure the polling thing worked. on microsoft exchange [i know that it should, but you never know!!] and it does . When i was there, i managed to get the code to run just by double clicking on the code ICON, seem to remember doing something with 'open with' can't seem to do it here at home. Both systems run win2k. did i do something sublimilally without realising it? what did i do i cannot remember, i have tried opening with etc. when i do this all get is a burst of the 'black windows box' just in the same way as putting in 'cmd' on the run thing, as you can see i am not up on all the terms. if anyone can help, i would appreciate it. kind regards bill ramsay. From peter at engcorp.com Mon Jun 7 18:11:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jun 2004 18:11:46 -0400 Subject: Brain Dead Singleton In-Reply-To: <40C4209A.6090403@jessikat.fsnet.co.uk> References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> <40C1B470.1000407@jessikat.fsnet.co.uk> <40C4209A.6090403@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Peter Hansen wrote: >> I don't think deleting things from >> sys.modules has defined, guaranteed behaviour, so I'm uncertain >> whether anyone should rely on it working. > > If sys.modules isn't intended to be a modifiable cache, perhaps we > shouldn't be given access to it. > > The docs for 2.3 say > "modules > This is a dictionary that maps module names to modules which have > already been loaded. This can be manipulated to force reloading of > modules and other tricks.... " Hmmm... I'd be more inclined to think it was an approval if it didn't use the term "trick" to describe it. Anyway, this now leads me to wonder whether any singleton pattern which doesn't involve manipulating __builtin__ is safe from deletion of items in sys.modules... -Peter From balaji at email.arizona.edu Thu Jun 10 18:19:48 2004 From: balaji at email.arizona.edu (Balaji) Date: 10 Jun 2004 15:19:48 -0700 Subject: Access atributes of different class.. Message-ID: <494182a9.0406101419.445069e7@posting.google.com> Hello Everybody... This is what I'm trying to do.. from generation import* class codegeneration: def __init__(self,expr): self.LP={} self.P=[] self.F=1. self= MatrixGenerator(expr) self.stackManagement(expr) generation module has the method stackManagement and its defined in class matrix generator. stackManagement return self. results..matrix Generator has an dictionary self.results when stackManagement is called something gets into self.results. Now I want to access this self.results thru codegeneration. How can I do that.. Balaji From roy at panix.com Tue Jun 22 07:48:28 2004 From: roy at panix.com (Roy Smith) Date: Tue, 22 Jun 2004 07:48:28 -0400 Subject: useless destructors References: Message-ID: In article , Marcin 'Qrczak' Kowalczyk wrote: > On Tue, 22 Jun 2004 02:36:24 -0700, David Turner wrote: > > > Further to the discussion from earlier titled "does python have > > useless destructors?", I've posted a brief summary of garbage > > collection, RAII, and the "using" clause (which is what PEP310's > > "with" clause amounts to). The post is here: > > > > http://dkturner.blogspot.com/2004/06/garbage-collection-raii-and-using.html > > You left "for later" a point which makes the last proposition unworkable: > how to implement selective refcounting in a dynamically typed language? > Will it still work if the refcounted object is referred to from a plain > object? The only way I can imagine is to manage refcounts on each object > passing, returning and rebinding. Well, you could take a page from perl, and "taint" refcounted objects. Any time you make a reference to an object, if the referenced object is refcounted, the referrer becomes refcounted too. The next question is, would this in practice end up refcounting most objects? If so, that would sort of defeat the purpose. From apardon at forel.vub.ac.be Tue Jun 29 03:22:55 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Jun 2004 07:22:55 GMT Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: Op 2004-06-28, Mark Hahn schreef : > > "Antoon Pardon" wrote > >> Well personnally I would solve this with a more general loop construct. >> >> Something like: (Pseudo code) >> >> loop: >> list.append(x) >> while len(list) < 10: >> blah blah. >> >> >> The more general construct would be something like: >> >> loop: >> code >> while condition1: >> code >> else: >> exit code if condition1 fails >> while condition2: >> code >> else: >> exit code if condion2 fail > > This seems non-intuitive to me. Also how would you know the "while" was not > a regular "while"? Even if the parser could figure it out, the reader would > be confused. These are details. If you want to do it with an other keyword, that is fine by me. I'm interrested in the functionality, not in a particular implementation. One possibility would be to not allow what you call a regular while, all loop constructs would need to start with a loop statement. An other possibility would be the "and while" construction that was dicussed here. Something like while condition1: loopcode else exitcode and while condition2: loopcode else exitcode. > BTW: Your code example has the "while" indentation not aligning with > anything above which is illegal indentation. I know. This is one reason I hate indentation as grammatical information. Some possible language constructs don't have a structure that is easily fitted in such a mold. You then see that such constructs are disregarded because of layout problems, not on lack of merrit for such a language construct. It also makes it sometimes difficult to have your program follow the logical structure of your program. e.g. if you have code like this: loop: loopcode1 and while condition loopcode2 You could simulate it like this while true: loopcode1 if not condition: break loopcode2 But in order to reflect the logical structure of above I would prefer to write the if alliged with the while. But that of course is not possible. -- Antoon Pardon From lard at tardis.ed.ac.molar.uk Tue Jun 29 10:41:03 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 29 Jun 2004 15:41:03 +0100 Subject: sending of mail (smtp) - connection refused - but smtp server is In-Reply-To: References: <10e2v1446n95e4b@corp.supernews.com> Message-ID: <10e2vs06fabvrc5@corp.supernews.com> Peter Hansen wrote: > Alex Hunsley wrote: > >> I am failing with "connection refused" error, even though we >> definitely have an smtp server running on port 25! > > ... > >> any ideas what the problem could be? this usually happens when someone >> is not aware they have to run an SMTP server, but we do have one >> running, as can be seen above! > > > Not sure, but please try this at the interactive prompt and report > (or analyze) what it returns: > > >>> from socket import * > >>> getaddrinfo('192.168.1.105', 25, 0, SOCK_STREAM) > > > This is something that smtplib.py is actually doing to get the > host:port combination that it uses to connect. It seems that > the only possible source for the failure you see is if it > does not return the expected values. > > -Peter Hi Peter when I run the above interactively, I get: [(2, 1, 6, '', ('192.168.1.105', 25))] I've just discovered something interesting. If I completely miss out connect() and close(), it works! i.e. my code now reads: s = smtplib.SMTP('192.168.1.105') #s.connect() s.sendmail(me, [you], msg.as_string()) #s.close() and this works! Is it a bad state of affairs to leave things in? thanks alex From peter at engcorp.com Mon Jun 14 15:05:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 15:05:54 -0400 Subject: Searching for the best scripting language, In-Reply-To: <2c60f0e0.0406141101.13df93ac@posting.google.com> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <2c60f0e0.0406141101.13df93ac@posting.google.com> Message-ID: <9uGdnW9CBYaOalDdRVn-vA@powergate.ca> Richard James wrote: > Well back in my day, in '75, "Real men" programmed in Intel binary > machine codes without using those "sissy" Assembly language > mnemonics... You used *binary*?! Ah, luxury.... > I think the value of maintainable code far outweighs cute one line > coding tricks... > > And no matter how close to the hardware it made you feel, I really > don't miss those #%$@ front panel switches! :) > > -- R.J. From michael at foord.net Mon Jun 14 11:34:37 2004 From: michael at foord.net (Fuzzyman) Date: 14 Jun 2004 08:34:37 -0700 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> <40cc1b05$0$41764$5fc3050@dreader2.news.tiscali.nl> Message-ID: <8089854e.0406140734.28ff0e8c@posting.google.com> Gr?goire Dooms wrote in message news:<40cc1b05$0$41764$5fc3050 at dreader2.news.tiscali.nl>... > Kamilche wrote: > > I love Python, but I'm less than in love with IDLE. It's OK, but it > > really doesn't have enough capabilities. > > > > What I consider critical, are a popdown listing of all my functions, > > colored syntax printing, and a right-click 'definition' context menu > > that will hop you to the spot where that keyword is defined, if > > possible. Everything else I could learn to do without, but these > > features keep me hoping for a better IDE for Python. > > > > I'm used to the Microsoft Visual C++ debugger, and though tooltip > > variable debugging and intellisense were nice, they broke often enough > > that you couldn't rely on them anyway, so I don't really need those > > features. > > > > I would also like the ability to create application 'forms' visually. > > I'm on a Windows XP machine. > > > > Any suggestions on what I should install next? > > This patch to IDLE improves it a bit: > http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group_id=5470&atid=305470 > > It adds among other things the pop-down function list. > It's a little cumbersome to apply but the result is quite good. > I've been using it for a few days and I'm quite happy with it. > I may provide a patch against python 2.3.3 or another version if someone > is interrested. > > If you are interresed, I made a smaller patch adding the qualified name > autocompletion (module.functions). But the former patch does it > better (it even supports filename autocompletion). This looks *very* interesting. How do you apply a patch like this ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From fishboy at SPAMredSPAMpeanutSPAM.com Tue Jun 15 01:56:39 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Tue, 15 Jun 2004 05:56:39 GMT Subject: How do you feel ? References: Message-ID: <84pt81e52c.fsf@redpeanut.com> Sylvain Hellegouarch writes: > Hi, > > A bit off topic. > > I just wondered what was your feeling when you were coding with > Python. I have beebn coding with different languages and the only > that has given me the will to invent or to be creative has been > Python. Python allows me not to focus on the complexity of the > language itself. > > Of course, from time to time, I find something that is not clear to > me but indeed after a couple of research you find the information > you were looking for. > > I love that language and above all, I love using it. > > Sorry for this little spam but it is always good to acknowledge good > things and not only complaining when it doesn't work. > > Thanks the Python team. - Sylvain I get a little giddy quite often. I start to think, "I can code anything!" Step 1. Code l33t application Step 3. Profit ><{{{*> From mwh at python.net Fri Jun 18 06:35:26 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jun 2004 10:35:26 GMT Subject: does python have useless destructors? References: <7ifz8udxp2.fsf@enark.csis.hku.hk> Message-ID: dkturner at telkomsa.net (David Turner) writes: [snippety] > We have three issues here - garbage collection (undoubtedly more > efficient than reference counting), RAII (undoubtedly safer than > try/finally), and PEP 310 (the "with" form). I fail to buy either of your 'undoubtedly's. You may be correct in both of them, but they both require justification... (Besides, saying garbage collection is more efficient than reference counting is like saying fruit is more tasty than apples). > I've already pointed out the problems with "with" (it's the same ball > game as try/finally, and suffers from the same limitations). I must have missed that. Message-ID? > So my opinion is that the RAII idiom should somehow be enabled in > Python. The crucial difference between "with" and RAII here is that > "with" requires intervention by the end-user of the object, whereas > the RAII idiom does not. Well, in C++ the distincton the creator of the object makes is that the RAIIed thing is an automatic variable, isn't it? > One possibility is to introduce scoped objects, analogous to auto or > stack-allocated objects. It would be illegal How do you tell that this has/is going to happen? If you can't pass one of these objects to a subroutine, the idea is nearly useless, I'd have thought. > to pass a reference to these outside of a given scope, and they > would have __del__ (or another method) called when the scope ends. > This is slightly cheaper than reference counting, but of course it > imposes very real limitations on the usefulness of the object. Ah :-) Cheers, mwh -- > So what does "abc" / "ab" equal? cheese -- Steve Holden defends obscure semantics on comp.lang.python From markv_at_letitrain_com at yougettheidea.com Sat Jun 5 10:56:53 2004 From: markv_at_letitrain_com at yougettheidea.com (MarkV) Date: Sat, 5 Jun 2004 10:56:53 -0400 Subject: #! shbang for pyc files? Message-ID: Is there a way to make it possible to execute a compiled python file (whatever.pyc) on a linux/unix system without requiring the user to type "python whatever.pyc"? In the case of a .py file, you can put "#! /usr/bin/python" at the top and chmod +x, and then you don't even need the .py extension to run it - just type "whatever" - but when you compile the file, it loses this ability! FYI, the context here is that we want to distribute scripts as part of an application, but we don't want users to go mucking around with the scripts. Yeah, I know, that's half the fun, but they don't get to muck around with the C programs, and when they do muck around with the current shell scripts, it causes us fits because their changes don't get into our source control. Thanks in advance for any suggestions. From frithiof.jensen at die_spammer_die.ericsson.com Tue Jun 22 07:41:51 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 22 Jun 2004 13:41:51 +0200 Subject: windows/python compatability References: <1a00439d.0406211538.52097044@posting.google.com> Message-ID: "kluge" wrote in message news:1a00439d.0406211538.52097044 at posting.google.com... > i'm a newbie to python. i'm learning to program and wanted to know how > to tell which version of windows my finished python program will work There is some system information in the "os" module. i.e. os.environ contains what is there and os.getenv() reads a single value. os.getenv('OS') f.ex. gets the name of the operating system; my box says 'Windows_NT' although it is really Win2k. If you stick to using Python functions *only* for everything "system-related" such as manipulating file paths (os.path may help), time e.t.c. then your program will probably run on anything Python runs on. From csad7 at yahoo.com Thu Jun 3 15:32:39 2004 From: csad7 at yahoo.com (chris) Date: Thu, 03 Jun 2004 21:32:39 +0200 Subject: reStructuredText Cheat Sheet In-Reply-To: References: Message-ID: David Goodger wrote: > I whipped together a cheat sheet for reStructuredText: > 1 page for syntax, and a 1 page reference for directives > and roles. Please take a look: > (not > meant to be converted to HTML; use the source text as-is). > Feedback is welcome. > hi, to be honest i find it a bit confusing... i did not really look into ReST's syntax yet but i assumed it partly as a wiki style "markup" alternative and thought it was (also) meant as that (apart from surely more py stuff). maybe it is just me or that i am no native english speaker but i did not really understand the syntax on the sheet or what some things are for. an example would be the 2nd table about explicit markup, do the 2 dots ".." belong to the syntax or not? i need to look more into the docutils docs, maybe it gets clearer then. it is a good thing to have though chris From dldietmeyer at charter.net Thu Jun 24 10:20:06 2004 From: dldietmeyer at charter.net (Donald L. Dietmeyer) Date: Thu, 24 Jun 2004 09:20:06 -0500 Subject: Delphi extension Message-ID: <10dloooa4p9hade@corp.supernews.com> I was given a libxx.so that was probably written in Delphi. I need to wrap it so that I can call the functions/procedures of the library from Python. I tried the usual extension technique compiling a C file. I don't get anything meaningful back when I call, so it doesn't work, or I am missing some critical point. I have spent a good deal of time searching the net, and found one or two comments about doing the job, but no evidence that anyone has done it. I would appreciate any suggestions or advice. Don From djordan8 at houston.rr.com Wed Jun 16 19:50:25 2004 From: djordan8 at houston.rr.com (Doug Jordan) Date: Wed, 16 Jun 2004 23:50:25 GMT Subject: cannot pass a variable from a function References: <87smcvuma1.fsf@strauser.com> Message-ID: <515Ac.529$M96.246@fe2.texas.rr.com> Kirk, Thanks for your input, hoever that is not exactly what I am trying to do. I understand that q is local scope. I was trying to return q and make a call to the function using another variable with global scope. In other language subroutine foo(b,c) c=b*1000 return call foo(q,r) where q and r are defines and same type as b,c as function How do I do this in python. I need to perform operations on a variable and pass the new variable to the program. Hope this might clear it up. Doug "Kirk Strauser" wrote in message news:87smcvuma1.fsf at strauser.com... -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-06-16T22:46:42Z, "Doug Jordan" writes: > #function suppose to return variable > def fctn2(c): > for h in c: > q=h*80 > return q > > def prntfctn(y): > for j in y: > print j > > fctn2(list) > prntfctn(q) The name "q" only exists inside the scope of the fctn2 variable. If you want it present inside the global scope, assign it there: q = fctn2(list) prtnfctn(q) That should do what you want. Note that I'm unaware of any modern programming language that would allow a function to assign a value to a global variable without explicitly requesting it. If such a thing exists, then I highly recommend you avoid it at all costs. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFA0NS95sRg+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkEmA8BDSEgCaAgcp u44PX2uPlSMGYAV4VG5jaC8= =G3qn -----END PGP SIGNATURE----- From lbates at swamisoft.com Wed Jun 2 16:52:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 2 Jun 2004 15:52:37 -0500 Subject: Could python help to create hundreds of NT accounts ? References: Message-ID: I needed to do something like this but with a little twist. Client wanted to put user information in a database and have servers add users to the domain on the fly. I wrote an NT service that: 1) Wakes up, scans database for new or changed users 2) Adds new users, removes deleted users, disables users that are marked as disabled 3) Changes rights, password, etc. for changed users 4) Put some information in comment field that is used by an application on the server. 5) Updates WTS information for this user to have a default program run upon login. 6) Goes back to sleep. I installed this on several servers and when I add user to DB it appears in a few minutes on all servers. Seems to work fine. I used Mark Hammond's Python Programming on Win32 quite extensively, but it took several weeks to track everything I needed down. If you are interested, we could discuss a short term consulting agreement to address your specific problem. FYI, Larry "google account" wrote in message news:e84f5d12.0406011439.57ec785f at posting.google.com... > Not really being a programmer, but thinking that there must be a > better way than to do it by hand and havign a friend who likes to tell > me that python is the answer to everything I am hoping. > > I have two NT4 domains, and I need to create instances of all the > account names from one in the other. > > All accounts need to have identical group memberships to each other, > and different passwords. > > I have in mind some program that will automatically generate a > password (I already wrote one of those) and write out to a csv file > username,passwd thgat we can refer to when the clients need to log > into their new account. > > Because there are about 1600 accounts, I'd really love it if there > was a way to do this with a script. > > I bought the Dietel How to Program Python book in an attempt to learn > this language, but it doesn't seem to have much in it related to NT > stuff like this. > > IF anyone has done anything like this, or knows how, I'd love to > hear from you. > > Cha! > > nemir (at) hot mail dot com From miki.tebeka at zoran.com Mon Jun 21 08:43:55 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 21 Jun 2004 14:43:55 +0200 Subject: wxPython on GTK In-Reply-To: References: Message-ID: <20040621124354.GH876@zoran.com> Hello Batista,, > I'm still deciding about using Tkinter or wxPython for a project I have > (sigefi, on SF). > > The decision is not made, I have to finish first a little program that will > be done in both GUIs, and then make a choice (I'll write something about the > experiment, I'll let you know). IMO wxPython is better when dealing with large projects. For small ones Tkinter will probebly be better. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From emes at spamerom.wiatr.w.oczy.i.noz.w.plecy Thu Jun 3 14:15:17 2004 From: emes at spamerom.wiatr.w.oczy.i.noz.w.plecy (emes) Date: Thu, 3 Jun 2004 18:15:17 +0000 (UTC) Subject: gtk.TextView and insert_at_cursor - why doesn't it work? Message-ID: hi all, i'm developing an application in gtk (+glade). i have to intercept any modification of gtk.TextView widget contents. using glade, i connected following signals to callback method: insert_at_cursor delete_from_cursor paste_clipboard last two work well. after c+p or pressing backspace, my callback is executed. but the first one doesn't. simple key press and character input don't invoke my callback. why? also, pasting with context_menu->paste activates callback but middle-click paste doesn't. -- michal salaban -|- emes (na) pld-linux.org -|- jabber: emes at jabber.org From mrjean1 at comcast.net Fri Jun 18 19:41:28 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Fri, 18 Jun 2004 23:41:28 GMT Subject: Saving search results in a dictionary - why is pyparsing better than regexp? References: Message-ID: <180620041652224569%mrjean1@comcast.net> If you need a fast parser in Python, try SimpleParse (mxTextTools). We use it to parse and process large log files, 100+MB in size. An example, the run time for the parsing step alone with a simple but non-trivial grammar is comparable to grep. Total run time is dominated by the processing step and increased formore complex grammars, obviously. /Jean Brouwers ProphICy Semiconductor, Inc. In article , Paul McGuire wrote: > "Lukas Holcik" wrote in message > news:Pine.LNX.4.60.0406181448190.19022 at nymfe30.fi.muni.cz... > > Hi Paul and thanks for reply, > > > > Why is the pyparsing module better than re? Just a question I must ask > > before I can use it. Meant with no offense. I found an extra pdf howto on > > python.org about regexps and found out, that there is an object called > > finditer, which could accomplish this task quite easily: > > > > regexp = re.compile(".*?)\">(?P.*?)", > \ > > re.I) > > iterator = regexp.finditer(text) > > for match in iterator: > > dict[match.group("pcdata")] = match.group("href") > > > > ---------------------------------------_.)-- > > | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* > > ----------------------------------------''-- > > > > > Lukas - > > A reasonable question, no offense taken. :) > > Well, I'm not sure I'd say pyparsing was "better" than re - maybe "easier" > or "easier to read" or "easier to maintain" or "easier for those who don't > do regexp's frequently enough to have all the re symbols memorized". And > I'd be the first to admit that pyparsing is slow at runtime. I would also > tell you that I am far from being a regexp expert, having had to delve into > them only 3 or 4 times in the past 10 years (and consequently re-learn them > each time). > > On the other hand, pyparsing does do some things to simplify your life. For > instance, there are a number of valid HTML anchors that the re you listed > above would miss. First of all, whitespace has a funny way of cropping up > in unexpected places, such as between 'href' and '=', or between '=' and the > leading ", or in the closing /a tag as "< /a >". What often starts out as a > fairly clean-looking regexp such as you posted quickly becomes mangled with > markers for optional whitespace. (Although I guess there *is* a magic > re tag to indicate that whitespace between tokens may or may not be > there...) > > Comments are another element that can confound well-intentioned regexp > efforts. The pyparsing example that I gave earlier did not handle HTML > comments, but to do so, you would define an HTML comment element, and > then add the statement: > link.ignore( htmlComment ) > (pyparsing includes a comment definition for C-style block comments of > the /* */ variety - maybe adding an HTML comment definition would be > useful?) What would the above regexp look like to handle embedded HTML > comments? > > In the sample I posted earlier, extracting URL refs from www.yahoo.com, a > number of href's were *not* inside quoted strings - how quickly could the > above regexp be modified to handle this? > > Doesn't the .* only match non-white characters? Does the above regexp > handle hrefs that are quoted strings with embedded spaces? What about > pcdata with embedded spaces? (Sorry if my re ignorance is showing here.) > > Lastly, pyparsing does handle some problems that regexp's can't, most > notable those that have some recursive definition, such as algebraic infix > notation, or EBNF. Working samples of both of these are included in the > sample that come with pyparsing. (There are other parsers out there other > than pyparsing, too, that can do this same job.) > > pyparsing's runtime performance is pretty slow, positively glacial compared > to compiled regexp's or string splits. I've warned away some potential > pyparsing users who had *very*clean input data (no hand-edited input text, > very stable and simple input format) that used string split() to run 50X > faster than pyparsing. This was a good exercise for me, I used the hotshot > profiler to remove 30-40% of the runtime, but I was still far shy of the > much-speedier string splitting algorithm. But again, this application had > *very* clean input data, with a straightforward format. He also had a very > demanding runtime performance criterion, having to read and process about > 50,000 data records at startup - string.split() took about 0.08 seconds, > pyparsing took about 5 seconds. My recommendation was to *not* use > pyparsing in this case. > > On the other hand, for simple one-off's, or for functions that are not time- > critical parts of a program, or if it doesn't matter if the program takes 10 > minutes to write and 30 seconds to run (with say, pyparsing) vs. 15 minutes > to write and 0.5 seconds to run (with say, regexp's), I'd say pyparsing was > a good choice. And when you find you need to add or extend a given > parsing construct, it is usually a very straightforward process with > pyparsing. > > I've had a number of e-mails telling me how pleasant and intuitive it is to > work with pyparsing, in some ways reminiscent of the "I like coding in > Python, even if it is slower than C at runtime" comments we read in c.l.py > every week (along with many expositions on how raw runtime performance > is not always the best indicator of what solution is the "best"). > > Just as David Mertz describes in his Text Processing with Python book, > each of these are just one of many tools in our toolkits. Don't get more > complicated in your solution than you need to be. The person who, in 6 > months, needs to try to figure out just how the heck your code works, > just might be you. > > Sorry for the length of response, hope some of you are still awake... > > -- Paul > > > > From nelson at monkey.org Sat Jun 19 11:38:16 2004 From: nelson at monkey.org (Nelson Minar) Date: Sat, 19 Jun 2004 15:38:16 GMT Subject: Attention, hyperlinkers: inference of active text References: <10d6bln988rmne6@corp.supernews.com> Message-ID: If I understand your question correctly, you're looking for a way to guess what part of an English sentence is a URL. The problem you're facing is trailing punctuation characters. Ie, these are good: Look at http://bamboo.org ! It is on my drive as file:\Program%20Files\Perl\odysseus.exe And these are bad: Look at http://bamboo.org! The secret is in "file:\My Download Folder\dont_look.txt". If you want to make life as easy as possible for your authors, you need some good heuristics. You need to guess where the URL starts and ends. My terminal emulator (SecureCRT) does a pretty good job of this. Nat Friedman's dingus also did this trick awhile ago - I can't find it easily now, but I think the code might be part of rxvt or Gnome. Your other option is to require folks to delimit URLs with something like . This is pretty painless and common, but only you can know whether your users will accept it. From miki.tebeka at zoran.com Sun Jun 20 04:29:17 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 20 Jun 2004 10:29:17 +0200 Subject: [python] using try: finally: except In-Reply-To: References: Message-ID: <20040620082917.GB308@zoran.com> Hello David, > In referring to my copy of the python bible, it tells me I can't use all > three items 'try' except and finally. I can use the t/f or t/e > combinations though > > What combination can i use if i want to catch the exception and still have > a finally block? try: try: do_something() except Exception, e: print "bummer" finally: print "at last" Google this list for why you can't have try/except/finally together. HTH. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From me at privacy.net Mon Jun 21 16:21:48 2004 From: me at privacy.net (Heather Coppersmith) Date: 21 Jun 2004 16:21:48 -0400 Subject: Catching errors in attribute names at assigment References: Message-ID: On Mon, 21 Jun 2004 22:01:31 +0200, Pawel Kraszewski wrote: > If you say __all__=["a","b","c"], those 3 attributes are the > only ones valid for field/method accessing. So class.a=5 is ok, > but class.d=5 raises exception. ITYM __slots__ instead of __all__. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From tim.one at comcast.net Sun Jun 13 13:22:28 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 13:22:28 -0400 Subject: Limits on number of classes? In-Reply-To: <889cbba0.0406130859.7e2fc2da@posting.google.com> Message-ID: [Kamilche] > My design reqires hundreds of classes, maybe over a thousand. Can Python > handle that? Sure. > Will there be a speed hit? Compared to what? The only part of Python that takes time proportional to the number of classes is the time it takes for cyclic garbage collection to stare at the classes from time to time, and determine that they're not yet trash. That's not unique to class objects, though, that's an expense accruing to every kind of container (classes, instances, lists, tuples, ...). If your inheritance chain is a thousand levels deep, then (a) it's going to take a long time to resolve a method defined in the base class when accessed from an instance of the most-derived class; and, (b) you're insane . > Just wondering if anyone had hit the limits of Python. The number of class objects is limited by your virtual memory (each class object consumes memory, of course). Base Zope contains about 2,500 Python classes, and Zope3 about 4,500 so far. The only problem that causes is confusion at times. For example, there are 12 distinct classes named "B" in Zope3 so far. Most are throwaways in tests. When you're staring at a test using class B, it's sometimes far from obvious exactly which of the dozen B classes it thinks it's using. From peter.maas at mplusr.de Wed Jun 2 06:00:57 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 02 Jun 2004 12:00:57 +0200 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: <69cbbef2.0406010619.7cd39e71@posting.google.com> References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: has schrieb: > Announcing the final v1 release of HTMLTemplate; best damn HTML > templating system evar, or yer money back. Enjoy! :) Good work BUT there are some other Python templating frameworks around, e.g. - Cheetah - ZOPE's TAL - about half a dozen TAL derivatives - Quixote's PTL - SkunkWeb's STML - Yaptu - XYaptu - Template Macro Did you find these alternatives unsatisfactory? If somebody wants to use a Python templating framework why should he prefer HTMLTemplate? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From tim.peters at gmail.com Tue Jun 15 21:03:16 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 15 Jun 2004 21:03:16 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE019639F5@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE019639F5@au3010avexu1.global.avaya.com> Message-ID: <1f7befae040615180375069489@mail.gmail.com> [Delaney, Timothy C (Timothy)] ... > Tim Peters is one of the primary developers *of* Python. We're very > lucky that he happens to really like questions involving numeric stuff, > and goes out of his way to answer them Indeed you are . The truth is more depressing, though: I have so little time to answer questions now, except on some weekends, that I generally stick to questions only I *can* answer. For example, I used to answer all questions about Python dicts, but more than a few people are intimately familiar with that code now, so now I usually leave dict questions alone. But very few people are (or ever were) intimately familiar with Python's arithmetic code, so I still try to field questions about that. [Claudio Grondi] > Now knowing you [Tim Peters] as a Python and programming > expert, may I ask you even for more support by providing a > reply to my other posting to this newsgroup: > "Python Scripting in Windows MSIE 6.0"? I don't know anything about it -- but I'd reply if I was the only one who did, and if it were a weekend . From pelcogirltemp at yahoo.com Thu Jun 17 14:58:30 2004 From: pelcogirltemp at yahoo.com (Cheryl Untalan) Date: Thu, 17 Jun 2004 11:58:30 -0700 (PDT) Subject: python23_d.lib Message-ID: <20040617185830.70240.qmail@web21406.mail.yahoo.com> I?m new to Python and SWIG. How would I go about obtaining the Python source and making a debug build? Do I also need to set something within the environment? I am using XP, Visual Studio .NET, Python 2.3.3, and SWIG 1.3.21. ------------------------------------------------ Thomas Heller theller at python.net Fri Jun 11 13:46:16 EDT 2004 ? Previous message: python23_d.lib ? Next message: python23_d.lib ? Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] ________________________________________ "Shankar KN" <123 at 456.com> writes: > Hi, > > I am trying to get a hand on python23_d.lib but in vain. > I am developing a C++ dll which has a SWIG interface to the Python world. > After installing Python and SWIG I am able to build this DLL in Release mode > but not in Debug mode because of non-availability of python23_d.lib. > > Any clues as to how I could proceed with Debug build? Get the Python sources and make a debug build. Thomas __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From BrendanSimon at fastmail.fm Tue Jun 15 07:52:21 2004 From: BrendanSimon at fastmail.fm (Brendan J Simon) Date: Tue, 15 Jun 2004 21:52:21 +1000 Subject: python with Java API Message-ID: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Hi, I have a Java application from a company. They also provide an API in C++ (MSW platforms only) and Java (for all platforms) for developers that want to create their own front end. I want to use wxPython to create a decent Unix opensource frontend. Is it possible to Interface python to a java application easily ??? Assuming yes to above, would something like Jython or SWIG or some other tool be required. Any advice or pointers would be greatly appreciated. Regards, Brendan Simon. From indigo at bitglue.com Sat Jun 12 01:09:14 2004 From: indigo at bitglue.com (Phil Frost) Date: Sat, 12 Jun 2004 01:09:14 -0400 Subject: fast list search? In-Reply-To: <40CA7329.2050302@lbl.gov> References: <%Cryc.14374$kn2.241788@news.ono.com> <40CA7329.2050302@lbl.gov> Message-ID: <20040612050914.GA3999@unununium.org> Perhaps the standard 'sets' module would be of use? It's implemented with dictionaries, and seems to do the thing that is needed. On Fri, Jun 11, 2004 at 08:06:17PM -0700, Dan Gunter wrote: > How about using a dictionary, with the keys being the ints and the > values being the index in the 'list', i.e. len(dictionary). This is > quite fast: > > >>> d = {} > >>> for i in xrange(0,500000): > ... if not d.has_key(i): d[i] = len(d) > > -Dan > > Javier Zaragoz? Arenas wrote: > >I think the better way is sort before the list > > > > > >>>thelist.sort() > > > > > >And then, a binary search > > > > > >>>point_of_insertion = bisect.bisect(thelist, item) > >>>is_present = thelist[point_of_insertion -1:point_of_insertion] == [item] > > > > >> if not is_present: > >.... thelist.insert(point_of_insertion, item) > > > >and done! > > > >Fco Javier Zaragoz? Arenas > > > > > > > >"ramon aragues" escribi? en el mensaje > >news:mailman.747.1086774432.6949.python-list at python.org... > > > >>Hi, > >> > >>I?ve got a list with more than 500,000 ints. Before inserting new ints, > >>I have to check that it doesn?t exist already in the list. > >> > >>Currently, I am doing the standard: > >> > >>if new_int not in long_list: > >>long_list.append(new_int) > >> > >> > >>but it is extremely slow... is there a faster way of doing this in python? > >> > >>Thanks a lot, > >> > >>Ramon Aragues From tor.iver.wilhelmsen at broadpark.no Sun Jun 6 05:27:17 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 06 Jun 2004 11:27:17 +0200 Subject: if does not evaluate References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: Matteo Dell'Amico writes: > So, even if this a little "perlish" :-), I think it will continue to > work in future versions of python, since otherwise it would break too > much existing code. Yes, and at least one would hope it would work anyway with a cast, that is "int(something)". From dcsmpayne at bigpond.com Sun Jun 13 05:41:06 2004 From: dcsmpayne at bigpond.com (news) Date: Sun, 13 Jun 2004 09:41:06 GMT Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: You could consider using boa constructor or PythonCard. However, I fear you will be disappointed ... there is just nothing (in any language) which comes close to the GUI IDE of VB. Boa probably comes closest ... but it is one heck of a steep learning curve. BTW. I am also a high school teacher and previously taught VB until more recent years when I have been encouraging students to enter programming competitions. The feedback from comps continues to be "those who use VB continue to under perform" ... most likely because VB allows one to focus so much on the gui rather than the problem / logic. ANyway, last year I had a very close minded group who wanted C++ at any cost. I refused and compromised by teaching them Java. I have not been happy with this move mostly because in NSW (Australia) we have a very restrictive syllabus which focuses on "structured programming". Hence (IMO) students are disadvantaged if they do anything other than VB. Similarly, this syllabus does not extend to cover OOP, design patterns and the like, so I would be shooting myself in the foot if I attempted to cover these things. Java does allow programming in the imperative (structured) style but is oh so bloody *&^%$ ... students need to use it in an OO way to realise the true strength and value of the language. This year I am starting earlier (yr7) and introducing the students to Python. To capture their imagination I am creating a unit on programming Python games. Eventually I am aiming to be able to utilise the pygame modules. Now I know it is going to take some time (more than I have with the students this year), but it something different for them and I may attract greater numbers in two years time when we will have the time to develop this area. If I had the money I would buy a class set of Michael Dawson's - Python Programming for the absolute beginner. Premier Press. As far as an IDE goes I am going to stick with IDLE, build a reasonable knowledge and skill base, then attack wxpython and / or tkinter before moving on to pygame. regards Darren Payne Hurlstone Agricultural High School From chrisks at NOSPAMudel.edu Sat Jun 12 17:49:29 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 12 Jun 2004 17:49:29 -0400 Subject: does python supported in WinCE/ProcketPC? In-Reply-To: <6f922c86.0406120643.140822f@posting.google.com> References: <6f922c86.0406120643.140822f@posting.google.com> Message-ID: chanmy8 wrote: > does python supported in WinCE/ProcketPC? Yes. See http://python.org/download/download_windows.html From paul.bissex at gmail.com Sat Jun 26 20:04:27 2004 From: paul.bissex at gmail.com (Paul Bissex) Date: Sat, 26 Jun 2004 20:04:27 -0400 Subject: How to trim n characters from right end of a string? In-Reply-To: References: Message-ID: <10015231040626170457c2710b@mail.gmail.com> On Sat, 26 Jun 2004 23:45:42 GMT, Robert wrote: > > Please tell this newbie how to remove n characters from the right end of a > string. What Tony said, plus this: >>> s = "chopme" >>> n = 2 >>> s = s[:-n] >>> print s chop -- paul bissex, e-scribe.com -- database-driven web development 413.585.8095 69.55.225.29 01061-0847 72?39'71"W 42?19'42"N From me at privacy.net Wed Jun 23 08:26:08 2004 From: me at privacy.net (Duncan Booth) Date: 23 Jun 2004 12:26:08 GMT Subject: Using metaclasses to play with decorators. References: Message-ID: "Colin J. Williams" wrote in news:uRdCc.27945$Nz.1231193 at news20.bellglobal.com: > OK, I'll ignore 'staticmethod', but could you tell me how > > def methodA(x, y) [noself]: > return x + y > > differs in substance from > > def methodA(self, y): > return self + y > > or > def methodA(x, y): > return x + y > > What has been gained by the added syntactic clutter? Does this help? class X: def methodA(x, y) [ staticmethod ]: return x+y def methodB(self,y): return self+y def methodC(x,y): return x+y anX = X() anX.methodA(2, 3) # returns 5 anX.methodB(2, 3) # Exception: too many arguments anX.methodC(2, 3) # Exception: too many arguments X.methodA(2, 3) # returns 5 X.methodB(2, 3) # Exception: First argument must be an instance of X X.methodC(2, 3) # Exception: First argument must be an instance of X From imbosol at aerojockey.invalid Fri Jun 18 23:28:12 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 19 Jun 2004 03:28:12 GMT Subject: [python] using try: finally: except References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> Message-ID: Peter Hansen wrote: > OKB (not okblacke) wrote: > >> Carl Banks wrote: >> >>>The right way is: >>> >>> try: >>> try: >>> x = 'hello' >>> except: >>> print "oops" >>> finally: >>> y = 'world' >>> print x," ",y >> >> I seem to recall reading somewhere that this was a cop-out for some >> implementation reason. Is there any word on when or if it's going to be >> remedied? It seems unbearably ugly and unintuitive; one of the most >> irritating Python warts. > > I recall differently. I recall reading several times that since > it is completely ambiguous what the programmer meant if both are > specified together, Guido deliberately kept them separate so that > one had to be very explicit about whether the finally was inside > or outside the except. The behaviour of the code is quite different > depending on the order... try...except and try...finally are really two completely different statements with different purposes. It's very unfortunate that try is used for both of them. Frankly, when you do a try...finally, you're not really trying. In the words of the Jedi Master: "Try not. Do, or do not. There is no try." Which is why I think it should rather be do...finally. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From claird at lairds.com Thu Jun 3 09:19:34 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 13:19:34 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 2) References: <10bsm3r1h275cd7@corp.supernews.com> <95aa1afa.0406030318.4d8b92f6@posting.google.com> Message-ID: <10bu9b6e2o81de1@corp.supernews.com> In article <95aa1afa.0406030318.4d8b92f6 at posting.google.com>, Michele Simionato wrote: >"Cameron Laird" wrote in message >news:<10bsm3r1h275cd7 at corp.supernews.com>... >> Michele Simionato illustrates Python's itertool-related chop(), >> a far different thing than Perl's standard library member >> http://mail.python.org/pipermail/python-list/2004-May/222673.html > >FWIW, I didn't know Perl had a 'chop'. I took the name from Chicken, a >Scheme implementation I like a lot. > > Michele Simionato I want to make clear that I wasn't criticizing. While I didn't know about Chicken, I've come across "chop" before in the sense of "segment a sequence"; I thought it was entirely legitimate. HOWEVER, a lot of Pythoneers and especially Python newcomers are familiar with Perl, and I thought it important to make *that* distinction explicit. -- Cameron Laird Business: http://www.Phaseit.net From kirk at strauser.com Wed Jun 16 19:20:05 2004 From: kirk at strauser.com (Kirk Strauser) Date: Wed, 16 Jun 2004 23:20:05 GMT Subject: cannot pass a variable from a function References: Message-ID: <87smcvuma1.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-06-16T22:46:42Z, "Doug Jordan" writes: > #function suppose to return variable > def fctn2(c): > for h in c: > q=h*80 > return q > > def prntfctn(y): > for j in y: > print j > > fctn2(list) > prntfctn(q) The name "q" only exists inside the scope of the fctn2 variable. If you want it present inside the global scope, assign it there: q = fctn2(list) prtnfctn(q) That should do what you want. Note that I'm unaware of any modern programming language that would allow a function to assign a value to a global variable without explicitly requesting it. If such a thing exists, then I highly recommend you avoid it at all costs. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFA0NS95sRg+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkEmA8BDSEgCaAgcp u44PX2uPlSMGYAV4VG5jaC8= =G3qn -----END PGP SIGNATURE----- From vng1 at mac.com Mon Jun 28 00:44:47 2004 From: vng1 at mac.com (Victor Ng) Date: Mon, 28 Jun 2004 00:44:47 -0400 Subject: Learning Pyrex with libxml2 In-Reply-To: <5a2ed384.0406230341.71efe67e@posting.google.com> References: <5a2ed384.0406230341.71efe67e@posting.google.com> Message-ID: <2k9m20F18uq7kU1@uni-berlin.de> There's a good example of how to use Pyrex with C code that uses struct extensively in the Pyxpat sample at: http://www.prescod.net/python/pyrexopt/pyxpat/pyxpat.pyx There's also a discussion about a similar problem the Pyrex info mailing list at: http://lists.copyleft.no/pipermail/pyrex/2004-January/thread.html#478 Hmmm... answering my own questions on c.l.p again. This is probably a bad sign of something, although I'm not quite sure. vic Victor Ng wrote: > Hi, I'm trying to learn how to use Pyrex by converting some of the > libxml2 examples. I'm not having much luck - I can create a document, > but any attempt to create nodes causes a segfault. > > The code I'm trying to port is io2.c (http://xmlsoft.org/examples/io2.c) > > I've commented the couple lines that cause a problem for me. > > thanks, > vic From qrczak at knm.org.pl Tue Jun 22 05:56:50 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 22 Jun 2004 11:56:50 +0200 Subject: useless destructors References: Message-ID: On Tue, 22 Jun 2004 02:36:24 -0700, David Turner wrote: > Further to the discussion from earlier titled "does python have > useless destructors?", I've posted a brief summary of garbage > collection, RAII, and the "using" clause (which is what PEP310's > "with" clause amounts to). The post is here: > > http://dkturner.blogspot.com/2004/06/garbage-collection-raii-and-using.html You left "for later" a point which makes the last proposition unworkable: how to implement selective refcounting in a dynamically typed language? Will it still work if the refcounted object is referred to from a plain object? The only way I can imagine is to manage refcounts on each object passing, returning and rebinding. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From cronje_med at yahoo.com Sat Jun 19 09:32:17 2004 From: cronje_med at yahoo.com (cronje_med) Date: Sat, 19 Jun 2004 13:32:17 -0000 Subject: Newbie Help Message-ID: Ok, so I'm a bit new at this, so please don't make fun of me too much. I was trying to make a math function that wouldn't pull a NameError if I didn't enter a number or variable containing a number. Here's what I have: def math(num): if num.isdigit() == 1: print "Is a number!" return num else: print "Is not a number!" return num >>> math(5+5) AttributeError: 'int' object has no attribute 'isdigit' >>> math("5+5") Is not a number! '5+5' >>> math("5+x") Is not a number! '5+x' Any help anyone can provide would be great. Thank you. From dmq at gain.com Wed Jun 23 22:49:21 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 23 Jun 2004 19:49:21 -0700 Subject: Bug in __del__ function References: <217kd05a0ohtfqepgm2i2lvm7616lga918@4ax.com> Message-ID: On 23 Jun 2004 21:22:59 -0400, Heather Coppersmith wrote: >On Wed, 23 Jun 2004 18:07:50 -0700, >David MacQuigg wrote: > >> The example below is a repeatable test case. It might be possible to >> simplify this further, but at this point, I haven't a clue as to why >> it works with some sequences of commands, but not others. > >> I'm also not able to repeat the problem by putting the commands in the >> file, and just running the file. Adding the necessary 'print' >> keywords makes the problem go away. This could be just a problem in >> IDLE, but unless I'm sure of that, I don't want to be using __del__ in >> my programs. > >> Is this a bug, or have I misunderstood the use of __del__? > >[ code / interaction mostly snipped ] > >>>>> del cat1 >>>>> cat2 >> <__main__.Cat object at 0x00A11F70> >>>>> rc(cat2) >> sys.getrefcount(obj): 5 ### Should be one less. > >I'm not sure about that. The interactive prompt keeps a reference to >the last thing it printed, which in this case was cat2. Perhaps IDLE >has similar behavior? That would also explain why adding extra print >statements and/or running from a file makes the problem go away. Wow. This explains everything. The erratic behavior is all dependent on what the interpreter sees as the current _ (underscore) reference. Simply printing a value changes that reference and frees the deleted object. >>> del cat2 ### nothing happens, because _ still references the object. >>> _ <__main__.Cat object at 0x00A11F70> >>> 2 ### changes _ and immediately frees the object. Deleting instance: <__main__.Cat object at 0x00A11F70> Cat:0 Mammal:0 Animal:0 2 ### The deletion apparently occurs before the command finishes. >>> This will make a good example for the "Gotcha" section in my OOP chapter. Thanks for your help. -- Dave From skip at pobox.com Mon Jun 28 23:02:23 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jun 2004 22:02:23 -0500 Subject: file compression In-Reply-To: References: Message-ID: <16608.56255.446839.16511@montanaro.dyndns.org> Elaine> The files I'm working with are python modules and LaTeX source Elaine> files, and I need to make them into archives so I can store them Elaine> in my website. Check out the zipfile module and class: % pydoc zipfile ... class ZipFile | Class with methods to open, read, write, close, list zip files. | | z = ZipFile(file, mode="r", compression=ZIP_STORED) | | file: Either the path to the file, or a file-like object. | If it is a path, the file will be opened and closed by ZipFile. | mode: The mode can be either read "r", write "w" or append "a". | compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib) ... Skip From tim.one at comcast.net Thu Jun 10 21:09:49 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jun 2004 21:09:49 -0400 Subject: reference counting and PyTuple_SetItem In-Reply-To: <40C8AC0F.9010503@unidata.ucar.edu> Message-ID: [Anne Wilson] ... > Now I'm testing this: > > > while() { > pyFiveMinArgs = PyTuple_New(PY_CALL_ARG_CNT); > PyTuple_SetItem(pyFiveMinArgs, 0, PyInt_FromLong(300L)); > PyTuple_SetItem(pyFiveMinArgs, 1, PyInt_FromLong(1L)); > PyTuple_SetItem(pyFiveMinArgs, 2, PyString_FromString("5min")); > PyTuple_SetItem(pyFiveMinArgs, 3, PyString_FromString(statsDir)); > PyTuple_SetItem(pyFiveMinArgs, 4, PyString_FromString(rHost)); > > pyOneHourArgs = PyTuple_New(PY_CALL_ARG_CNT); > PyTuple_SetItem(pyOneHourArgs, 0, PyInt_FromLong(3600L)); > PyTuple_SetItem(pyOneHourArgs, 1, PyInt_FromLong(15L)); > PyTuple_SetItem(pyOneHourArgs, 2, PyString_FromString("1hr")); > PyTuple_SetItem(pyOneHourArgs, 3, PyString_FromString(statsDir)); > PyTuple_SetItem(pyOneHourArgs, 4, PyString_FromString(rHost)); > ... > > pyValue = PyObject_CallObject(pyFunc, pyFiveMinArgs); > Py_DECREF(pyValue); > pyValue = PyObject_CallObject(pyFunc, pyOneHourArgs); > Py_DECREF(pyValue); > > ... > Py_DECREF(pyFiveMinArgs); > Py_DECREF(pyOneHourArgs); > } > > > But, OW! It pains me to be so inefficient, creating the same damn > PyObjects over and over and over and over and over again. OTOH, it's so clear as to be darned-near obvious now -- even though it's still wrong To me this is way beyond "micro" optimization. In my own code I'm > actually doing this for three more cases beyond the fiveMin and oneHour > stuff shown above. Does it matter? That is, have you profiled the code and determined that this part is a bottleneck? If not, optimization will introduce bugs and waste *your* time (not to mention mine ). > Is there a more efficient way to do this embedded call? Ignoring error-checking, most people would float the argument construction outside the loop (faster), and use a higher-level API function to do the calls (slower); e.g., i1 = PyInt_FromLong(1); i15 = PyInt_FromLong(15); i300 = PyInt_FromLong(300); i3600 = PyInt_FromLong(3600); statsdir = PyString_FromString(statsDir); srhost = PyString_FromString(rHost); s5min = PyString_FromString("5min"); s1hr = PyString_FromString("1hr"); while() { pyValue = PyObject_CallFunction(pyFunc, "OOOOO", i300, i1, s5min, statsdir, srhost); Py_DECREF(pyValue); pyValue = PyObject_CallFunction(pyFunc, , "OOOOO", i3600, i15, s1hr, statsdir, srhost); Py_DECREF(pyValue); } Py_DECREF(i1); Py_DECREF(i15); [etc] > (... other than rewriting the Python code in C...) Can I use a list > instead of tuple? Not unless pyFunc takes a list as an argument. You would have exactly the same refcount woes: it's not tuples that cause those, it's trying to optimize low-level operations with flawed understanding of how they work. "Do the simplest thing that could possibly work" is good advice here. Write tests (preferably before coding) to ensure that things continue to work. If timing shows the code is truly too slow, and profiling shows that this part is truly the bottleneck, then it *may* be good to trade off maintainability for speed. But what you're doing in the C loop here is almost certainly insignificantly expensive compared to the overhead of calling back into Python at all. Indeed, I'd seriously question why this part is coded in C at all -- it's buying you bugs, but I'm not sure it's buying you anything worth having. From grey at despair.dmiyu.org Sun Jun 27 15:03:01 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sun, 27 Jun 2004 19:03:01 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On 2004-06-26, Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. Main editor, vim. Small, fast, awesome syntax highlighting, doesn't get in my way. Secondary, boa-constructor. Builds wxPython code cleanly. I'll build the base of the app in boa and then move to vim for the non-interface portions. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From mwh at python.net Tue Jun 29 14:15:05 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 29 Jun 2004 18:15:05 GMT Subject: Watershed Python Versions References: <40dd3107.0406191120.6879a1c6@posting.google.com> Message-ID: tedlandis at rogers.com (Ted) writes: > I would like to collect opinions on which versions of Python should be > considered watershed versions. By this I mean versions which are > stable and contain significant landmark features. As others have said, all versions are pretty stable. 2.2 was a landmark release. At all times, I would contend that the best release to start a new project with is the most recent (so, now, 2.3.4). Cheers, mwh -- The Internet is full. Go away. -- http://www.disobey.com/devilshat/ds011101.htm From daniel at linuxuser.co.uk Fri Jun 25 15:02:06 2004 From: daniel at linuxuser.co.uk (daniel at linuxuser.co.uk) Date: Sat, 26 Jun 2004 00:32:06 +0530 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 +++ Attachment: No Virus found +++ Panda AntiVirus - www.pandasoftware.com -------------- next part -------------- A non-text attachment was scrubbed... Name: id09509.pif Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From peufeu at free.fr Fri Jun 18 03:20:07 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 09:20:07 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: > I'm new to python. To my eyes this is a pretty poor attempt to > have static variables. I've implemented in the past a few static variables in python def accumulate( x ): accumulate.accumulator += x return accumulate.accumulator accumulate.accumulator = 0 From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Thu Jun 24 12:37:34 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Thu, 24 Jun 2004 18:37:34 +0200 Subject: Python COM - limit on size/complexity of returned object? References: <51f8958a.0406240327.1b26a76f@posting.google.com> Message-ID: Hi ! Only for size (because I don't understand correctly english). I had a COM-server, in Python. And I send/read string of 5-10MB size, without pb (perhaps time had few seconds in excess). @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B sites : http://mclaveau.com http://bergoiata.org http://ponx.org From jussij at zeusedit.com Mon Jun 14 09:38:06 2004 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Mon, 14 Jun 2004 23:38:06 +1000 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> <6ee58e07.0406131343.7d68af87@posting.google.com> Message-ID: <40CDAA3E.40AE@zeusedit.com> Lothar Scholz wrote: >> What I consider critical, are a popdown listing of all my functions, >> colored syntax printing, and a right-click 'definition' context menu >> that will hop you to the spot where that keyword is defined > > The problem is that you need more then file level scope for this. For > example the information about all projects and runtime files must be > keept in memory. Zeus for Windows can do this: http://www.zeusedit.com/lookmain.html If you create a Zeus project/workspace, add your source files to the workspace, the editor automatically manages the creation and update of the ctags information. This information is then used for code-completion, intellisensing and keyword searching. Jussi Jumppanen Author of: Zeus for Windows (All new version 3.92 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From jacek.generowicz at cern.ch Mon Jun 21 08:30:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 21 Jun 2004 14:30:43 +0200 Subject: Collecting Python's responses. Message-ID: I'm looking for ways of creating annotated records of Python interactive sessions, for documentation purposes. For example, something like # dir shows the contents of the namespace >>> dir() ['__builtins__', '__doc__', '__name__'] # Addition works too >>> 1+2 3 However, I would like to automate the incorporation of Python's actual output, so I would like to run a program which looks something like this: session(text('dir shows the contents of the namespace'), code('dir()'), text('Addition works too'), code('1+2')) which would somehow send the code to a Python process, collect the response, and interleave the two with the annotation text to create HTML output, or commented Python source code (or some other format for which I provide a back end). Does anything like this exitst? If not, any suggestions how best to go about it. (The popen family seems unsuitable because of buffering deadlocks, I'd rather not use telnetlib ...) From donn at u.washington.edu Thu Jun 10 12:35:28 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 10 Jun 2004 09:35:28 -0700 Subject: Passing file descriptors References: Message-ID: In article , Josiah Carlson wrote: [... evidently wishing to pass a file descriptor over a local socket connection ...] > Certainly I need a two things: > 1. Unix domain socket, local socket (standard socket connected locally), > or pipe > 2. sendmsg/recvmsg, fcntl.ioctl, or equivalent file descriptor manipulation > > In the script listed at the end of this post, I use a file descriptor > pair returned by os.pipe(), which should be sufficient. I also use > fcntl.ioctl(). > > > As stated previously, this works properly on SunOS 5.8: ... > It does not work on the linux machine I'm testing it on: ... > IOError: [Errno 22] Invalid argument > Seemingly this is because I_SENDFD/I_RECVFD is not properly implemented > on linux 2.4, but maybe I'm doing something wrong. I'd say it's a fair bet that I_SENDFD is not implemented on Linux, properly or otherwise. It looks to me like an AT&T STREAMS function, as opposed to Berkeley socket. Casual look around the include files doesn't suggest any support on Linux for any STREAMS stuff. As usual, there's a parallel Berkeley way to do this, using as already mentioned a UNIX domain socket, and sendmsg, and SCM_RIGHTS. If Python's socketmodule.c doesn't directly support sendmsg and the attendant data structures, you'll have to add that in C, either in socketmodule.c or your own module. That means mainly getting the msghdr struct together (I think the control object you want to pass, with SCM_RIGHTS and the fds can be packed up in Python.) Donn Cave, donn at u.washington.edu From tjreedy at udel.edu Wed Jun 30 12:57:53 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jun 2004 12:57:53 -0400 Subject: script to download Yahoo Finance data References: <94abfadd.0406291838.53600d7b@posting.google.com> Message-ID: "dan roberts" wrote in message news:94abfadd.0406291838.53600d7b at posting.google.com... > Folks, > > This is my first Python project so please bear with me. I need to > download data from Yahoo Finance in CSV format. The symbols are > provided in a text file, and the project details are included below. > Does anyone have some sample code that I could adapt? Perhaps someone will post something. In the meanwhile, the specialized function you need is urlopen() in urllib(or possibly same function in urllib2). This does all the hard work for you. The rest is standard Python that you should learn. A start (maybe missing some function args): import urllib template = "http://ichart.yahoo.com/table.csv?s=%s&a=00&b=2&c=1962&d=05&e=30&f=2004&g= d&ignore=.csv" symlist = file('whatever').read() for sym in symlist: url = template % sym stuff = urllib.urlopen(url) Terry J. Reedy From fishboy at spamspamspam.com Wed Jun 2 11:48:51 2004 From: fishboy at spamspamspam.com (fishboy) Date: Wed, 02 Jun 2004 15:48:51 GMT Subject: memory error References: Message-ID: On Wed, 02 Jun 2004 09:11:13 -0400, Bart Nessux wrote: >def windows(): > import os > excludes = ['hiberfil.sys', 'ipnathlp.dll', 'helpctr.exe', 'etc', >'etc', 'etc'] > size_list = [] > for root, dirs, files in os.walk('/'): > total = [x for x in files if x not in excludes] > for t in total: > s = file(os.path.join(root,t)) > size = s.read() > size_list.append(size) > s.close() > >windows() Yeah, what the other guys said about os.stat and os.path.getsize. Also, if you really want to read the actual file into memory, just get small chunks and add those up. Like (untested): numberofbytes = 0 CHUNKSIZE = 4096 for root,dirs, files in os.walk('/'): for name in files: if name not in excludes: f = file(os.path.join(root,name)) while 1: s = f.read(CHUNKSIZE) if not s: f.close() break numberofbytes += len(s) this way you never have more than 4k of data in memory at once. (well it might be 8k, I dont know enought about the internals to tell you when the previous 's' is garbage collected.) ><{{{*> From pwatson at redlinepy.com Fri Jun 25 06:58:06 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 25 Jun 2004 05:58:06 -0500 Subject: question about cx_Oracle .thanks References: Message-ID: <2k2eq0F17aa0uU1@uni-berlin.de> "coolmenu" wrote in message news:a6a2957e.0406250233.402c2ddd at posting.google.com... > David Fraser wrote in message news:... > > coolmenu wrote: > > > Hi > > > i hava a db ORACLE 10G,a table valid_card > > > (card_no,varchar2(10),now_balance number (12,2)) > > > > > > its'some record in table ('7188','42055.66') > > > > > > i use cx_Oracle to select now_balance from table > > > > > > curobj.execute("select loan_amount from valid_card where > > > card_no='7181930166881974'"); > > > [] > > > > > >>>>tuple=curobj.fetchone() > > >>>>tuple > > > > > > (42505.660000000003) > > > > > > why 42505.66---->42505.6600000000003??? > > > thanks > > > > This is because of the conversion of the float to decimal. Float objects > > have limited accuracy. I don't think it's much to do with cx_Oracle > > > > David > > > Can someone give me a advice? how can i do? > donnt select number from oracle? This has nothing to do with Oracle. This is the problem of representing floating point numbers on a binary system. You may need to format the number for presentation. >>> x = 42055.66 >>> x 42055.660000000003 >>> print "the answer is %.2f" % (x) the answer is 42055.66 From peter at engcorp.com Mon Jun 7 20:47:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jun 2004 20:47:58 -0400 Subject: how to use __str__ and __repr__? In-Reply-To: <2ik9mdFnvcsbU2@uni-berlin.de> References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9mdFnvcsbU2@uni-berlin.de> Message-ID: <7P6dnaLiT8YikVjdRVn-hQ@powergate.ca> Jim Newton wrote: > i read that in the documenation. and i assumed from that that > print another() > actually prints the string returned from another().__str__() > and thus __str__ must be being inherited from the superclass > of another, but apparently print does something different. > > why does print another() actually print something rather than > complaining that there is no __str__ defined? I believe print basically calls str(obj) on the object, and str() is a builtin which (I believe) basically tries to call __str__() and if that is not defined, calls __repr__(). If __repr__ is not defined, it probably defers to a standard representation based on the id() of the object, which is always defined. Not sure what else you're trying to do (I haven't read your full post) but I believe this and some thought should answer for pretty much everything you're seeing. Note that you should probably never call __str__() directly, but call the str() builtin instead. Same for __repr__() versus the repr() builtin. -Peter From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 17 14:09:13 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 17 Jun 2004 20:09:13 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B742016357CD@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = 0gk500b4gd0888 at cougar.noc.ucla.edu Recipient(s) = python-list at python.org; Subject = *SPAM* Document Scanning time = 06/17/2004 20:09:13 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment Bill.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From listsub at wickedgrey.com Fri Jun 25 19:29:50 2004 From: listsub at wickedgrey.com (Eli Stevens (WG.c)) Date: Fri, 25 Jun 2004 16:29:50 -0700 Subject: Zero-fill shift References: <40990BC8.7000306@cs.yorku.ca> Message-ID: <24bf01c45b0c$6d0e85e0$b401010a@sparta> Daniel Orner wrote: > Great, this works. 8-) Unfortunately, I've run into another problem. > In the Java algorithm, two integers are added. This often results in > an overflow and a negative number, which is the desired result. > However, I can't seem to duplicate that in Python, as adding two > integers that are too large just results in a long (and using the > int() method doesn't work). I've tried various solutions, but haven't > come up with something that duplicates this behavior exactly. The behavior you are after is called "Two's complement," and is tied to using fixed-size integers and to simplifying how negative numbers are handled in hardware. Google, of course, knows all (provided you know the questions... ;). But more to the point: Here's something that will do the trick if your overflow isn't ever more than one bit. Note the last two cases - you may need to do some additional bounding if cases like those might occur for you (I haven't really dug into your algorithm, sorry! :). You will also need to extend it out to 32 bits. >>> def cp(myint): ... if myint > 0x7f: ... return -1 * (0xff - myint + 1) ... return myint ... >>> cp(1) 1 >>> cp(127) 127 >>> cp(128) -128 >>> cp(255) -1 >>> cp(0) 0 >>> cp(256) 0 >>> cp(257) 1 >>> cp(513) 257 >>> cp(-257) -257 Heh, implementing 2's complement in software... Who'd have thought? :) Enjoy! HTH, Eli -- Give a man some mud, and he plays for a day. Teach a man to mud, and he plays for a lifetime. WickedGrey.com uses SpamBayes on incoming email: http://spambayes.sourceforge.net/ -- From nicksjacobson at yahoo.com Sun Jun 6 02:24:14 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 5 Jun 2004 23:24:14 -0700 Subject: exec throws an exception...why? References: <3415c0lg306oec1a69c3mkolnbhfbku243@4ax.com> Message-ID: fishboy wrote in message news:<3415c0lg306oec1a69c3mkolnbhfbku243 at 4ax.com>... > On 5 Jun 2004 18:46:11 -0700, nicksjacobson at yahoo.com (Nick Jacobson) > wrote: > > >This works fine: > > > >x = 1 > >def execfunc(): > > print x > >execfunc() > > > >So why doesn't this? > > > >s = \ > >""" > >x = 1 > >def execfunc(): > > print x > >execfunc() > >""" > > > >codeobj = compile(s, "", "exec") > >d = {} > >e = {} > >exec codeobj in d, e > > > >Error message: > >Traceback (most recent call last): > > File "C:\Nick\proj\python1.py", line 17, in ? > > exec codeobj in d, e > > File "", line 6, in ? > > File "", line 5, in execfunc > >NameError: global name 'x' is not defined > > > >I'm using ActiveState Python 2.3.2 on Windows XP Pro. Thanks! > > > >P.S. It does work if I say > >exec codeobj in d > >but I don't understand why. > > It works because the local and global namespaces are both 'd'. it > doesn't work in the first because it puts 'x' in the local and then > looks in global. > > Now, why it puts 'x' in local, I don't know. If this was a quiz, I'd > put "Nested Scope" and pray. > > ><{{{*> I don't know either, that's why I asked ;) And I don't see why assigning both the local and global namespaces to the variable 'd' fixes it. But to answer that, the latter question has to be addressed first. --Nick From no at spam.invalid Wed Jun 2 19:59:18 2004 From: no at spam.invalid (Russell E. Owen) Date: Wed, 02 Jun 2004 16:59:18 -0700 Subject: Why did no one invent Python before? References: Message-ID: In article , j_mckitrick at bigfoot.com (j_mckitrick) wrote: >Yes, it's a silly question, but given how far we have come, why is it >that a natural looking, easy to read, incredibly powerful language has >appeared only recently, from a tech standpoint? > >I can't *believe* how much more productive I am with the built in data >types and powerful expressions Python offers. It made me want to quit >my C++ job. Well, not quite. ;-) > >Seriously, why is a language like this only NOW appearing? And aside >from the interpreter, because while it is nice, it's not the main >forte' of the language, IMHO. I think smalltalk users would argue that it was done many years ago. It looks a bit odd at first to C programmers, but is easy to learn and has most of the strengths of python: - interpreted - automatic garbage collection - simple and clean - powerful - rich set of collection types - rich set of libraries There are a few important differences: - much worse for scripting - built in GUI - much better development environment; you really don't know what you're missing until you've used smalltalk's browsers, inspectors and debuggers. It's the main thing I really, really miss in python. I think lisp users would also argue for their language. It's really weird to non-lisp users (much more so than smalltalk is to C/python programmers) but really powerful. Anyway, I did not intend to detract from your praise of python. It is a wonderful language, and my main language right now. -- Russell From bart_nessux at hotmail.com Fri Jun 11 11:50:39 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 11 Jun 2004 11:50:39 -0400 Subject: urllib IOError Exception Message-ID: From the urllib documentation: "If the connection cannot be made, or if the server returns an error code, the IOError exception is raised. " Suppose I have an array of IPs and I want to pass each element of the array to urllib. Basically, I'm just trying to see how many hosts are serveing-up Web pages in a certain IP range. Is there a way in which I can handle the IOError so that the script will continue on to the next host in the array if the host before isn't running a Web server? Below is my code: def gen_ip_range(): import urllib n = 0 hosts = [] networks = [] while n < 254: n = n + 1 networks.append("192.168.%s." %(n)) for network in networks: h = 0 while h < 254: h = h + 1 hosts.append(network+str(h)) for host in hosts: f = urllib.urlopen("http://%s" %host) print f.read() f.close() gen_ip_range() Thanks, Bart From ptmcg at austin.rr._bogus_.com Wed Jun 23 00:06:50 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 23 Jun 2004 04:06:50 GMT Subject: Improving upon the Decorate-Sort-Undecorate idiom References: Message-ID: "Thomas Philips" wrote in message news:b4a8ffb6.0406221212.741d2379 at posting.google.com... > I recently had the need to sort a large number of lists of lists, and > wondered if an improvement to the Decorate-Sort-Undecorate idiom is in > the works. Ideally, I would like to sort the list of lists (or tuples) > in place by using a simple variant of the current idiom, i.e. > > list_of_lists.sort(*columns) > > where *columns is a tuple that specifies the column order for the > sort. If *columns is left blank, the sort ought to work as it does > today, i.e. > > list_of_lists.sort() > > should sort by columns 0, 1,2,..... > > Has such a method been considered for inclusion in Python? Does it > have any problems that would inhibit its adoption? > > Thomas Philips Thomas - Here are some pure-Python ideas, plus a preview of the Python 2.4 sort() enhancement. -- Paul import pprint listOfLists = [ [ 'a', 1, 'z', 3.1 ], [ 'c', 0, 'z', 4.2 ], [ 'a', 1, 'y', 5.5 ], [ 'b', 2, 'z', 1.0 ], [ 'c', 0, 'z', 4.2 ], ] print "\n- original list" pprint.pprint (listOfLists) print "\n- vanilla sort()" listOfLists.sort() pprint.pprint (listOfLists) def byColumns(col): def columnCompare(a,b): for c in col: if a[c] != b[c]: return cmp(a[c],b[c]) else: return 0 return columnCompare print "\n- using custom sort method" columns = (1, 2, 0) listOfLists.sort(byColumns(columns)) pprint.pprint (listOfLists) def sortByColumns(lst,cols): tmp = [ ([item[c] for c in cols],item) for item in lst ] tmp.sort() return [ t[1] for t in tmp] print "\n- using D-S-U with varying input columns" columns = (2,3) listOfLists = sortByColumns(listOfLists, columns) pprint.pprint (listOfLists) print "\n- using key argument in Python 2.4 (compare to D-S-U)" cols = (1,3) listOfLists.sort( key=lambda item: [item[c] for c in (cols)] ) pprint.pprint (listOfLists) From mandrzejewski at besancon.parkeon.com Wed Jun 16 07:45:26 2004 From: mandrzejewski at besancon.parkeon.com (Mike Andrzejewski) Date: 16 Jun 2004 13:45:26 +0200 Subject: python with Java API In-Reply-To: References: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <1087386326.20135.5.camel@dhcp78-116.besancon.parkeon.com> Hi, We have a quite big project which uses (historical feature...) Qt, and we are now _sure_ it was the _worst_ technical choice we made: It's deeply bad designed, and only appropiated for very light GUI. I would recommend Swing, without hesitation. Le mer 16/06/2004 ? 12:28, Sylvain Hellegouarch a ?crit : > Brendan, > > I would definitely go for Qt which doc is just awesome. > > Personnal opinion of course. > > - Sylvain > > Brendan J Simon wrote: > > Hi, > > > > I have a Java application from a company. They also provide an API in > > C++ (MSW platforms only) and Java (for all platforms) for developers > > that want to create their own front end. I want to use wxPython to > > create a decent Unix opensource frontend. > > > > Is it possible to Interface python to a java application easily ??? > > > > Assuming yes to above, would something like Jython or SWIG or some other > > tool be required. > > > > Any advice or pointers would be greatly appreciated. > > > > Regards, > > Brendan Simon. ________________________________________________________________________ Mike Andrzejewski Software Engineer Parkeon Parc La Fayette, 6 rue Isaac Newton 25075 Besancon Cedex 9, France. Phone : +33 (0)3.81.54.50.02 Fax : +33 (0)3.81.54.49.90 e-mail : andrzejewski at parkeon.com ________________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Mon Jun 28 23:43:54 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Jun 2004 20:43:54 -0700 Subject: Python Magazine exists! (was: Python intro questions) References: Message-ID: <4edc17eb.0406281943.32bb2e9a@posting.google.com> BTW Mark, what's the status of the article *I* submitted (I sent you a private email a couple of days ago but had no answer yet, so let me try the public forum instead ;) Michele Simionato From nospam at bluewin.ch Fri Jun 4 11:47:14 2004 From: nospam at bluewin.ch (Thomas Chassaing) Date: Fri, 04 Jun 2004 17:47:14 +0200 Subject: Setting the default precision in mxNumber Message-ID: <40c09982$1@zinews.unizh.ch> Hi, I just installed the mxNumber package and looking trough the documentation I found no means to set the default precision for Float numbers (I think it is set to 64bits). Does anyone know how the default precision can be changed, or do I have to use the Float(value,precision) constructor all the time? Thanks T. Chassaing From no_replies at fake_email_address.invalid Thu Jun 3 17:08:25 2004 From: no_replies at fake_email_address.invalid (Robert Oschler) Date: Thu, 3 Jun 2004 17:08:25 -0400 Subject: Anybody seen a misspelled variable name finder tool? Message-ID: One of the recurring bugs I find in my program, is a bug due to a misspelling of a variable name. Is there a code checker out there that can help find these critters? If so, URL's please. Thanks. -- Robert From __peter__ at web.de Fri Jun 25 04:29:43 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Jun 2004 10:29:43 +0200 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> <889cbba0.0406240650.35ebf730@posting.google.com> <889cbba0.0406241734.14667b79@posting.google.com> Message-ID: Kamilche wrote: > Heheh, I'm a Python newbie. I can't even understand the code you have > written, but I'll try. If I don't understand Python code, I tend to blame the code. I'll try to either explain or rewrite the "dark" pieces below. > You know, as I was writing stuff like fn(**args.__dict__) yesterday > (which for me is pretty advanced!), it occurred to me that Python is > not 'simpler than C', like I had originally thought. :-D It's better > in many ways, but it has its dark alleyways where a novice can get > stabbed in the back, too. Python and C are both simple. Python has friendlier error messages and less bloat, i. e. manual garbage collection in programs that actually work. Recent additions to Python and the newstyle/classic class schism, while all reasonable in themselves, make it harder to "know it all". If decorators take off, this will become even worse. Enough pessimism - Python is still much more compact than C++, and if anyone has the power to say no, then it's Guido van Rossum. If a way to integrate type inferencing smoothly is actually found, why should anyone want to program in C at all? Peter Now the revised code: import itertools, re, string _validchars = string.ascii_letters + string.digits + \ "!@#$%^&*()`~-_=+[{]}\\|;:\'\",<.>/?\t " _allchars = string.maketrans("", "") _invalidchars = _allchars.translate(_allchars, _validchars) # repeat(v) gives an "endless" sequence of v, so # zip("abc", repeat(None)) == [("a", None), ("b", None), ("c", None)] # In Python 2.4 I would use a set but in 2.3.x dicts are faster. # _invalidset = set(_invalidcars) _invaliddict = dict(zip(_invalidchars, itertools.repeat(None))) # contains only valid characters valid = "This is a string to test for invalid characters." # contains both valid and invalid characters invalid = valid + _invalidchars + valid # A LONG string containing MANY invalid characters to make # the translate() solution look bad massaged = (_invalidchars + valid) * 100 # supposing _invalidchars == "abc" we get the regex re.compile("[abc]"). # rInvalid.search(s) would then return a non-None result whenever s # contains an a, b, or c. The nice thing for our purpose is that it stops # at the first match, i. e. if the first char is invalid, we don't care # about the rest rInvalid = re.compile("[%s]" % re.escape(_invalidchars)) def validate_list(s, invalid=_invalidchars): # since the set of invalid characters is used many times, # it is faster to have it as a local variable. # I don't know why, but achieving this via a default parameter # is even faster than a # invalid = _invalidchars # assignment at the beginning of the function for c in s: if c in invalid: return False return True def validate_dict(s, invalid=_invaliddict): # exactly the same as validate_list, but the # c in invalid # is faster because invalid is a dictionary for c in s: if c in invalid: return False return True def validate_translate(s): return len(s.translate(_allchars, _invalidchars)) == len(s) def validate_regex(s): return not rInvalid.search(s) def validate_noop(s, valid=valid): """ Not a valid implementation. Only to estimate the function call overhead. """ return s is valid def measure(func, data): """ Run the speed test for a func/data pair and print the result. func: name of the function to be tested data: name of the variable containing the sample data """ print " ", data, setup = "from findcharspeed import %s, %s" % (func, data) run = "%s(%s)" % (func, data) # example of the above: # from findcharspeed import validate_list, valid # validate_list(valid) # this statement will be timed # timeit.main() expects parameters from the commandline, so we have # to add the appropriate switches when invoking it programmatically. timeit.main(["-s" + setup, run]) if __name__ == "__main__": import timeit # functions I want to time tests = [validate_list, validate_dict, validate_translate, validate_regex, validate_noop] # make sure the functions return the correct result for f in tests: assert f(valid) assert not f(invalid) # calculate the timings for f in tests: print f.__name__ # test each candidate function with 3 different sample strings for data in ["valid", "invalid", "massaged"]: measure(f.__name__, data) From dave at boost-consulting.com Thu Jun 24 07:42:24 2004 From: dave at boost-consulting.com (David Abrahams) Date: 24 Jun 2004 04:42:24 -0700 Subject: Determining caller's file and line number References: <8a638f47.0406231330.7d59152f@posting.google.com> <230620041639365943%mrjean1@comcast.net> Message-ID: <8a638f47.0406240342.40692aa@posting.google.com> Jean Brouwers wrote in message news:<230620041639365943%mrjean1 at comcast.net>... > Here is one example: Fantastic! Thank you so much! -- David Abrahams Boost Consulting http://www.boost-consulting.com From Kuser-admin at kde.gr.jp Tue Jun 29 16:21:18 2004 From: Kuser-admin at kde.gr.jp (Kuser-admin at kde.gr.jp) Date: Wed, 30 Jun 2004 05:21:18 +0900 Subject: Subscribe request result (Kuser ML) References: <20040629202115.159C21F83C5@mail.kde.gr.jp> Message-ID: <200406300521.FMLAAA23972.Kuser@kde.gr.jp> Hi, I am the fml ML manager for the ML . --Kuser at kde.gr.jp, Be Seeing You! ************************************************************ If you have any questions or problems, please contact Kuser-admin at kde.gr.jp ************************************************************ From has.temp2 at virgin.net Wed Jun 2 15:06:36 2004 From: has.temp2 at virgin.net (has) Date: 2 Jun 2004 12:06:36 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406021106.c393f20@posting.google.com> Pete Prodoehl wrote in message news:... > This HTMLTemplate is quite different from the other HTML-Template's I've > seen... [...] I confess that the potential for confusion didn't occur to me till fairly late on. I just chose the name because it was self-explanatory and didn't clash with the name of any existing modules for the same languages, and didn't realise that html-template modules for other languages were similarly derived from a single common source. Guess I should hurry to snap up any as-yet unaffiliated languages before the competition gets there first...;) > I believe these all share the basic idea of using a common templating > language within your HTML documents (which can be valid, if using for the tags.) [...] > The nice thing about this is that once you learn the templating tags, it > doesn't matter what language you use, so you could change the backend > from Perl to Python and not even have to change any of your templates. I've heard this said before, but am curious just how much of an advantage it really is? I'd have thought reimplementing an entire backend would be a much bigger task than porting templates and a relatively rare occurence in practice; not sufficient in itself to justify learning a second language in the first place. Anyone got any practical experience in this and can comment? From aweil at mail.ru Mon Jun 28 16:37:23 2004 From: aweil at mail.ru (alejandro david weil) Date: Mon, 28 Jun 2004 17:37:23 -0300 Subject: Can you make this faster? In-Reply-To: References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <200406281737.00688.aweil@mail.ru> On Mon June 28 2004 16:51, Andrea Griffini wrote: > After making a few experiments I found this faster... > > def fmtstring5(args, [..] > t = _type(arg) > if t is _str: > l = _len(arg) > fmt = fmt + _str(_len(arg)) + 's' > elif t is _int: [..] > else: > raise Exception("Can't pack argument of type %s!" % t) > return fmt+'\0' > PS: I'm new to python, and found its speed interesting and > more than adequate for many uses... It's however kind > of depressing seeing that so much dinamicity is "wasted" > in places where it's not needed (e.g. when calling "len" > or "str"). This version was running on the examples I > tested about twice the speed of the original version. It seems that no one has read my last post :-) You can replace str() with an array access for many of the strings as you want.. let's say.. slen = [] for i in xrange(256): slen.append(str(i)) And then, in your function: def mystrbla..(): ... try: fmt += slen[_len(arg)] + 's' except: fmt += str(_len(arg)) + 's' Please, try it! :-) ------------------------------------------------------------------ And, another improvment is add the 's' to the slen array :-) and..: slen = [] for i in xrange(256): slen.append(str(i)+'s') def mystrbla..(): ... l = _len(arg) if l <256: fmt += slen[l] + 's' except: fmt += str(l) + 's' Unreaded greetings! alejandro -- + There is no dark side of the moon really. Matter of fact it's all dark. From claird at lairds.com Mon Jun 14 19:11:22 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 14 Jun 2004 23:11:22 -0000 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <10cr9m1q7tlp4b4@corp.supernews.com> Message-ID: <10csc4qspq17u0c@corp.supernews.com> In article , Peter Hansen wrote: >Carl Banks wrote: >> Heh. It seems to me that, by the same reasoning, we could claim that >> Python has verbose execution. Someone's obviously willing to give >> Perl the benefit of the doubt here, but not Python. I smell >> shenanigans. > >I tried a few Google searches, even apparently reaching the page that >started this thread, but I can't see what "verbose execution" might >mean other than (a guess) a "trace" mode which prints something for >every line executed as the interpreter runs. And, if that's really >what it is, then Python does have the capability pretty easily, via >sys.settrace(). (Which I'm sure Carl knows, therefore I assume my >guess is wrong.) . . . I idly and gratuitously submit that I regard it as more likely the Scriptometer folks are that ... naive. -- Cameron Laird Business: http://www.Phaseit.net From claird at lairds.com Thu Jun 3 09:41:23 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 13:41:23 -0000 Subject: Why did no one invent Python before? References: Message-ID: <10buak3htmhb5de@corp.supernews.com> In article , Peter Hansen wrote: >j_mckitrick wrote: . . . >> Seriously, why is a language like this only NOW appearing? > >I would claim that Rexx, which appeared long before even Python >was invented, is quite "like this" language we currently love. > >-Peter Good catch. I find Rexx similar also in the passion it has inspired in some users, particularly in its Amiga (and, in a more subdued way, OS/2) manifestation(s). -- Cameron Laird Business: http://www.Phaseit.net From beliavsky at aol.com Tue Jun 8 16:47:13 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 Jun 2004 13:47:13 -0700 Subject: Python "header" files Message-ID: <3064b51d.0406081247.17008d43@posting.google.com> Ideally, one can use someone's C++ code by just looking at the header files (which should contain comments describing the functions in addition to function definitions), without access to the full source code. Can analogs of C++ header files be created for Python code? Python "header" files could list only the 'def' statements and docstrings of Python functions and classes, but that does not tell you what the functions return. One could list the return statements as well, but there can be several of them in a function, and they often show HOW something is calculated, which is "too much information" for a header file. I wonder how Python projects with multiple programmers can be coordinated without giving all programmers access to all of the source code. I am currently working on one-man projects, but I am still interested in ways of separating interface from implementation. From davidf at sjsoft.com Sat Jun 19 07:04:47 2004 From: davidf at sjsoft.com (David Fraser) Date: Sat, 19 Jun 2004 13:04:47 +0200 Subject: wxPython on GTK In-Reply-To: References: Message-ID: Fernando Perez wrote: > Batista, Facundo wrote: > > >>In this context, I got worried when a friend of mine (codeveloper of sigefi) >>could not install PyNSource because wxPythonGTK been always using private >>methods from GTK, and now that GTK does not have them anymore, don't work. >> >>The bug is 915333 >>(http://sourceforge.net/tracker/index.php?func=detail&aid=915333&group_id=98 >>63&atid=109863). >> >>The problem is that it's actually closed but not fixed, so I'm worried about >>the viability of wxPython in GTK. > > > My _guess_ is they'll have to fix it, and sooner rather than later. Wx is in > widespread use under Linux, and they managed to break it completely under > (among others) Fedora Core 2: > > In [2]: import wx > --------------------------------------------------------------------------- > ImportError Traceback (most recent call last) > > /home/fperez/code/python/vis3d/ > > /usr/lib/python2.3/site-packages/wx/__init__.py > 43 __revision__ = "$Revision: 1.1.2.4 $"[11:-2] > 44 > ---> 45 from wxPython import wx > 46 > 47 _newnames = {} > > /usr/lib/python2.3/site-packages/wxPython/__init__.py > 18 # Ensure the main extension module is loaded, in case the add-on > modules > 19 # (such as utils,) are used standalone. > ---> 20 import wxc > 21 > 22 > #---------------------------------------------------------------------------- > > ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: > _gtk_accel_group_detach > > Essentially in Fedora2, Wx is unusable. I have four versions of wxPython running successfully on Fedora 2 - wx 2.4.2.4 with GTK, wx 2.5.1.5 with GTK, wx 2.5.1.5 with GTK2 and wx 2.5.2 prerelease with GTK2 The only problem is that certain binary RPMs produced aren't compatible with Fedora Core 2, because they're built on a RedHat 9 machine You can rebuild them from source rpms and they work fine. In fact (checks) ... surprise, surprise, you can get Fedora RPMs from Fedora extras. Now if you have a problem with that you can complain :-) David From peter at engcorp.com Sat Jun 19 09:19:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 09:19:28 -0400 Subject: [python] using try: finally: except In-Reply-To: References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> Message-ID: Carl Banks wrote: > Frankly, when you do a try...finally, you're not really trying. In > the words of the Jedi Master: "Try not. Do, or do not. There is no > try." Which is why I think it should rather be do...finally. I have to disagree (because it's wrong :-) : try: print "will this code work?" x = y print "no, it won't!" finally: print "so it really _was_ 'try'..." If you used 'do' you might get the impression that the contents of the 'do' were guaranteed to execute or something... -Peter From emcpeters at anacapasciences.com Thu Jun 24 08:37:29 2004 From: emcpeters at anacapasciences.com (Evan McPeters) Date: Thu, 24 Jun 2004 05:37:29 -0700 Subject: Applications for ipaq and Palm Pilot Message-ID: <40dacb1a$1@newsfeed.netlojix.com> I need to develop an application that will run on an ipaq handhelp and possibly the Palm Pilot as well. Can this be done in python? Do I need a special library to make it work? Thank you. From jjl at pobox.com Fri Jun 4 07:42:45 2004 From: jjl at pobox.com (John J Lee) Date: Fri, 4 Jun 2004 12:42:45 +0100 (GMT Daylight Time) Subject: Which is the most mature Soap module? In-Reply-To: References: <87d64jdpz3.fsf@pobox.com> Message-ID: On Fri, 4 Jun 2004, [ISO-8859-1] Mickel Gr?nroos wrote: > The following is a rather long message. Here is a summary of my questions > below: > > 1. ZSI fails on a TypeError when using ZSI.ServiceProxy, why? dunno -- it's a while since I used it. Is that part of the WSDL stuff? All that (which is common code between ZSI and SOAPpy) was pretty flaky when I tried it. > 2. Is there a way to use cookie authentification with SOAPpy > (client-side)? Yes, no reason why not to use my ClientCookie package to do that, but I don't know from memory exactly where you need to insert the required code in SOAPpy. I'm slightly surprised if SOAP needs cookie handling, but not entirely, since I know it is required for some XML-RPC services. [...] > 2. Second, I need to upload a local file to a specific place on the server > using the cookie as authentification. [...] > TypeError: an integer is required > >>> > > Any ideas what this might be? I gather I would need to set the port to 443 > somewhere, but I can't find the right place. No idea without digging, sorry. As I say, WSDL support is definitely flaky, so it's always possible you've just hit a bug. > The second part, i.e. the upload, is trickier. Using SOAP::Lite in Perl, > one can specify a cookie to use for authentification, but I can seem to > find that in the documentation of SOAPpy. So how do I do cookie > authentification with SOAPpy (or ZSI for that matter)?? [...] > -> proxy('http://services.xmethods.net/soap/servlet/rpcrouter', > cookie_jar => HTTP::Cookies->new(ignore_discard => 1)); > > print $soap->echoString('Hello')->result; > > I need something like that 'cookie_jar' parameter in SOAPpy too. Help and > thanks! I might have a look this weekend, but don't promise. John From tismer at stackless.com Fri Jun 25 12:54:03 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 25 Jun 2004 18:54:03 +0200 Subject: Parameterized Functions without Classes Message-ID: <40DC58AB.8080108@stackless.com> Hi Pythonistas, just as a small comment on the side-effects of the rather new concept of local functions with access to their scope: This concept can be used to avoid having extra classes just for keeping some read-only state. Since this feature is not so obvious in the first place, I thought to share the obervation. In the ancient times, I saw myself writing classes to parameterize functions, like this: class Converter: def __init__(self, scale): self.scale = scale def __call__(self, arg): return self.scale * arg inch_to_cm = Converter(2.54) cm_to_inch = Converter(1 / 2.54) ... >>> inch_to_cm(20) 50.799999999999997 >>> cm_to_inch(20) 7.8740157480314954 >>> This can be easily done without an extra class, just by local variables which access the outer scope: def _converter(scale): def convert(arg): return scale * arg return convert inch_to_cm = _converter(2.54) cm_to_inch = _converter(1 / 2.54) >>> inch_to_cm(20) 50.799999999999997 >>> cm_to_inch(20) 7.8740157480314954 >>> This trick (and I don't consider it a trick) works for all cases, where you don't need write access to an instance variable, but read access, only. It is a very clean way to parameterize functions, and it is very effective since there is no attribute lookup necessary. cheers - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From qrczak at knm.org.pl Sun Jun 13 13:40:22 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sun, 13 Jun 2004 19:40:22 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 13 Jun 2004 10:24:14 -0700, David Turner wrote: > Objects that define __del__ shall have a reference count, which is > incremented when names are bound to the object and decremented when > those names go out of scope. The __del__ method is called when the > reference count reaches zero. This mechanism is orthogonal to garbage > collection. It's not statically known which variables hold objects which define __del__. This implies that you must walk over all local variables of all function activations, in addition to GC overhead, and you must manage reference counts in all assignments. I'm afraid it's unacceptable. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From martin at v.loewis.de Sun Jun 13 06:00:56 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 12:00:56 +0200 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <40CC25D8.4030104@v.loewis.de> Michael P. Soulier wrote: > As soon as I heard about not being able to trust destructors, I was > shocked, because I do rely on guaranteed finalization, and I also > consider it to be very elegant. "Guarantee" and "able to rely on" are different things, actually. A guarantee is something that someone gives you, which they might not do even though they could. For example, you can rely on sunset to occur before midnight, but nobody might give you a guarantee for that. So the Python language specification does not guarantee anything about invoking __del__. However, you can still rely on C-Python 2.3.4 invoking it eventually. More precisely, C-Python 2.3.4 (and most other releases of C-Python) will invoke __del__ if the last reference to an object goes away. A reference goes away if: - the variable is del'ed, or a different value is assigned, or - the variable is a local variable, and the function terminates through a return (if the function terminates through an exception, a traceback object is constructed which takes over the local variable). - the variable is attribute of an object, and the object goes away - the variable is an implicit variable in the interpreter, and gets a new value. Some of the implicit variables are: - the current exception and traceback - the last exception and traceback - the sys module - the codecs module > myfile = open("myfilepath", "w") > myfile.write(reallybigbuffer) > myfile.close() > > If the write fails due to a lack of disk space, the exception will > prevent the explicit close() from happening. Now, if myfile goes out of > scope, I would hope that the file object is destroyed and thus the file > is closed, but after reading the python documentation, it seems that > the only way to guarantee closure of the file is using the mentioned > try/finally construct... C-Python 2.3.4 will close the fil if myfile goes out of scope, unless there is an exception, in which case myfile is referred to in the traceback, in which case the file is closed when the traceback object is released, which happens when the exception handler for the exception has completed. If the exception was put out through PyErr_Print, the object stays alive through sys.last_traceback, where it stays until the next exception occurs. Regards, Martin From tzot at sil-tec.gr Fri Jun 4 04:47:54 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 04 Jun 2004 11:47:54 +0300 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <10buqs9pgco8vf4@corp.supernews.com> Message-ID: <4od0c0psni9ljtpcnu6guulubquotu9rmv@4ax.com> On Thu, 03 Jun 2004 18:18:49 -0000, rumours say that claird at lairds.com (Cameron Laird) might have written: >In article <2i96n6Fklj78U2 at uni-berlin.de>, >Reiner Block wrote: >>Hi, >> >>does anybody knows a really good Python reference? It is not the matter if it >>is online or a book, if it is in english or german. Because the official one >>from www.python.org is really bad. :-( . >When you provide more description about how http://docs.python.org/lib/lib.html > is "bad", >then others will understand better what you seek, >and will be able to help you find "a really good >Python reference" more accurately and efficiently. Even better, if provided with the "why" it is "bad", others might be able to improve the current documentation... -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From deetsNOSPAM at web.de Fri Jun 11 14:30:39 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 11 Jun 2004 20:30:39 +0200 Subject: class.print method illegal References: Message-ID: > creates a syntax error. Why can't a class have > a method called "print"? Doesn't seem to be > any way it could be confused with the reserved > print statement, or am I missing something? Obviously, otherwise python wouldn't complain :) As methods aren't much different from plain functions, I think we can agree that a exception rule like "in methods, keywords can be used as names, but not on normal functions" would be quite confusing. Now consider this example: >>> def foo(): >>> pass >>> foo Now what would you expect a >>> def print(): >>> pass to do when print is issued alone on the commandline? print as class method could be referenced as as klass.print of course, but as I stated above, that would be inconsistent. Another reason might be that creating a context-relevant re-interpretation of keywords complicates the parser uneccesarily - with very limited benefit. - Regards, Diez B. Roggisch From __peter__ at web.de Fri Jun 11 13:08:27 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 19:08:27 +0200 Subject: raw Strings from XML attributes References: Message-ID: Karen Loughran wrote: > . But because it isn't raw it won't match. I fear you have a misconception about raw strings. r"\abc" "\\abc" and chr(92) + "abc" are exactly the same strings when written in Python source code. If your strings do not match, it has nothing to do with "rawness". Peter From michele.simionato at poste.it Tue Jun 15 05:39:56 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Jun 2004 02:39:56 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: <95aa1afa.0406150139.7ad976fe@posting.google.com> Michael Sparks wrote in message news:... > [ I'm not really sure of the etiquette of the python-dev list, so I think > I'll play "safe" and post this thought here... I know some of the > developers do look here, and Guido's comment (before europython) on the > dev list saying he's not interested in new syntaxes makes me think this > is a better place for it... ] > > Anyway... > > At Europython Guido discussed with everyone the outstanding issue with > decorators and there was a clear majority in favour of having them, which > was good. From where I was sitting it looked like about 20:20 split on the > following syntaxes: > 1 def func(arg1, arg2, arg3) [dec,dec,dec]: > function... > 2 [dec,dec,dec] def func(arg1, arg2, arg3): > function... > > When it came to the decision on whether 2.4 includin one of these two > options or a waiting for a third unspecified, indeterminate syntax in a > later version, it looked like around a 60:40 vote in favour of waiting. > (ie 60:20:20 for waiting/syntax 1/syntax 2) > The problem of metaclasses-based solutions is that they are hacks. We don't want everybody to implement his/her version of decorators (yes me too I have implemented mine). Decorators MUST be in the core language. Waiting will only favor the abuse of metaclasses. I do not particularly like each of two syntaxes (even if the second one looks better) but also I do not particularly dislike them. My preferred solution would be def func(...) is dec: .... *without* the ability to specify multiple decorators (i.e. let compose the multiple generators explicitely by hand, with a functional.compose function or something like that). But I prefer to have a syntax I don't like 100% then waiting for another year or so. Why don't put a given syntax in 2.4a, see how it goes, and change it in 2.4b if it is the case? Michele Simionato From peter at engcorp.com Thu Jun 10 10:58:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 10:58:29 -0400 Subject: exceptions In-Reply-To: <8ef9bea6.0406100620.7de79250@posting.google.com> References: <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> <95aa1afa.0406092138.338568b2@posting.google.com> <8ef9bea6.0406100620.7de79250@posting.google.com> Message-ID: <1oCdnUhK66iK6lXdRVn-sA@powergate.ca> Hung Jung Lu wrote: > michele.simionato at poste.it (Michele Simionato) wrote: > >>Sorry for the previous message, but I couldn't resist the temptation >>to mock you. So you may realize how irritating certain statements can >>be. > [...] At this modern age, one > not only needs to learn, but one needs to learn how to learn. > Meta-learning, if you wish. :) Thus proving the point once again... -Peter From surferjeff at gmail.com Fri Jun 11 15:14:50 2004 From: surferjeff at gmail.com (Jeff) Date: 11 Jun 2004 12:14:50 -0700 Subject: Insecure Pickling Message-ID: <781dd16f.0406111114.17959b90@posting.google.com> The pickle module is so powerful. It has probably saved me thousands and thousands of lines of code over the years. It alone is enough to pursuede me to use Python in many instances. However, it is so insecure it can hardly ever be used. How often can you truly trust the think you're unpickling? Has anyone seen a secure pickle alternative? From heikowu at ceosg.de Thu Jun 3 16:33:26 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 3 Jun 2004 22:33:26 +0200 Subject: Python reference In-Reply-To: <2i9e1tFkjtj8U1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: <200406032233.26503.heikowu@ceosg.de> Am Donnerstag, 3. Juni 2004 21:55 schrieb Reiner Block: > [snip] btw... looking at your resum?, I find it quite hard to believe you've never had to call exec*() in another language before... ;) Calling exec() in C takes the same arguments, first argument: program name, and then the rest... Anyway, hope this clears things up! Oh, and I just wanted to say that I find the Python documentation fantastic as it is! I don't want to have another PHP-newbie like spelling-out-every-detail-but-don't-find-what-you're-looking-for kind of documentation, but just as Python applauds to every programmers common sense, so should the documentation... And if there's any doubt, looking up man 2 exec should've gotten you there too... I don't say I don't have any criticism about some other parts (like the Extending and Embedding manual), but overall it's just fine as it is... Heiko. From davidf at sjsoft.com Wed Jun 30 13:05:59 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 19:05:59 +0200 Subject: Python Bounties In-Reply-To: <7xwu1povzf.fsf@ruckus.brouhaha.com> References: <7xwu1povzf.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > David Fraser writes: > >>>http://orderweb.co.za/open_source_developers_bounties.htm >> >>... >>There have been a few projects to set up open marketplaces for open >>source developers, but I couldn't find them using google ... anyone? >> >>I hope you post more details soon :-) > > > If that's Mark Shuttleworth's project, there was a Slashdot thread about > it a month or two ago. No I'm talking about open marketplaces for connecting bidders and buyers, not individual bounty sponsorship David From esj at harvee.org Wed Jun 2 12:00:07 2004 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 02 Jun 2004 12:00:07 -0400 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <40BDF987.7080809@harvee.org> David Fraser wrote: > It looks cool because it doesn't embed Python code in the template. > Do any of the other frameworks have this approach? opagcgilib.py is a simple look for %%key%% in dictionary and substitute value type of template tool. Which, quite frankly, is enough for me. All of the embedded python whoo-ha is just more of a barrier than anything else. Every time some bright puppy comes up with another twisted syntax party trick, it makes software development even more inaccessible to handicapped people like myself. I like Python for many reasons but a very important one is that it is something I can dictate using unenhanced speech recognition tools like NaturallySpeaking. It lets me get my work done and the typing idea have to do, doesn't aggravate the pain in my hands/arms. So anytime someone creates something with lots of special characters and StUDlYCapS, I want to scream but I don't because I don't want to damage my voice like I did my hands. Every time there is something special in the text that deviates from English, I need to go build a special tool to translate English to that SpclEnv. It is unfortunately not an easy process because most tools nor NaturallySpeaking are built for signaling context changes or making context changes. The end result being that I try to create only simple grammars and avoid using tools that cause me physical pain. having said that, I should probably admit to having created my own web page template tool. It is a very simple tool based on the opagcgilib.py Toolkit. since opagcgilib.py uses a dictionary as its input, I created a dictionary derivative that when an entry is read, it runs the value through opagcgilib.py. when a substitution occurs, it triggers a recursive run through opagcgilib.py until a value has no substitutions. The end effect is if you stuff a dictionary with a template and then all the components that will be requested during substitutions, you can merge these elements together into a single HTML page. What's a very nice is that you can just change the elements you need for subsequent pages. there are some helper functions for importing pages or fragments thereof into the dictionary. the user experience of editing these fragments is actually quite easy. All fragments are complete HTML pages and can be edited with an ordinary HTML editor. The only thing that is special is that sometimes you see %%main_body%% in a fragment. Everything else is just the same which is good because high-level editing of HTML is far easier if you are using speech recognition. (Are you starting to get a sense of a theme here... :-) here is a fragment from the camram web site construction code (unfortunately line wrapped) zodiac = inflatable() zodiac["top"] = extract_all("top_template.html") zodiac["copyright_date"] = "2002-2004" zodiac["main_welcome"], zodiac["title"] = extract_core("main_welcome.html", True) zodiac["main_news"] = extract_core("main_news.html") expel_all ( zodiac["top"], "output/index.html") # set up for all internal pages zodiac["top"] = extract_all("internal_template.html") # now do only per page changes # pages referred to by the top menus zodiac["title"] = "c a m r a m: Download It:" zodiac["body_text"], zodiac["title"] = extract_core("download.html", True) expel_all ( zodiac["top"], "output/download.html" -------------- and yes, this is what Python code written by speech recognition looks like. ---eric From dw at botanicus.net Wed Jun 9 17:07:15 2004 From: dw at botanicus.net (David Wilson) Date: Wed, 9 Jun 2004 22:07:15 +0100 Subject: Dicts 5x Faster than Sets In-Reply-To: <889cbba0.0406091124.4c29126e@posting.google.com> References: <889cbba0.0406091124.4c29126e@posting.google.com> Message-ID: <20040609210715.GB25097@china.botanicus.net> On Wed, Jun 09, 2004 at 12:24:25PM -0700, Kamilche wrote: > Hm, I just saw the 'sets' feature, and ran some timings to see if I > should use it instead of 'dict' sometimes. I discovered it's 4x slower > in adding, and 6x slower in removing items! Which version of Python did you test this on? In the upcoming Python 2.4, sets will be significantly faster, so don't discard their use yet, as they'll be implemented using native code within the year. David. -- "Science is what we understand well enough to explain to a computer. Art is everything else we do." -- Donald Knuth From eugene at boardkulture.com Sat Jun 12 12:08:35 2004 From: eugene at boardkulture.com (Eugene Van den Bulke) Date: Sun, 13 Jun 2004 02:08:35 +1000 Subject: accumulators Message-ID: Hi, I have just finished reading Paul Graham Hackers & Painters book (which I recommend even though he seems a bit hard on Python) In chapter 13 of his book he wants to demonstrate LISP power VS other languages (to be precise he wants to illustrate what he means by relative power of programming language). "We want to write a function that generates accumulators - a function that takes a number n, and returns a function that takes another number i and returns n incremented by i (that's incremented by, not plus. An accumulator has to accumulate). In Common Lisp this would be: (defun foo (n) (lambda (i) (incf n i))) ... Python doesn't fully support lexical variables, you have to create a data structure to hold the value of n. And although Python does have a function data type, there is no literal representation for one (unless the body is only a single expression) so you need to create a named function to return. This is what you end up with: def foo(n): s=[n] def bar(i): s[0]+=i return s[0] return bar " It seems to me that this code does the job (but I am not sure I understand exactly what an accumulator is): def test(n): return lambda i: n+i Is that an accumulator? If it is, PG must have written this chapter working on an older verion of Python ... Regards, Eugene Van den Bulke From indigo at bitglue.com Sat Jun 5 00:51:44 2004 From: indigo at bitglue.com (Phil Frost) Date: Sat, 5 Jun 2004 00:51:44 -0400 Subject: Can python control complicated classes/objects written in C++ In-Reply-To: References: Message-ID: <20040605045144.GA1386@unununium.org> If you can think it, Python can do it. To get a feel for how it works, take a look at http://python.org/doc/2.3.4/ext/ext.html. Using the C API, you can make Python do anything. However, writing all the glue can be boring and error prone, so there are a number of tools to make this easier. Take a look at http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ and http://swig.sourceforge.net/ for ideas. On Fri, Jun 04, 2004 at 11:24:38PM -0500, Bo Peng wrote: > Dear Python group: > > I am planning on an application that involves several complicated C++ > classes. Basically, there will be one or two big data objects and some > "action" objects that can act on the data. I would like to use a script > language to control the interaction between these c++ objects. > > [snip] > > I am totally new to Python. I have read boost.python, python extension > document but still do not know exactly what to do. My questions are: > > 1. can Python fully read/write member data and run member functions of > my objects? > > 2. can python pass complicated objects (TAction) to another object (TData)? > > 3. If python can not do this, I will have to create my own scripting > language. Given the above pseudo code, any suggestion on how to > implement it? I have googgled Qt Script for Application and many other > weird implementations but I either do not like the grammar of the script > language or the huge overheads. > > Many thanks in advance. > > Bo From jbperez808 at yahoo.com Wed Jun 9 11:46:11 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 09 Jun 2004 23:46:11 +0800 Subject: dropping into the debugger on an exception In-Reply-To: References: <2inqlrFp53m5U1@uni-berlin.de> <2iolfjFp6c46U1@uni-berlin.de> Message-ID: <2iop8fFo3oeeU1@uni-berlin.de> Peter Hansen wrote: > Just to be clear: you don't want this to happen all the time, > you want it to happen only with a particular script, yet you > don't want to modify that script at all? Correct. I don't even want it to happen all of the time with that particular script (because I may eventually deploy it for others to use who may be confused by being dropped into pdb). I can easily disable it by not assigning info() to sys.excepthook. But like I said, preferably, I don't even want to add anything to the script source code. > Would it be sufficient to have a local sitecustomize.py file > in the directory where the script is, or do you have other > scripts in that folder which you don't want to get the same > treatment? > What about a wrapper which you invoke instead of the script, > which sets this up and then runs the real script using > "import" and an appropriate direct call? These are both acceptable to a certain extent, and frankly, if these were the alternatives, I will just stick to putting info() in any script I intend to debug this way. I was just wondering if there wasn't a cleaner/more intuitive way which would be to just invoke the script from within pdb and have pdb do the right thing (i.e. stay within itself) upon an exception. Can't one prevent pdb from exiting if an (unanticipated) exception occurs in a script (or function) it invokes? And secondly, how do you pass command-line arguments to a script invoked from within pdb? I'm not even sure how to invoke a script proper like you would from a command line, all the examples I see invoke specific functions within a script. Not being able to accomplish simple things like this in a straightforward manner is what's keeping me from wholeheartedly embracing pdb. From pwmiller1 at adelphia.net Wed Jun 30 23:21:52 2004 From: pwmiller1 at adelphia.net (Paul Miller) Date: 30 Jun 2004 20:21:52 -0700 Subject: Any list larger than any number by way of dimensions? References: Message-ID: <2e363c08.0406301921.4c4681f9@posting.google.com> David Fraser wrote in message news:... [re: None < number < list < string < tuple ] > > > > Which is consistent but wrong. > > It's consistent but arbitrary. How can you say its wrong? It does what > its defined to do. It may be right, but it's probably not The Right Thing To Do(tm). The main problem /I/ have with it is that complex numbers represent an exception (no pun intended) to this rule among all the built-in types in that they don't compare to anything. I wonder if the Right Thing (tm) would be to have comparisons between types raise an exception unless the interpreter is instructed otherwise by a __cmp__ method. This neatly takes care of subclasses of builtin types, so you could still use a subclass of int, for example, anywhere you could use an int (unless you specifically override __cmp__). from __future__ import comparisons, anyone? :) From fowlertrainer at anonym.hu Tue Jun 29 05:47:26 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 29 Jun 2004 11:47:26 +0200 Subject: what editor do you use? In-Reply-To: <40e11ad2$1@e-post.inode.at> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <40e11ad2$1@e-post.inode.at> Message-ID: <40E13AAE.5050908@anonym.hu> Leopold Schwinger wrote: > Currently I use crimson-editor (only for win32) > http://www.crimsoneditor.com/ I use Context in win32, SciTE in Linux X, joe in Linux console. Context is working good in Windows, I use for Zope external editor too. FT From christian_dumenil at moiroud.com Thu Jun 17 01:16:27 2004 From: christian_dumenil at moiroud.com (christian_dumenil at moiroud.com) Date: Thu, 17 Jun 2004 07:16:27 +0200 Subject: Its me Message-ID: <20040617053854.D6F0EEC0E7@mailint.ascom.fr> The file is protected with the password ghj001. From me at privacy.net Sat Jun 12 09:34:11 2004 From: me at privacy.net (Duncan Booth) Date: 12 Jun 2004 13:34:11 GMT Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: "Roger Binns" wrote in news:q3ipp1-4bp.ln1 at home.rogerbinns.com: > Duncan Booth wrote: >> The object itself can know that it needs to be safely disposed of, >> but it cannot tell *when* to dispose of itself. My example function >> might create multiple objects some of which need disposing when the >> function returns, and others have a longer lifetime. The choice >> between disposing at the end of the function or when some containing >> object is disposed has to be one for the caller. > > You have totally confused me now. Ignoring special cases such as > cycles, Python destructs an object when there are no references left > to it, and in CPython that happens at the moment the last reference is > released. So in normal code the objects will go away as names > referencing them go out of scope. I wouldn't say that cycles are special cases exactly. C Python destroys an object when no references are left. Jython and IronPython destroy objects when the underlying garbage collector feels like it (i.e. when the object is no longer reachable, which even without cycles is not the same as having no references). In most, if not all of these cases the underlying garbage collector is generational, so you can't even be sure that unreachable objects will be destroyed by the next collection, it may take several collections. Python (as a language) is careful not to specify a specific implementation (such as reference counting) because that would prevent efficient implementation on a variety of platforms. > > If the Python object is a proxy for another non-Python visible object > (such as a C level filehandle or GUI Window). In those cases > the extension module author has to deal with the situation, either by > adding an extra reference (the C level object is then the remaining > reference) or handling the lifetime of the C level object > independently. > > But for this thread, the actual problem is that __del__ methods may > not be called on objects, and if you read the doc implies they almost > never will be called. So we have the counter-intuitive (and IMHO user > hostile) situation where someone marks a class as needing extra code > to run to destroy it, and Python addresses that by saying you will > be lucky if the object will be destroyed (ie by not destroying the > object). No, Python guarantees that the object will (almost always) be destroyed. It just doesn't make guarantees about when that will happen. If you want guarantees about resources being released you have to write the code to do that yourself (e.g. with try..finally). The same applies for other languages such as Java, or languages running in Microsoft's .Net framework. Guaranteeing that all resources will be released at a specific time has implications for performance, and finalisers are actually pretty rare in practice, so the usual solution is to compromise. From chuck.amadi at ntlworld.com Wed Jun 23 02:29:12 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Wed, 23 Jun 2004 07:29:12 +0100 Subject: parse output screen ok but cant get desired output new file! Message-ID: <1087972151.1542.1.camel@cpc1-ely11-6-0-cust49.cdif.cable.ntl.com> By the way list is there a better way than using the readlines() to > > >parse the mail data into a file , because Im using > > >email.message_from_file it returns > > >all the data i.e reads one entire line from the file , headers as well > > >as just the desired body messages . > > > > > >fp = file("/home/chuck/pythonScript/testbox") > > >mb = mailbox.UnixMailbox(fp, > > >email.message_from_file) > > > > > > > > >mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") > > >for mail in fp.readlines(): > > > mailout.write(mail) > > > > > >Something like this> > > > > > >for mail in mb: > > > body = mail.get_payload() > > > mailout.write(body) # write only the body messages to SurveyResults.txt > > > > > >Cheers if the is a better way I can't get my head round how I can print > > >mail ( > > >only the body messages) to screen and the entire mail headers and body > > >to the new file. > > > > > >Hi have any one got any suggstions to my script I can parse the email > > >body messages to screen but I want the same desired effect to save to a > > >new file.I have tried a few things to no effect. > > . > > . > > . > > There's a lot going on in your message. I *think* what you want > > is the suggestion to replace > > for mail in fp.readlines(): > > mailout.write(mail) > > with > > mailout.write(fp.read()) > > -- > > > > > Hi again where I print mail.get_payload() > I want to write this to the file. Bu uisng readlinds() function I > obviously get the entire contents including the headers thus I want to > do something like this > for bdymsg in mb: > bdymsg = mail.get_payload() > print mail.get_payload()# prints body msg's to screen > mailout.write(bdymsg) > # mailout.write(mail.get_payload()) # Something along these lines. > mailout.close() From peter at engcorp.com Tue Jun 22 05:44:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Jun 2004 05:44:56 -0400 Subject: Cannot create a new file In-Reply-To: <40d79715$1_3@aeinews.> References: <40d77b19$1_3@aeinews.> <40d79715$1_3@aeinews.> Message-ID: Eric Belanger wrote: > Traceback (most recent call last): > File "./hnbupdate", line 42, in ? > localtousb() > File "./hnbupdate", line 12, in localtousb > > shutil.copyfile("/home/bilange/usb/.hnb","/home/bilange/.hnb-backup/"+str(int(time.time()))) > > File "/usr/local/lib/python2.3/shutil.py", line 38, in copyfile > fdst = open(dst, 'wb') > IOError: [Errno 2] No such file or directory: > '/home/bilange/.hnb-backup/1087869914' There's the problem... you can't copy to a non-existent directory. I think in your first posting, you gave some misleading info, too. You said that using os.system('cp ' + file1 + ' ' + file2) showed a Python IOError, but I think it was this instead (with the full filename instead of ...): cp: cannot create regular file `/home/bilange/....': No such file or directory If that's true, the problem is the same there, though the error comes from the cp program and not from Python. What you probably want to do is use os.makedirs(). This will create the directory, even recursively, if needed. It normally throws an exception if the directory already exists though, so you probably want to put all this in a nice function: def mycopy(src, dst): '''copies one file to another, quietly creating the dest dir if required''' dstdir = os.path.split(dst)[0] try: os.makedirs(dstdir) except OSError: pass # dir exists, ignore error shutil.copyfile(src, dst) # optionally copy access/modification time as well shutil.copystat(src, dst) -Peter From ptmcg at austin.rr._bogus_.com Sat Jun 26 20:07:58 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 27 Jun 2004 00:07:58 GMT Subject: How to trim n characters from right end of a string? References: Message-ID: "Robert" wrote in message news:GUnDc.13670$OX2.9785 at fe2.texas.rr.com... > Please tell this newbie how to remove n characters from the right end of a > string. > > Thanks, Robert > > At the Python '>>>' prompt: >>> a = "This is a string." >>> print a[:-5] This is a st From balaji at email.arizona.edu Mon Jun 14 23:15:12 2004 From: balaji at email.arizona.edu (Balaji) Date: 14 Jun 2004 20:15:12 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> Message-ID: <494182a9.0406141915.7061d0f6@posting.google.com> Hello Everybody... Here is a code (tested) class Test: def __le__(self,other): print " <= " def __ge__(self,other): print " >= " def __add__(self,other): print " + " def __radd__(self,other): print " r+ " Suppose s is an instance of Test. s=Test() s>=100 prints >= but 100>=s prints <= The point here is mathematically it is right but not modelling wise. By modelling I mean, the user wants to preserve the order in which he typed the expression. Is there a way to obtain the radd behavior in __ge__ and __le__ with current syntax.. Regards Balaji From jeffbarish at starband.net Wed Jun 16 15:40:38 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Wed, 16 Jun 2004 13:40:38 -0600 Subject: Easiest way to port Python program to PDA Message-ID: I have been developing a Python program with two intercommunicating (using sockets) parts, one of which runs on a desktop and the other on a PDA. For ease of development, I developed them both on a desktop. Now that I have them working on the desktop, I need to move the part destined for a PDA to a PDA. I had originally planned to use a Sharp Zaurus because it runs Linux (the OS of my desktop system) and I had found a Python port that was supposed to be available for that platform (Riverbank Computing). Unfortunately, Riverbank Computing just discontinued their port. They refer interested parties to another port (http://www.vanille.de/projects/python.spy), but that site has no code to download and does not respond to queries. Accordingly, I have to conclude that there is no Python port available for the Zaurus so I am back to square 1. My question in short: does anyone have suggestions for the easiest way to move the Python program to a PDA. The program uses a few modules from the standard distribution (2.3): socket, thread, time, os, and Tkinter. I expected to rewrite the GUI, but I am hoping to rewrite the rest of the program as little as possible. I have discovered a python for StrongARM Pocket PCs. There is also a python port for PalmOS, but that project appears to be dormant. I have also discovered handhelds.org, which explains how to run linux on iPAQ, but it isn't clear to me that it is possible to run python on the resulting linux installation. Does anyone have comments on the Palm vs Pocket PC choice? How difficult will it be to program the GUI on the PDA? I presume that I am going to have to do that using a language other than python, so I wonder about integrating it with the python code. If I have to program the GUI in another language, should I bite the bullet and rewrite the entire program in that language? -- Jeffrey Barish From msoulier at digitaltorque.ca._nospam Thu Jun 10 11:12:53 2004 From: msoulier at digitaltorque.ca._nospam (Michael P. Soulier) Date: Thu, 10 Jun 2004 15:12:53 +0000 (UTC) Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: On 10 Jun 2004 01:00:09 -0700, David Turner wrote: > > I'd challenge you on all three of those. Simple? Not to the guy who > has to remember to write finally around every resource-allocating > operation that may raise an exception. Clean? Hardly. See my > example below. Explicit? Yes, that's true, it is explicit. Much in > the same way as malloc and free are explicit. Are you sure that's > what you want? This is exactly what I've been arguing. I had one individual email me privately and insult my opinion of elegance. Nice to know that usenet hasn't changed much. I find the C++ code below far more elegant than the explicit release. Exactly what is the point of encapsulation if I have to look inside the black box? > C++: > ---- > mutex::scoped_lock lock(db_lock); > updatedb(); I greatly prefer this. One of the things I hate about Perl is the fact that I end up with "or die()" noise on every line that attempts to do something. Python was so much cleaner in that I could just put all suspect code in a try block. Now, it's looking like every time I acquire something, I'll need a try/finally around it to make sure it's released. I've traded one set of noise for another. Python programmers are always claiming that Python is so much cleaner than most languages. Lately, I'm not seeing that, and I think more can be done to achieve that. Mike -- Michael P. Soulier The major advances in civilization are processes that all but wreck the societies in which they occur. -- Albert North Whitehead From klachemin at home.com Thu Jun 24 21:42:35 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 18:42:35 -0700 Subject: Code: Rolling a Container Into a String Message-ID: <889cbba0.0406241742.51a2980b@posting.google.com> I want to convert a dict into string form, then back again. After discovering that eval is insecure, I wrote some code to roll a Python object, dict, tuple, or list into a string. I've posted it below. Does anyone know an easier way to accomplish this? Essentially, I want to avoid doing an 'eval' on a string to get it back into dict form... but still allow nested structures. (My current code doesn't handle nested structures.) I conked out before writing the 'unroll' code. I'm going to go watch some boob tube with my husband, instead, and leave that code for another day. If you know of a better way, or feel like writing the 'unroll' code and posting it, by all means, do so! :-D I'll check Google newsgroups before I tackle the job, to see if some kind soul took pity on me. --Kamilche import types SimpleTypes = [types.BooleanType, types.FloatType, types.IntType, \ types.LongType, types.NoneType, types.StringType] _dictdelim1 = "{" _dictdelim2 = "}" _listdelim1 = "[" _listdelim2 = "]" _tupledelim1 = "(" _tupledelim2 = ")" def roll(item): "Return a string representation of an object, dict, tuple, or list." return _roll2(item, [], {}) def unroll(s): "Unrolls a string back into a dict, tuple, or list." if type(s) != types.StringType: raise Exception("You may only pass strings to this function!") err = "Error occurred when parsing " + s + "!" state = 0 container = None for c in s: if c == _dictdelim1: lookfor = _dictdelim2 elif c == _listdelim1: lookfor = _listdelim2 elif c == _tupledelim1: lookfor = _tupledelim2 else: raise Exception(err) state = 1 def _quoted(s): ' Return a stringized value' if type(s) != types.StringType: return str(s) else: l = [] s = s.replace("'", "\'") l.append("'") l.append(s) l.append("'") return ''.join(l) def _roll2(d, lst, r): ' Function that does the work.' # Start of _roll2 t = type(d) if t == types.DictType: theid = id(d) if theid in r: raise Exception("Recursion detected! Stopping now.") r[theid] = theid cnt = 0 lst.append(_dictdelim1) for key in d.keys(): if key[0] != '_': lst.append(_quoted(key)) lst.append(': ') t = type(d[key]) if t in SimpleTypes: lst.append(_quoted(d[key])) else: _roll2(d[key], lst, r) lst.append(", ") cnt += 1 if cnt > 0: del lst[-1] lst.append(_dictdelim2) elif t in (types.ListType, types.TupleType): theid = id(d) if theid in r: raise Exception("Recursion detected! Stopping now.") r[theid] = theid cnt = 0 if t == types.ListType: lst.append(_listdelim1) else: lst.append(_tupledelim1) for item in d: if type(item) in SimpleTypes: lst.append(_quoted(item)) else: _roll2(item, lst, r) lst.append(", ") cnt += 1 if cnt > 0: del lst[-1] if t == types.ListType: lst.append(_listdelim2) else: lst.append(_tupledelim2) elif hasattr(d, '__dict__'): _roll2(d.__dict__, lst, r) else: raise Exception("Unhandled type " + str(t) + \ "! You may only pass dicts, tuples, lists, and " + \ "objects with a __dict__ to this function!") return ''.join(lst) class simple: pass def main(): l = ['List1', 'List2', 'List3'] d = {'Dict1': 'd1', 'Dict2': 'd2', 'list': l} t = ('Tuple1', d, 'Tuple2') print "It handles dicts, lists, and tuples." print roll(t), "\n" o = simple() o.name = 'the name' o.password = 'the password' o.list = ['ol1', 'ol2'] o.dict = {'od1': None, 'od2': 2} o.tuple = ('tuple1', 'tuple2') o.float = 1.5 o.long = 12345678901234567890 o.bool = True o.int = 1 print "It handles objects." print roll(o), "\n" print "It won't roll attributes whose name starts with '_'" o._recursion = o.tuple print roll(o), "\n" print "It will raise an exception if it detects recursion." print "This next one will cause recursion." o.recursion = o.tuple print roll(o), "\n" print "You can't roll simple types." print roll('a'), "\n" if __name__ == "__main__": main() From grante at visi.com Wed Jun 30 20:29:10 2004 From: grante at visi.com (Grant Edwards) Date: 01 Jul 2004 00:29:10 GMT Subject: setting icon using py2exe? References: Message-ID: On 2004-06-30, David Fraser wrote: > Or if you don't have time for that you could try this build > which is from latest CVS: > http://davidf.sjsoft.com/files/py2exe-0.5.1a1.win32-py2.3.exe > > Untested :-) Tested (at least a little bit), and it appears to work. Thanks! The correct icons show up in the desktop explorer (which is new), but I still don't get my icons showing up in the window's banner or in the taskbar when the program is running. :/ -- Grant Edwards grante Yow! Kids, don't gross me at off... "Adventures with visi.com MENTAL HYGIENE" can be carried too FAR! From jacek.generowicz at cern.ch Fri Jun 11 03:55:14 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jun 2004 09:55:14 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <16752bcc.0406101354.63610c62@posting.google.com> Message-ID: moughanj at tcd.ie (James Moughan) writes: > Jacek Generowicz wrote in message news:... > > moughanj at tcd.ie (James Moughan) trolls: > I have no doubt that Lisp can be extremely practical as a language. Lisp (Common Lisp) is _first and foremost_ an extremely practical language. It is the product of a couple of decades of smart people working on a language for solving difficult programming problems in industry, not in academia. > I'm expressing a slightly humorous characterization of the attitude of > parts of the Lisp community, especially in academia. While there is (used to be) quite a number of Lisp courses around which should be considered crimes against Lisp and humanity itself <0.3 wink> (I had the misforture of first encountering Lisp through one of these myself), that is no good reason to contribute yourself to perpetuating the myths that such courses help to establish. > > Maybe Lisp (and therefore Lisp books) are designed for intelligent > > people who want to solve hard problems, and it is assumed that > > intelligent people can look up trivia like how to open files in the > > language standard (); maybe books are considered necessary to teach > > you the difficult things which you cannot read between the lines of > > the standard. [...] > Strange, I've always worked the other way around. For the extremely > simple, basic things it seems like *slight* overkill to refer to the > ansi standard. What's the point of writing a book telling you how to open files in CL? This is described in the CLHS, which is available on-line: http://www.lisp.org/HyperSpec/FrontMatter/index.html > For complex issues I'd rather have a formal language document that > tells me exactly what's going on, rather than someone blathering for > 50 pages. While the CLHS tells you formally how macros work, it tells you nothing of the philosophy of using them, it tells you nothing about best practice, it tells you nothing about the pitfalls, and so on. Do you really think that you would prefer to try to get an understanding of what macros are, and how you should use them from the CLHS (http://www.lisp.org/HyperSpec/FrontMatter/index.html) than from _On Lisp_ (http://paulgraham.com/paulgraham/onlisp.html) ? I somehow doubt it. > In this case, I merely found it particularly striking that a subject > like file i/o, which would be considered basic and important in most > languages, seemed to be in many Lispers' 'blind spot'. Because it's just not interesting. There are so many interesting things to say and to explain about Lisp. In a language like Java, opening files is just about as difficult a concept as the programmer is likely encounter <0.1 wink>, so Java books describe how to do it. Lisp is by smart people, for smart people who want to solve difficult problems. Opening files is so trivial that it's just not worth wasting ink on it. > Lisp is, without doubt, the most interesting language around in terms > of pure theory. The corollary to that, I guess, is that it attracts a > lot of pure theorists. Common Lisp attracts a lot of people who want to solve difficult programming problems. Please notice this fact. > Not really, no. People think about programs tree-style where certain > control structures occur, and virtually all languages nest at those > points. However, not in cases like assignment and mathematical > expressions, where Lisp would still tend to mandate it. That sort of > deeply nested code is often the most unreadable. This is your opinion from the perspective of never seriously having tried to think about programs as trees. We're back to my original point: don't confuse your opinion formed fromed with lack of experience and imagination with some universal truth. > Also Lisp usually nests somewhat uncomfortably, e.g. in an if > statement > > (if (< i 0) > (* -1 i) > i) > > There's simply no context there for the eye to pick up on. Of course there is. Indentation. (Shouldn't be too hard a concept for a c.l.py reader to grasp). Of course, in a trivial example like this, the indentation level is the same because each of the three constituent parts fits on one line. Try this: (if (this that the other) (foo bar (fubar baz)) (fred bob (bill ben))) (Yes, there is a lot more to be said about this, but I don't propose to do this on c.l.PY) > Nest all of that a couple of layers deeper and it's going to become > annoying. Nope, you look at the indentation, just like in Python. Unlike in Python, my editor is capable of swapping an arbitrarily large consequent with an abitrarily large bloop, with a single keystroke. When you catch on to these possibilities, the prodictivity gaing is huge. > I am not trolling about Lisp, btw. I'm expressing my experiences of > playing around with Lisp as a new language. My intention was more in > the line of amusement. Unfortunately it's a form of amusement _too often_ chosen by ignorant people ... which is a pity, because in doing so they help to perpetuate the myth that what is actually the world's most advanced and practical programming language, is some sort of joke ... thereby helping to keep IT in the dark ages. <0.2 wink> IOW, it's not funny. Pick something else to amuse yourself (like actually learning Lisp, for example :-) > And, frankly, if you think that a mildly sarcastic comment about some > of the learning materials for Lisp, along a bold statement that Lisp > doesn't have the world's most intuitive syntax is a viscous, trollish > slur on the language, justifying random personal attacks, then you > really need to get a freaking life. Too many ignoramuses making too many of these cheap shots ... yes it winds me up. > Lisp pretty much forces you into one way of doing things. Please get a clue before posting such unfounded misinformation. Common Lisp natuarally allows you to program in more different styles that any other language I have come across. > That's a shortcoming, not a feature. It would be, if it were true. > But different problems may - shock - be better expressed through > different languages, and diferent syntaxes. Yes, and Common Lisp - shock - allows you to use any syntax you want. And - shock - even though you can arrange for Lisp to understand _any_ syntax, people usually decide to base their domain-specific syntaxes on s-expressions, because an s-expression based one usually turns out to be the best for the job. Pertinent piece of history: s-expressions were originally not meant for human consumption, something called m-expressions, which were to be the sort of thing that you (and others) claim is the "natural" way of expressing programs, was planned. Shock: the m-expressions never caught on because the s-expressions turned out to be such a wonderful way of writing programs. The programmers didn't want to let go of their lovely, natural s-expressions. From cjw at sympatico.ca Sun Jun 20 14:48:23 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 20 Jun 2004 14:48:23 -0400 Subject: Using metaclasses to play with decorators. In-Reply-To: References: Message-ID: Robert Brewer wrote: > j_mckitrick wrote: > >>You guys are WAY over my head, and I'm supposed to be a C.S. >>junior! :-\ >> >>Could someone give me an idea of what metaclasses and >>decorators _are_? > > > Sure thing. > > >>I think metaclasses are classes with their base methods >>overridden, correct? >> >>And decorators are a form of delegation, right? > > > Oh, and you were doing so well until you guessed... ;) > > >>If so, where am I wrong? And how do these techniques make >>for better code/coding? > > > Metaclasses are mind-demolition tools: > > http://www.python.org/2.2/descrintro.html#metaclasses > > As a CS student, you're probably familiar with the concept of a > 'factory': a block of code which forms objects of a given class. In > Python, classes are also objects. A metaclass can be thought of as a > 'class factory': a factory which produces classes (as opposed to > instances of classes). To say it another way, a class can loosely be > considered a template for objects; a metaclass is a template for > classes. > > Metaclasses allow you to customize the creation of classes. A common use > is when you have a base class, let'a call it A, and you want to provide > a behavior for each subclass "class B(A)", C, D... For example, you > might want to 'register' each subclass in a module-level list. You can > do this without metaclasses: > > class A(object): > pass > > class B(A): > custom_data = {} > > class C(A): > funky_stuff = [] > > subclasses_of_A = [B, C] > > ....but that can get tedious, especially if you aren't writing the > subclasses (perhaps you're writing a framework). Whenever anyone writes > a subclass (perhaps in a different module), they have to remember to > append their new subclass to subclasses_of_A. > > Metaclasses solve this by customizing class-creation code. In our > registration example, we might write: > > subclasses_of_A = [] > > class RegisterA(type): > def __init__(cls, name, bases, dct): > subclasses_of_A.append(cls) > > class A(object): > __metaclass__ = RegisterA > > class B(A): > custom_data = {} > > class C(A): > funky_stuff = [] > > Testing this (we'll save our module as 'metatest.py'), we obtain > (PythonWin 2.3.2): > > >>>>import metatest >>>>metatest.subclasses_of_A > > [, , ] > > When we declare class A, we are creating a new object 'A' which happens > to be a class. By giving it a __metaclass__ attribute, we can customize > the creation of class A. RegisterA doesn't override type.__new__, so > type.__new__ forms the new class as usual. RegisterA does override > __init__, so RegisterA.__init__ gets called with our new (empty) class A > as the first argument, at which point we append metatest.A to our list. > I'll leave you to figure out how to exclude A but keep all the > subclasses ;) Exercise 2 would be to make this mechanism generic (that > is, keep subclasses_of_A separate from subclasses_of_Thing). > > ================================ > > Decorators are a very recent discussion; you might want to browse recent > threads on python-dev for a lot more information. You should certainly > read PEP 318 (http://www.python.org/peps/pep-0318.html). Basically, a > decorator is a way to transform a function. Again, this can usually be > done without metaclasses. The most-frequently-discussed examples are > staticmethods and classmethods: > > class Thing(object): > def newThing(cls, attr): > t = cls() > t.attr = attr > return t > newThing = classmethod(newThing) > > Decorators will hopefully provide a clearer syntax for saying the same > thing (although the exact syntax is still up for debate): > > class Thing(object): > def newThing(cls, attr) [classmethod]: > t = cls() > t.attr = attr > return t > > This moves the transformation ('classmethod') closer to the function > definition, rather than placing it at the end of the function. In > addition, you don't have to write the name 'newThing' three times. Also, > multiple transforms could be defined at once. > > Does that help? > > > Waiting expectantly for a heapin' helpin' of picked nits, > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > I don't wish to pick nits, but to suggest that GVD defined metaclasses as classes whose instances are classes. This seems straighforward. I have yet to wrap my mind around decorators. Colin W From mwh at python.net Thu Jun 17 07:08:46 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jun 2004 11:08:46 GMT Subject: Add methods to int? References: <2jbck8Fv3nqjU1@uni-berlin.de> <2jbg91Fvsfl0U1@uni-berlin.de> <2jbj2dFvou27U1@uni-berlin.de> Message-ID: Peter Otten <__peter__ at web.de> writes: > PS: If you know whether read-only dictionaries are a technical or political > decision, don't hold back to tell us. technical. Cheers, mwh -- I'm not a PSU agent. -- from Twisted.Quotes From russblau at hotmail.com Fri Jun 18 14:48:02 2004 From: russblau at hotmail.com (Russell Blau) Date: Fri, 18 Jun 2004 14:48:02 -0400 Subject: Equation style Message-ID: <2jgrn3F11al7vU1@uni-berlin.de> This is not really a Python question, but it does relate to a Python program I'm working on, so this seems like as good a place as any to ask for suggestions ... I'm working on a GUI application that lets the user enter an alegbraic equation and displays a nicely-formatted representation of the same equation (and then maybe does other stuff with it). The question is: if you have an equation containing terms such as x * y / z, which way of formatting the equation is better (these being pathetic ASCII imitations of what the GUI would display more nicely): y x y x --- or --- ? z z Does your answer depend on whether these symbols represent numbers, constants, or variables? (Obviously, both forms are exactly equivalent mathematically; the question is which one looks better for display purposes.) Any other suggestions on style would be welcome. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From __peter__ at web.de Thu Jun 24 03:31:54 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jun 2004 09:31:54 +0200 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: Kamilche wrote: > was looking for a way to speed up detecting invalid characters in my > TCP string, and thought of yet another use for the translate function! > If you were to 'translate out' the bad characters, and compare string > lengths afterwards, you would know whether or not the line contained > invalid characters. The new method is more than 10x faster than the > standard 'if char in string' test! So - here's the code plus sample > timings: For a fair comparison you should use a dictionary instead of a string for the containment test. Peter From kveretennicov at yahoo.com Wed Jun 9 07:20:41 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 9 Jun 2004 04:20:41 -0700 Subject: Destructors and exceptions References: Message-ID: <5155aad2.0406090320.38977fac@posting.google.com> "Humpty Dumpty" wrote in message news:... > > There is no Python equivalent of C++'s "destructor garanteed to be called > upon scope exit", for a couple of reasons: scope exit only destroys > references to objects, not the objects themselves; destruction of objects is > left to the garbage collector and you have no influence on it. In > particular, the gc is not required to release resources, so finalizers (the > __del__ method, closest to C++'s destructor) may not get called. This means > __del__ is pretty much useless (AFAIMC), and you can't rely on them being > called before program exit (or ever, for that matter). > > I agree, it is a real pitty that Python doesn't have a way of doing what you > mention, other than try-finally, which makes code more difficult to read. A > new specifier, e.g. "scoped", would be a required addtion to Python: > interpreter would garantee that __del__ of scoped objects would be called on > scope exit, and raise an exception if attempt to alias. > Is there a PEP or something for "scoped specifier"? - kv From tjreedy at udel.edu Tue Jun 15 23:29:22 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jun 2004 23:29:22 -0400 Subject: (OT) Boa Constructor and Python 2.3.4 References: Message-ID: "flupke" wrote in message news:f%zzc.96$Ow7.58431618 at hebe.telenet-ops.be... > C:\Python23>C:\Python23\python.exe > C:\Python23\Lib\site-packages\wxPython\tools\boa\boa.py > Starting Boa Constructor v0.2.8 > importing wxPython > reading user preferences Comments based on traceback and no knowledge of boa specifically. Since you just asked for 'ideas' without giving specific questions or where you get lost, I have to make some guesses. > Traceback (most recent call last): > File "C:\Python23\Lib\site-packages\wxPython\tools\boa\boa.py", line 231, > in ? > import Preferences, Utils, About > File "C:\Python23\Lib\site-packages\wxPython\tools\boa\Preferences.py", > line 130, in ? > execfile(file) This executes 'file', which I presume is prefs.rc.py, *in* the current (Preferences) module. Preferences.py must either define or import the constants used in 'file'. > File > "C:\Python23\Lib\site-packages\wxPython\tools\boa\Config\prefs.rc.py", line > 25, in ? > splitterStyle = wxCLIP_CHILDREN | wxSP_LIVE_UPDATE | \ This line appears to be continued to another line, which presumably or's in more constants, but traceback printer does not pick that up. > NameError: name 'wxSP_FULLSASH' is not defined I would report this to boa people. In meanwhile, to get going, I would find where constants are defined and add missing definition -- or remove use of it. Terry J. Reedy From peufeu at free.fr Thu Jun 24 16:30:59 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Thu, 24 Jun 2004 22:30:59 +0200 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: Blowfish encryption is very secure (128 bits) and very fast (10 megabytes/s on a Celeron 400). I used that, you could try it. On Thu, 24 Jun 2004 14:53:14 -0400, Peter Hansen wrote: > Till Plewe wrote: >> On Wed, Jun 23, 2004 at 12:50:39AM -0400, Peter Hansen wrote: >>> Besides, what you say is not possible. On my machine, >>> which is about a P4 2500MHz, scanning an array.array('c') with >>> 22MB of data in it, doing nothing but reading each byte and >>> ignoring it, takes about 8 seconds. So does converting the >>> array to a list, which is pretty much all C code. >> are you sure it takes 8s? > > What I meant (but didn't state explicitly) was that even if you > convert the string to a list of 23068672 individual characters, > scanning the list takes about as long as scanning the array > did. > > And not only did I not say all that, but what I did say I > even said wrong, since I notice I said "array to list" > instead of "string to list". > > Basically, I've been totally wrong in everything I said > in this thread. ;-) > > -except-this-post-ly y'rs, > Peter -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From alloydflanagan at comcast.net Tue Jun 22 10:28:20 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 22 Jun 2004 07:28:20 -0700 Subject: Python and MP3 References: Message-ID: O-Zone wrote in message news:... > Hi all, > i'm looking for an MP3 player/library in Python/wxPython to use in a > multiplatform program. Someone can help me ? > > Oz I haven't looked for a player, but you may be interested in a library for reading/editing the information tags that are part of MP3 files: http://pyid3lib.sourceforge.net/. This is where things like the song title, album, artist, etc. are stored. From dcsmpayne at bigpond.com Mon Jun 14 06:34:23 2004 From: dcsmpayne at bigpond.com (news) Date: Mon, 14 Jun 2004 10:34:23 GMT Subject: Silly question; best way to run a python program from Vim? References: Message-ID: You have to tell vim you want it to treat what you type as a command. Enter command mode by typing : and allow vim to execute by adding ! directly after, then type the program eg :! hi_lowgame.py will run the hi_lowgame I have coded from inside vim. regards Darren "Kenneth McDonald" wrote in message news:slrnccl20h.12c.kenneth.m.mcdonald at g4.gateway.2wire.net... > After looking around at various editors, I've finally decided on > (I think :-) ) Vim for my future work. (jed is a great editor, > but doesn't do neat things like allow me to write python code > to add to the editor functionality. Emacs is just too bloated > these days. jEdit is one of the best GUI editors I've seen, but > I've still not seen a GUI editor with the power of those with > a non-GUI ancestry. etc. etc.) > > However, I can't quite figure out how one 'should' excute > the Python program one is currently working on in Vim. I'm > aware of the :python and :pyfile commands, but they seem to > be oriented towards running scripts which are intended to > do editing tasks, i.e. which interact with Vim. I simply want > to do something like > > :runthissucker > > to execute the current file under python, pop up a window > with the results, automatically take me to the point in > the buffer (or other file) where an error was encountered, > etc. In other words, I want to run the program as part of > the development process of that program, not as an addon to > Vim. (Looking back, that isn't terribly clear, but it's about > as clear as I can think to make it right now.) Using 'jed' > and the standard jed python mode, this was just '^C^C', but > from what I understand of the python functionality of > Vim, I currently have to do something like > > :python my_file.py > > Thanks for the help. Of course, if you have other useful > suggestions for using Vim with Python, please feel free > to contribute those also. > > Cheers, > Ken From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 10 11:02:02 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 10 Jun 2004 17:02:02 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B74201634F33@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = nirarbel at yifan.net Recipient(s) = python-list at python.org; Subject = Information Scanning time = 06/10/2004 17:02:02 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment Notice.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From claudiac at ltid.inpe.br Fri Jun 25 15:03:15 2004 From: claudiac at ltid.inpe.br (=?iso-8859-1?Q?Cl=E1udia?= Cristina dos Santos) Date: Fri, 25 Jun 2004 16:03:15 -0300 Subject: Problem f2py Message-ID: <40DC76F3.FF7628B7@ltid.inpe.br> Dear Friends, I?m trying to run Python in window XP PC. Please advise-me on how to deal with the following errors: C:\Python234>f2py -c -m hello hello.f running build running config_fc running build_src building extension "hello" sources f2py:> c:\docume~1\mctinp~1\config~1\temp\tmpols7pt\src\hellomodule.c creating c:\docume~1\mctinp~1\config~1\temp\tmpols7pt creating c:\docume~1\mctinp~1\config~1\temp\tmpols7pt\src Reading fortran codes... Reading file 'hello.f' Post-processing... Block: hello Block: foo Building modules... Building module "hello"... Constructing wrapper function "foo"... foo(a) Wrote C/API module "hello" to file "c:\docume~1\mctinp~1\config~1\temp\t mpols7pt\src/hellomodule.c" adding 'c:\docume~1\mctinp~1\config~1\temp\tmpols7pt\src\fortranobject.c' to s ources. adding 'c:\docume~1\mctinp~1\config~1\temp\tmpols7pt\src' to include_dirs. copying C:\PYTHON~2\lib\site-packages\f2py2e\src\fortranobject.c -> c:\docume~1\ mctinp~1\config~1\temp\tmpols7pt\src copying C:\PYTHON~2\lib\site-packages\f2py2e\src\fortranobject.h -> c:\docume~1\ mctinp~1\config~1\temp\tmpols7pt\src running build_ext error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. Thanks for your help. Claudia. From peter at engcorp.com Wed Jun 16 22:21:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 22:21:45 -0400 Subject: Regular expression, "except end of string", question. In-Reply-To: References: Message-ID: Derek Basch wrote: > Thanks Peter and David, > > It always comforting to know that a really simple solution exists after > you waste a couple of hours messing with Regular Expressions. :) And, usually, there's an even simpler solution than the first couple of responses, as David #2 showed. :-) His has the added advantage of not building a temporary list too. -Peter From http Thu Jun 24 01:11:52 2004 From: http (Paul Rubin) Date: 23 Jun 2004 22:11:52 -0700 Subject: Obtaining Webpage Source with Python References: <6962d028.0406232103.6f5d9f7f@posting.google.com> Message-ID: <7xy8mdee07.fsf@ruckus.brouhaha.com> ryan at ryankaskel.com (Ryan Kaskel) writes: > Something like: > > pyPage = open('http://www.python.org/index.html',r).read() > > Obviously that won't work but how can I do something to that effect? import urllib pyPage = urllib.urlopen('http://www.python.org/index.html',r).read() From __peter__ at web.de Sat Jun 26 18:15:48 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Jun 2004 00:15:48 +0200 Subject: Is there a more elegant way to do this? References: <889cbba0.0406261358.6bc18e1d@posting.google.com> Message-ID: Kamilche wrote: > ''' > Is there a more elegant way of doing this? > I would like to have the arguments to pack > automatically taken from lst. > ''' > > def pack(self): > lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \ > 'green', 'blue', 'size', 'rotate', 'translucency'] > return struct.pack(' self.id, self.parent, self.number, \ > self.x, self.y, self.z, \ > self.red, self.green, self.blue, \ > self.size, self.rotate, self.translucency) There is an alternative struct.pack(" Is it true that joining the string elements of a list is faster than concatenating them via the '+' operator? "".join(['a', 'b', 'c']) vs 'a'+'b'+'c' If so, can anyone explain why? \\ jonas galvez // jonasgalvez.com From klachemin at home.com Wed Jun 2 02:22:06 2004 From: klachemin at home.com (Kamilche) Date: 1 Jun 2004 23:22:06 -0700 Subject: Python Only 30% Slower than C In Certain Cases Message-ID: <889cbba0.0406012222.19550dc9@posting.google.com> I have a very unusual application written in C, one which uses dictionaries for all data storage, and a unique file structure. After staring at a current task for a bit, I decided I REALLY wanted to pass the arguments as dictionaries, as well. I knew Python, and realized this application was screaming to be written in Python. It's a non trivial application - it emulates Python inheritance by loading text files at runtime. It uses a single generic object, and several lookup tables in memory. I finally got it to the point where it can create objects, and store them in the table, so I performed my first timing test. I was VERY surprised to discover that the C program created 40,000 objects per second, and the Python version created 28,000 objects per second! Plus, the memory footprint was less. This test was done with the debug version of the C program. The release version showed it was about 12x faster than Python, with a smaller memory footprint. Still, that's more impressive than I had thought. I recreated the wheel when making this app in C, setting up the memory management, hash tables, and all... the design is nice and the class structures are easily modified outside the program, and I was willing to trade speed for this flexibility. How far am I willing to trade? Ooh, this is tempting, to code the application in Python, instead of using it as a prototyping tool I'll just play with it a bit longer, code up the rest of the functionality and run some more timings. I must say, development speed with Python blows C out of the water, by MORE than a factor of 15. --Kamilche From amk at amk.ca Wed Jun 2 09:21:16 2004 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 02 Jun 2004 08:21:16 -0500 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: On Wed, 02 Jun 2004 12:27:43 +0200, David Fraser wrote: > It looks cool because it doesn't embed Python code in the template. > Do any of the other frameworks have this approach? Quixote's PTL embeds the template in Python code. Using the example given elsewhere in this thread: from quixote.html import href def page [html] (title, links): '' '%s' % title ... for link in links: '
  • ' href(link.href, link.text) '
  • ' ... See http://www.mems-exchange.org/software/quixote/doc/PTL.html for details. --amk From peter at engcorp.com Tue Jun 29 18:37:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 18:37:10 -0400 Subject: wxPython support non-GUI classes from wxWidgets? In-Reply-To: References: Message-ID: USCode wrote: > "Peter Hansen" wrote > >>The docs, somewhere, note that primarily only the functionality that >>is *not* duplicated by existing Python functionality is provided. >>I believe that includes at least XML, threading, and anything to do >>with networking, and probably other things. (Going entirely by >>memory here, from the last time I read this stuff, well over a >>year ago. I can find the exact location of the notes, if you aren't >>able to.) >> > > Thanks Peter. I guess what confused me was that the wxPython doc refers to > the wxWidgets doc as it's official documentation. But elsewhere on the > wxPython site it implies that only the GUI wxWidget functionality has Python > wrappers provided. Is there a list somewhere of all the wxWidget classes > that have wxPython wrappers currently available? That could be a good question for the wxPython mailing list. :-) In lieue of other info, the directories in the wxPython installation would probably be pretty revealing in that respect, if not comprehensive. -Peter From fumanchu at amor.org Thu Jun 3 16:27:25 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 3 Jun 2004 13:27:25 -0700 Subject: Perlish dictionary behavior Message-ID: Chris wrote: > One nice thing about Perl that is helpful when tallying things up by > type is that if you increment a hash key and the key does not exist, > Perl puts a one there. So you can have code that does something like > this: > > my %thingCounts; > foreach my $thing() > { > $thingCounts{$thing}++; > } >8 > Is there any clever way to be able to just say, like in Perl, > for thing in file: > thingCounts[thing] += 1 > > and have it do the above? Perhaps with a custom dictionary class or > something? Just wondering what that might look like. Here's one way: >>> class AllThingsStartAtZero(dict): ... def __getitem__(self, key): ... return dict.get(self, key, 0) ... >>> thingCounts = AllThingsStartAtZero() >>> for thing in ('a', 'b', 'c', 'd', 'a'): ... thingCounts[thing] += 1 ... >>> thingCounts {'a': 2, 'c': 1, 'b': 1, 'd': 1} Notice that a actually does get 'incremented twice'. Robert Brewer MIS Amor Ministries fumanchu at amor.org From martin at v.loewis.de Tue Jun 1 18:38:28 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jun 2004 00:38:28 +0200 Subject: terminological obscurity In-Reply-To: References: <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> <40b83034$0$27038$9b622d9e@news.freenet.de> <40b931c8$0$24826$9b622d9e@news.freenet.de> Message-ID: <40BD0564.5090002@v.loewis.de> Arthur wrote: > "Is green" doesn't help us if the list does not cohere around the > concept of color. Correct. Any kind of predicate involving functions requires that a certain base domain is used on which these functions are total. > And the above sentences implies, and I could independently imagine, a > list might cohere around nothing more then the concept of existence. Correct. Of course, people typically collect things in a collection to have algorithms operate on the elements of a collection, so a collection of all things that exist would not be useful, and would be difficult to create. > But of course the possbility of including non-exitence data does not > exist. Which makes the notion of homogeneity around that concept > meaningless. Indeed. > So I have, after consideration, decided to outlaw, if not the > terminolkgy itself (even its its most general form), than at least my > own efforts to find meaning in it. You find the term "color" meaningless because there are things it doesn't apply to? Is there any term in the universe (or, perhaps even in the English language) that you find meaningful? Regards, Martin From lbates at swamisoft.com Thu Jun 3 17:15:35 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 16:15:35 -0500 Subject: Anybody seen a misspelled variable name finder tool? References: Message-ID: http://pychecker.sourceforge.net/ Larry Bates Syscon, Inc. "Robert Oschler" wrote in message news:KoMvc.2548$1s1.212 at bignews4.bellsouth.net... > One of the recurring bugs I find in my program, is a bug due to a > misspelling of a variable name. Is there a code checker out there that can > help find these critters? If so, URL's please. > > Thanks. > > -- > Robert > > From eurleif at ecritters.biz Wed Jun 23 21:30:20 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 23 Jun 2004 21:30:20 -0400 Subject: vb mixed python programming In-Reply-To: References: Message-ID: <2jup5cF15siiiU1@uni-berlin.de> dm wrote: > I want to program using VB mixed python. who have any experience? and hwo > to do ? I haven't done it personally, but http://www.hps1.demon.co.uk/users/andy/pyvb/ looks useful. From aahz at pythoncraft.com Mon Jun 14 17:27:33 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2004 17:27:33 -0400 Subject: thread help References: Message-ID: In article , Bart Nessux wrote: > >I'm no expert on threading, far from it. Could someone show me how I can >make this work correctly? I want to probe 64 unique IP address for HTTP >servers simultaneously, not the same IP addy 64 times (as I'm doing >now). Any tips would be much appreciated. Create a threading.Thread subclass that takes one IP address and a list of ports to scan. Start 64 instances of this class, each with a different IP address. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From lbates at swamisoft.com Sun Jun 20 09:03:18 2004 From: lbates at swamisoft.com (Larry Bates) Date: Sun, 20 Jun 2004 08:03:18 -0500 Subject: Graph API / framework References: <40d4729e$1@rutgers.edu> Message-ID: You might want to review ReportLab. It has a very nice graphing API. www.reportlab.org HTH, Larry Bates Syscon, Inc. "George Sakkis" wrote in message news:40d4729e$1 at rutgers.edu... > Does anyone know of a good graph API ? The only one I found for Python is > part of kjbuckets > (http://starship.python.net/crew/aaron_watters/kjbuckets/kjbuckets.html), > but I was looking for something more sophisticated; I am more concerned > about elegance and extensibility than top performance. JUNG > (http://jung.sourceforge.net/doc/manual.html) for java looks more promising. > Does anyone have experience with it or some other relevant framework ? > Thanks, > > George > > From John_Dutcher at urmc.rochester.edu Fri Jun 4 14:05:26 2004 From: John_Dutcher at urmc.rochester.edu (John F Dutcher) Date: 4 Jun 2004 11:05:26 -0700 Subject: urllib2.urlopen(req) error........ Message-ID: <2c82369d.0406041005.799cc86d@posting.google.com> Can anyone comment on why the code shown in the Python error is in some way incorrect...or is there a problem with Python on my hoster's site ?? The highlites don't seem to show here...but line #80 and line # 38 are the first line offenders. --> --> --> HTTPError Python 2.2.2: /usr/bin/python Fri Jun 4 13:58:00 2004 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /home/euromill/public_html/scgi-bin/euro3.py 78 write_dig_err(ls) 79 x = x + 1 80 process_request(ls) 81 82 process_request = , ls = ['johnfdutchfrederic', ['77', '77', '77', '77', '77', '77', '77'], 'EuroMillions', '5', 'error'] /home/euromill/public_html/scgi-bin/euro3.py in process_request(ls=['johnfdutchfrederic', ['77', '77', '77', '77', '77', '77', '77'], 'EuroMillions', '5', 'error']) 36 req = urllib2.Request(url='http://www.euromillions.us/scgi-bin/euro8.py', \ 37 data = strdata) 38 f = urllib2.urlopen(req) 39 print "Content-type: text/html\n\n" 40 print f.read() f undefined, global urllib2 = , urllib2.urlopen = , req = /usr/lib/python2.2/urllib2.py in urlopen(url=, data=None) 136 if _opener is None: 137 _opener = build_opener() 138 return _opener.open(url, data) 139 140 def install_opener(opener): global _opener = , _opener.open = >, url = , data = None /usr/lib/python2.2/urllib2.py in open(self=, fullurl=, data=None) 320 type_ = req.get_type() 321 result = self._call_chain(self.handle_open, type_, type_ + \ 322 '_open', req) 323 if result: 324 return result req = /usr/lib/python2.2/urllib2.py in _call_chain(self=, chain={'do': [, ], 'file': [], 'ftp': [], 'http': [], 'https': [], 'proxy': [], 'unknown': []}, kind='http', meth_name='http_open', *args=(,)) 299 func = getattr(handler, meth_name) 300 301 result = func(*args) 302 if result is not None: 303 return result result undefined, func = >, args = (,) /usr/lib/python2.2/urllib2.py in http_open(self=, req=) 788 789 def http_open(self, req): 790 return self.do_open(httplib.HTTP, req) 791 792 self = , self.do_open = >, global httplib = , httplib.HTTP = , req = /usr/lib/python2.2/urllib2.py in do_open(self=, http_class=, req=) 782 return addinfourl(fp, hdrs, req.get_full_url()) 783 else: 784 return self.parent.error('http', req, fp, code, msg, hdrs) 785 786 self = , self.parent = , self.parent.error = >, req = , fp = ', mode 'rb'>, code = 500, msg = 'Internal Server Error', hdrs = /usr/lib/python2.2/urllib2.py in error(self=, proto=500, *args=({301: [], 302: [], 'default': []}, 'default', 'http_error_default', , ', mode 'rb'>, 500, 'Internal Server Error', )) 346 if http_err: 347 args = (dict, 'default', 'http_error_default') + orig_args 348 return self._call_chain(*args) 349 350 # XXX probably also want an abstract factory that knows things like self = , self._call_chain = >, args = ({301: [], 302: [], 'default': []}, 'default', 'http_error_default', , ', mode 'rb'>, 500, 'Internal Server Error', ) /usr/lib/python2.2/urllib2.py in _call_chain(self=, chain={301: [], 302: [], 'default': []}, kind='default', meth_name='http_error_default', *args=(, ', mode 'rb'>, 500, 'Internal Server Error', )) 299 func = getattr(handler, meth_name) 300 301 result = func(*args) 302 if result is not None: 303 return result result undefined, func = >, args = (, ', mode 'rb'>, 500, 'Internal Server Error', ) /usr/lib/python2.2/urllib2.py in http_error_default(self=, req=, fp=', mode 'rb'>, code=500, msg='Internal Server Error', hdrs=) 398 class HTTPDefaultErrorHandler(BaseHandler): 399 def http_error_default(self, req, fp, code, msg, hdrs): 400 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 401 402 class HTTPRedirectHandler(BaseHandler): global HTTPError = , req = , req.get_full_url = >, code = 500, msg = 'Internal Server Error', hdrs = , fp = ', mode 'rb'> HTTPError: HTTP Error 500: Internal Server Error _HTTPError__super_init = ', mode 'rb'>>> __del__ = ', mode 'rb'>>> __doc__ = 'Raised when HTTP error occurs, but also acts like non-error return' __getitem__ = ', mode 'rb'>>> __init__ = ', mode 'rb'>>> __module__ = 'urllib2' __repr__ = ', mode 'rb'>>> __str__ = ', mode 'rb'>>> close = ', mode 'rb'>>> code = 500 filename = 'http://www.euromillions.us/scgi-bin/euro7.py' fileno = fp = ', mode 'rb'> geturl = ', mode 'rb'>>> hdrs = headers = info = ', mode 'rb'>>> msg = 'Internal Server Error' read = readline = readlines = url = 'http://www.euromillions.us/scgi-bin/euro7.py' From emcpeters at anacapasciences.com Fri Jun 25 01:11:35 2004 From: emcpeters at anacapasciences.com (Evan McPeters) Date: Thu, 24 Jun 2004 22:11:35 -0700 Subject: Python Instant Messenger Example Message-ID: <40dbb408$1@newsfeed.netlojix.com> Does anyone have an example of a simple Instant Messenger program written in Python? I have some code for a simple server and simple client communicating over TCP/IP, so I could always combine both of those into each IM client, but perhaps there is a better way. Thank you. From nun at meyl.com Fri Jun 18 08:31:42 2004 From: nun at meyl.com (Mitja) Date: Fri, 18 Jun 2004 14:31:42 +0200 Subject: Parsing by Line Data References: Message-ID: <_eBAc.5092$37.671800@news.siol.net> python1 (news:casjot020q7 at enews3.newsguy.com) wrote: > Having slight trouble conceptualizing a way to write this script. The > problem is that I have a bunch of lines in a file, for example: > > 01A\n > 02B\n > 01A\n > 02B\n > 02C\n > 01A\n > 02B\n > . > . > . > > The lines beginning with '01' are the 'header' records, whereas the > lines beginning with '02' are detail. There can be several detail > lines > to a header. > > I'm looking for a way to put the '01' and subsequent '02' line data > into one list, and breaking into another list when the next '01' > record is found. I'd probably do something like records = ('\n'+open('foo.data').read).split('\n01') You can later do structured=[record.split('\n') for record in records] to get a list of lists. '01' is stripped from structured[0] and there may be other flaws, but I guess the concept is clear. > How would you do this? I'm used to using 'readlines()' to pull the > file data line by line, but in this case, determining the break-point > will > need to be done by reading the '01' from the line ahead. Would you > need > to read the whole file into a string and use a regex to break where a > '\n01' is found? From pete.prodoehl at cygnusinteractive.com Wed Jun 2 16:55:00 2004 From: pete.prodoehl at cygnusinteractive.com (Pete Prodoehl) Date: Wed, 02 Jun 2004 15:55:00 -0500 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: <69cbbef2.0406021106.c393f20@posting.google.com> References: <69cbbef2.0406010619.7cd39e71@posting.google.com> <69cbbef2.0406021106.c393f20@posting.google.com> Message-ID: <40BE3EA4.7020107@cygnusinteractive.com> has wrote: > Pete Prodoehl wrote in message news:... > >>The nice thing about this is that once you learn the templating tags, it >>doesn't matter what language you use, so you could change the backend >>from Perl to Python and not even have to change any of your templates. > > > I've heard this said before, but am curious just how much of an > advantage it really is? I'd have thought reimplementing an entire > backend would be a much bigger task than porting templates and a > relatively rare occurence in practice; not sufficient in itself to > justify learning a second language in the first place. Anyone got any > practical experience in this and can comment? Oh, you want *practical* experience eh? ;) I would think the "theory" is that you've got designers/authors working on templates, who don't know code. They know HTML, and know CSS, but they do not program or know any code. You give these people templates to work on. You, being a top-notch developer, can implement a system in Perl, Python, Ruby, PHP, etc, and as long as you stick to using the HTML-Template system appropriate for each language, your designers/authors never need to change their templates or learn Yet Another Templating System. Another successful separation of logic from presentation... or so the theory goes... ;) Pete From http Fri Jun 25 18:04:54 2004 From: http (Paul Rubin) Date: 25 Jun 2004 15:04:54 -0700 Subject: z80 vs Python References: Message-ID: <7xpt7n8fax.fsf@ruckus.brouhaha.com> Phil Frost writes: > Actually, the 286 is essentially a 32 bit processor. It has most of the > features of the 386, only many of the control structures such as the GDT > are different, as well as the memory bus. Huh? The 286 has memory protection and 386-like segment descriptors, but it's a 16 bit processor through and through. It has a 16-bit ALU with 16-bit registers, and addresses within a segment are 16 bits. Yes, there were versions of Unix that ran on it, which isn't too surprising given Unix's origins in the 16-bit PDP-11 world. I'm not aware of a Linux port to it, unless you mean something like ucLinux. From bhoel at web.de Wed Jun 9 15:25:54 2004 From: bhoel at web.de (Berthold Höllmann) Date: Wed, 09 Jun 2004 21:25:54 +0200 Subject: Can (should) this be rewritten without exec? Message-ID: Hello, I do need some code that does someting like --- snip --- class X(object): def a(*arg, **kw): """This is test a""" print "func a", arg, kw a=staticmethod(a) def b(*arg, **kw): """This is test b""" print "func b", arg, kw b=staticmethod(b) def __wrapper(func, *arg, **kw): func.__doc__ print "start wrapper" func(*arg, **kw) print "done wrapper" for c in ['a', 'b']: exec "%s = lambda *arg, **kw : __wrapper(X.%s, *arg, **kw)" % (c, c) exec "%s.__doc__ = X.%s.__doc__" % (c, c) print a.__doc__ a(1, 2, 3, d=4, e=5, f=6) b(1, 2, 3, d=4, e=5, f=6) --- snap --- Can this be rewritten without using 'exec'. In my real case 'X' is an extension module if that matters. Thanks Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From fishboy at spamspamspam.com Sat Jun 5 22:47:11 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 02:47:11 GMT Subject: exec throws an exception...why? References: Message-ID: <3415c0lg306oec1a69c3mkolnbhfbku243@4ax.com> On 5 Jun 2004 18:46:11 -0700, nicksjacobson at yahoo.com (Nick Jacobson) wrote: >This works fine: > >x = 1 >def execfunc(): > print x >execfunc() > >So why doesn't this? > >s = \ >""" >x = 1 >def execfunc(): > print x >execfunc() >""" > >codeobj = compile(s, "", "exec") >d = {} >e = {} >exec codeobj in d, e > >Error message: >Traceback (most recent call last): > File "C:\Nick\proj\python1.py", line 17, in ? > exec codeobj in d, e > File "", line 6, in ? > File "", line 5, in execfunc >NameError: global name 'x' is not defined > >I'm using ActiveState Python 2.3.2 on Windows XP Pro. Thanks! > >P.S. It does work if I say >exec codeobj in d >but I don't understand why. It works because the local and global namespaces are both 'd'. it doesn't work in the first because it puts 'x' in the local and then looks in global. Now, why it puts 'x' in local, I don't know. If this was a quiz, I'd put "Nested Scope" and pray. ><{{{*> From rnd at onego.ru Sat Jun 5 13:15:50 2004 From: rnd at onego.ru (Roman Suzi) Date: Sat, 5 Jun 2004 21:15:50 +0400 (MSD) Subject: #! shbang for pyc files? In-Reply-To: References: Message-ID: On Sat, 5 Jun 2004, Christian Gudrian wrote: Then why not just use a wrapper Python program which imports module and runs "main" function? >"MarkV" schrieb: > >> .py extension to run it - just type "whatever" - but when you compile the >> file, it loses this ability! > >Write a wrapper script: > >#!/bin/sh >python mycompiledpythonprogram.pyc > >Christian > > > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From aweil at mail.ru Mon Jun 28 22:15:04 2004 From: aweil at mail.ru (alejandro david weil) Date: Mon, 28 Jun 2004 23:15:04 -0300 Subject: Speed of str(positive_integer).. In-Reply-To: References: Message-ID: <200406282315.04537.aweil@mail.ru> On Mon June 28 2004 21:22, Christopher T King wrote: > On Mon, 28 Jun 2004, alejandro david weil wrote: > > *The thrid test is using divmod() that i thought that would be > > faster (i thought it could make only one division and get both > > qoutient and remainder, without having to multiply..) but > > was worse. > > PS: I want a faster divmod! :-) > > I was going to say that divmod was slower because it performs float > division instead of the integer division of // (which is true), but I'm > guessing the slowdown comes from the extra dictionary lookup needed for > divmod (unless this is somehow optimized away) instead. If that's indeed But both versions with and without divmod uses the same list lookup ( or there's something that i didn't see..). > true, then it seems that divmod doesn't adequately perform its intended > purpose, i.e. make use of the FPU's ability to divide and modulusify in > one step to gain speed. If it's ability is to use fpu, it's ok that fails.. but, for integers it can use standard i286 div instruction set (well I tried it only in x86, and also, I think that Psyco works only there, so, it should be supposed from begining), with does the same. Saludos, alejandro -- + There is no dark side of the moon really. Matter of fact it's all dark. From russblau at hotmail.com Wed Jun 9 11:03:47 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 9 Jun 2004 11:03:47 -0400 Subject: division bug? References: <964246.0406090655.7e190def@posting.google.com> Message-ID: <2ion6jFpc8l2U1@uni-berlin.de> "Milan" wrote in message news:964246.0406090655.7e190def at posting.google.com... > a program: > > a=10 > b=5 > print a/b > > and its result: 0. If you run the program, you see always a sero (0), > but 10/5 is 2. Who can help me? Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> a = 10 >>> b = 2 >>> print a/b 5 What version are *you* running? -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From michael at foord.net Mon Jun 7 04:33:18 2004 From: michael at foord.net (Fuzzyman) Date: 7 Jun 2004 01:33:18 -0700 Subject: ANN : filestruct and splitter Message-ID: <8089854e.0406070033.96cda7b@posting.google.com> filestruct filestruct is both a command line tool and a library of functions (well - a couple of classes really). http://www.voidspace.org.uk/atlantibots/pythonutils.html#fsdm As a command line tool it will do 'remote-directory syncs'. It will profile a directory, then reprofile and record all changes into a single zip file. It can then use that zip file to make the same set of changes on a remote copy of the file structure. Useful when you maintain two copies of the same file structure in different locations. (I work on various projects at home and at work). As a library of functions it has the ability to profile file structures producing a directory object - DirObj. This can write out the description as a markup language (FSDM - file structure description markup), and read it in to recreate the DirObj. It can then compare this with the current state of the file structure. This could also be the basis of, for example, an incremental archive, version control system etc In fact anything where changes to a file system need to be monitored. Full docs of course.... Splitter http://www.voidspace.org.uk/atlantibots/pythonutils.html#splitter This is a piece of code that has been written various times by many people - but dammit python makes this kind of hacking so much fun ! It's a simple class that can split files and recombine them automatically, with various attributes to control how it does it. Regards, Fuzzyman -- http://www.Voidspace.org.uk The Place where headspace meets cyberspace. Online resource site - covering science, technology, computing, cyberpunk, psychology, spirituality, fiction and more. --- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera From martin at v.loewis.de Sun Jun 27 03:56:53 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 27 Jun 2004 09:56:53 +0200 Subject: suse 9.1 and 64 In-Reply-To: References: Message-ID: <40de7dc6$0$13018$9b622d9e@news.freenet.de> Terry Reedy wrote: > I believe the main difference from the Python viewpoint is 64 instead of 32 > bit ints and everything that follows from that. For instance, type(2**60), > is int instead of long. Maybe someone else knows more. In addition, Python, in 64-bit mode, will use 64-bit addresses. That means it can address more that 4GB of main memory. Actually, the limitation on 32-bit systems is often 2GB, which 64-bit Python helps to overcome. Unfortunately, Python still won't support sequence indexes above 2**31, so you still can't have lists with more than 2**31 items (but such a list would consume 8GB of main memory for the pointers to the list items alone, plus memory for the actual objects). More unfortunate is that it won't deal with strings larger than 2GB, either. Regards, Martin From joewong at mango.cc Tue Jun 1 22:37:21 2004 From: joewong at mango.cc (Joe Wong) Date: Wed, 2 Jun 2004 10:37:21 +0800 Subject: strange socket behaviour Message-ID: <027501c4484a$88251d50$7f00a8c0@scl01.siliconcreation.com> Hello, I have a short program that the client make a connection to server, a thread is then created to poll any data sent from the server. The main thread will close the socket after 5 seconds. Here are the code: from socket import * import select import threading import time def poll(c): i, o, e = select.select([c], [], []) if not i: print "time out" return print i data = i[0].recv(1024) print "data: ", data if __name__=="__main__": c = socket(AF_INET, SOCK_STREAM) c.connect(('192.168.100.74', 8888)) th=threading.Thread(None, poll, "", (c, )) th.setDaemon(1) th.start() time.sleep(5) c.shutdown(2) c.close() th.join() print "completed" On Windows, as soon as client socket 'c' is closed, the select() call returns. However, on Linux, the program seems blocking forever ( may be I am not patient to wait ). Is there anything wrong with my code? Regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From P at draigBrady.com Fri Jun 25 12:26:01 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Fri, 25 Jun 2004 17:26:01 +0100 Subject: A better popen2 In-Reply-To: References: <40DB2889.60808@draigBrady.com> Message-ID: <40DC5219.6070907@draigBrady.com> Donn Cave wrote: > In article <40DB2889.60808 at draigBrady.com>, P at draigBrady.com wrote: > ... > >>http://www.pixelbeat.org/libs/subProcess.py >> >>Perhaps this could be included in commands.py for e.g.? > > > It looks pretty good to me. A couple of minor points: > > - dup2(a, sys.stdout.fileno()) -> dup2(a, 1) doh! of course. I hate magic numbers but what I did was certainly wrong. > - execvp('/bin/sh', ['sh', '-c', cmd]) > > I think that could be just execv(), since you've > supplied a path already. But I really prefer the > way Popen3 does it, where the input parameter is > argv, not a shell command (and you do use execvp.) I just copied the way Popen3 did it? > Of course you can supply ['sh', '-c', cmd] as that > parameter, but for me it's more often the case that > the parameters are already separate, and combining > them into a shell command is unnecessary and risky. > (Don't support both, like Popen3 does - that was a > mistake that seems to routinely leave people confused > about how it works.) fair enough. > And I haven't really tried to verify the logic or anything, > but it does look like the right idea to me. > > I will at least add it to my collection. I don't have > it at hand and haven't looked at it for a while, but > at one time I was thinking I would put together every > one of these things that has come across comp.lang.python, > might be a dozen or so but I don't think I have them all > yet. (I don't think I have "task", good find.) > > The most conspicuous recent one was (I think) called > popen5, and rumor has it, will be standard with 2.4, > and will have the select functionality you need, not > only on UNIX but also on Windows, where it isn't so > trivial a feat. Cool! I missed that: http://www.python.org/peps/pep-0324.html I had a 10 second look at process.Popen.communicate() and it seems to do much the same as I did, however it's missing a timeout parameter like I implemented which I think is important. > Other than the platform dependency issues, I think > the main reason this wasn't in the core library from > the beginning is that the problem is more complicated > than the solution, if you know what I mean. Or, each > programmer's itch seems to be in a slightly different > place. I aggree that the appropriate interface is hard to define however I think we all agree that popen2 is definitely not it. thanks a million, P?draig. From reiner.block at bisoft.de Thu Jun 3 15:55:42 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Thu, 03 Jun 2004 21:55:42 +0200 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: <2i9e1tFkjtj8U1@uni-berlin.de> Hi, sorry, my question was not detailed enough. It is not Python itself, it is the library documentation. So e.g. spawnlp is described with the header "spawnlp(mode,file,...)". In the example later you can see ----------------------------------------------------------------------- import os os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') ----------------------------------------------------------------------- There is no further explaination why there are suddenly two times 'cp'! The first says the first parameter is the mode like P_WAIT or P_NOWAITE. That's clear. But the second should be the program to start and the third...? :-( It is not clear why the 2nd and 3rd parameter are the same. HTH Searching greetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From roy at panix.com Thu Jun 24 18:38:40 2004 From: roy at panix.com (Roy Smith) Date: Thu, 24 Jun 2004 18:38:40 -0400 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> <4d79c4d9.0406240854.13489b48@posting.google.com> Message-ID: In article , Les Smithson wrote: > >>>>> "Matthew" == Matthew Bell writes: > > Matthew> I have found any number of native COM/.NET/ASP/etc C++ > Matthew> SNMP toolkits and tried using the Python Win32 extensions > Matthew> to talk to them but I just don't understand enough about > Matthew> low-level Win32 calls, event handling etc to get them to > Matthew> work, particularly as the code examples typically expect > Matthew> you to either be using Visual C++ or Visual Basic. > > Matthew> Thanks anyway, Matthew. > > I have to ask this - did you look at snmpy > (http://snmpy.sourceforge.net)? This uses ucd-snmp/net-snmp for the > grunt. It doesn't claim to be ported to Windows, but net-snmp is, and > the C module in snmpy doesn't *look* that difficult to build on > Windows. What have been people's experiences with snmpy? The last time I looked at it (over a year ago), I had troubles building it (on linux) because it had dependencies on an oldish version of net-snmp. I do a lot of SNMP work, but have never really found a good python SNMP package. I looked at PySNMP (the pure python one) but never managed to get that to work either. It also just seems wrong to be doing all the low-level BER and packet building stuff in Python. From beliavsky at aol.com Sat Jun 12 18:51:42 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 12 Jun 2004 15:51:42 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <3064b51d.0406121451.79464134@posting.google.com> Mediocre Person wrote in message news:<513d6f09f74eb423c810692fb7bb1f46 at news.teranews.com>... > * less fussing with edit - compile - link - run - debug - edit - > compile - link - run -..... The Python cycle of running programs and fixing run-time errors that would be caught at compiled time in another language is in my experience MORE tedious than than the cycle for compiled languages like C++ and Fortran. It is easy to write a script that compiles, links, and (if no errors occurred) runs a program in a compiled language, making those three steps effectively one. I very rarely find myself directly calling the linker. From eppstein at ics.uci.edu Tue Jun 15 23:08:00 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 15 Jun 2004 20:08:00 -0700 Subject: Looking for a different version of sort References: <8a4484e4.0406151819.6c0538e7@posting.google.com> Message-ID: In article <8a4484e4.0406151819.6c0538e7 at posting.google.com>, BigsyNY at yahoo.com (Brian McGonigle) wrote: > I would like "list(t).sort()" to return a new sorted list. For > example, then I could do "t = tuple(list(t).sort())" to simulate an > in-place sort of a tuple assigned to the variable "t". When I try this > now I get: There are situations when you might want to sort tuples, but they're rare -- unless you need to use them as dict keys or something, it's more likely that you should just be using lists. But I think the actual answer to your question is that a sorted() function is coming in Python 2.4 -- see e.g. http://www.python.org/dev/doc/devel/whatsnew/node6.html Once this is in place, you'd be able to do t = tuple(sorted(t)) without even turning it into a list first. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From jepler at unpythonic.net Fri Jun 18 17:43:00 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 18 Jun 2004 16:43:00 -0500 Subject: shared file access in python In-Reply-To: <9418be08.0406180620.3e64be96@posting.google.com> References: <9418be08.0406180620.3e64be96@posting.google.com> Message-ID: <20040618214300.GA7315@unpythonic.net> The file() constructor probably takes any second argument that your OS's fopen() does, though this may have changed with the creation of universal newlines. If there's something that os.open() can do that file() can't, you should be able to achieve it by using os.fdopen(): (untested) def magic_file(filename, flag=os.O_RDONLY, mode='r', bufsize=None): fd = os.open(filename, flag) return os.fdopen(fd, mode, bufsize) I don't know what _open or fsopen are. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tdelaney at avaya.com Sun Jun 6 20:57:48 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 7 Jun 2004 10:57:48 +1000 Subject: 2.2 <-> 2.3 surprise Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE018F0521@au3010avexu1.global.avaya.com> Roman Suzi wrote: > No. But I think it was too early for 2.2 to have the feature. > It's like having positive number addition in a version 0.1 > and fully capable addition in 0.2. It was discovered that the 2.2 behaviour was undesireable (even a bug). However, it was decided that there should not be a semantic change in a 2.2 bugfix. Personally I disagree in this case, as the 2.2 behaviour is non-useful. However, there aren't going to be any more 2.2 releases. Tim Delaney From tzot at sil-tec.gr Thu Jun 24 09:45:42 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 24 Jun 2004 16:45:42 +0300 Subject: Searching for the best scripting language, References: Message-ID: <7emld0537p6m8m084u7k8koo0oiuvav7p3@4ax.com> On Sun, 13 Jun 2004 13:25:57 -0800, rumours say that "Eric @ Zomething" might have written: >OK: imagine The President of the United States outlawed Perl tomorrow! Perhaps reading "Perl for dummies" upside down produces hidden messages pro terrorism. Reviews about Perl books describing them as "a strong weapon in the hands of an aficionado" would help too. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From Skulled2003 at netscape.net Wed Jun 30 08:24:22 2004 From: Skulled2003 at netscape.net (Skulled2003 at netscape.net) Date: Wed, 30 Jun 2004 08:24:22 -0400 Subject: Getting User Display Information Message-ID: <7702DFCD.460EE233.401E91D9@netscape.net> Hi there, I was wondering if it was possible to get the screen display size and other associated properties somehow either using python modules or if possible using Tk methods. Thanks a lot. Vinod __________________________________________________________________ Switch to the New Netscape Internet Service. As low as $9.95 a month -- Sign up today at http://isp.netscape.com/register Netscape. Just the Net You Need. New! Netscape Toolbar for Internet Explorer Search from anywhere on the Web and block those annoying pop-ups. Download now at http://channels.netscape.com/ns/search/install.jsp From b.scharpf at tesionmail.de Fri Jun 25 08:11:48 2004 From: b.scharpf at tesionmail.de (Bertram Scharpf) Date: 25 Jun 2004 12:11:48 GMT Subject: Redirecting I/O in embedded Python Message-ID: Hi, in one of my C programs, I call embedded Python code. Now, I would like to redirect stdin/stdout to strings I can assign to/read out within the C code. This should be a solvable problem creating modules that have a member function 'write' or 'readline' respectively and assigning them to sys.stdin and sys.stdout. Before I do this work, I would like to ask if there is a reported standard way to do it or if there is even the finished code to be obtained anywhere on the web. Thanks in advance, Bertram -- Bertram Scharpf Stuttgart, Deutschland/Germany http://www.bertram-scharpf.de From guettli at thomas-guettler.de Tue Jun 15 09:56:43 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 15 Jun 2004 15:56:43 +0200 Subject: Help with parsing web page References: Message-ID: Am Mon, 14 Jun 2004 17:48:33 +0100 schrieb RiGGa: > Hi, > > I want to parse a web page in Python and have it write certain values out to > a mysql database. I really dont know where to start with parsing the html > code ( I can work out the database part ). I have had a look at htmllib > but I need more info. Can anyone point me in the right direction , a > tutorial or something would be great. Hi, Since HTML can be broken in several ways, I would pipe the HTML thru tidy first. You can use the "-asxml" option, and then parse the xml. http://tidy.sourceforge.net/ Thomas From mwh at python.net Fri Jun 18 07:38:36 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jun 2004 11:38:36 GMT Subject: does python have useless destructors? References: Message-ID: Roy Smith writes: > > > Maybe I don't need it, maybe 310 gives me RAII and that's what > > > I really need. I don't know, but again, 310 doesn't give me > > > anything of consequence in terms of software architecture. > > I just read PEP-310, and there's something I don't understand. It says: > > > Note that this makes using an object that does not have an > > __exit__() method a fail-fast error. > > What does "fail-fast" mean? Hmm, that should be clarified. Basically the idea is that you'll get an attribute error if you try to use an object in a with: clause that isn't meant to be used there (as opposed to your program doing something other than what you expect). Cheers, mwh -- I'd certainly be shocked to discover a consensus. ;-) -- Aahz, comp.lang.python From norm at norm.com Mon Jun 7 14:07:36 2004 From: norm at norm.com (Norm) Date: Mon, 7 Jun 2004 14:07:36 -0400 Subject: ideas Python / Network Admin Message-ID: I was wondering if you would give me some examples (not code, but general ideas) of what you are using Python for in Network Administration / Security ? Thanks Norm From gherron at islandtraining.com Thu Jun 24 11:17:12 2004 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 24 Jun 2004 08:17:12 -0700 Subject: FFT with Python In-Reply-To: <017601c458a8$66cbf890$559ea380@D4XN6B41> References: <017601c458a8$66cbf890$559ea380@D4XN6B41> Message-ID: <200406240817.12139.gherron@islandtraining.com> On Tuesday 22 June 2004 03:29 pm, Satish Chimakurthi wrote: > Hi All, > > Did anyone compute FFT - Fast Fourier Trans using Python ? I am looking for > a simple Python package which can do spectral analysis for me. Can someone > help me get such a package ? Both Numeric (the old) Numarray (the new) are Python extensions that do FFT's. You can find both at http://numpy.org/ Gary Herron From bug-groff at gnu.org Thu Jun 17 01:28:45 2004 From: bug-groff at gnu.org (bug-groff at gnu.org) Date: Thu, 17 Jun 2004 08:28:45 +0300 Subject: Your product Message-ID: Please read the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_product.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From fishboy at spamspamspam.com Wed Jun 2 08:11:34 2004 From: fishboy at spamspamspam.com (fishboy) Date: Wed, 02 Jun 2004 12:11:34 GMT Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: <3ngrb0le5g1l08li3rmbl3258i5e0pt731@4ax.com> On Tue, 01 Jun 2004 11:39:47 GMT, Timo Virkkala wrote: >I was looking through my old emails, and ran across this in a signature: > >""" >-----------------------> <--------------------------- >When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! >""" > >Curious as I was, I wanted to decrypt the end. At first I thought that it >was ROT-13, and tried that. Nope. Then I saw the lone "k" in the middle, and >thought that it must be "a", so I tried ROT-16. Wrong again. I also tried >all other rotations, from 1 to 26, to no avail. Does anyone have any ideas >what to try next? > >I also included the arrows, which began the signature, since I thought they >might be significant in some way... Well, it's an anagram for 'lord dog jet fwd jerk pkg' From BigsyNY at yahoo.com Tue Jun 15 22:19:45 2004 From: BigsyNY at yahoo.com (Brian McGonigle) Date: 15 Jun 2004 19:19:45 -0700 Subject: Looking for a different version of sort Message-ID: <8a4484e4.0406151819.6c0538e7@posting.google.com> I'm a Perl programmer learning Python (up to chapter 7 in Learning Python, so go easy on me :-) and I find that I look to do things in Python the way I would do them in Perl. In Perl functions and methods usually only return and undefined value in the event of an error, make an endless number of compound statements possible. Is there a version of sort() I could import from somewhere that returns a reference to the object on which it was performed, rather than returning "None". >>> t = ('x','y','z','a','b','c',) >>> t ('x', 'y', 'z', 'a', 'b', 'c') >>> list(t) ['x', 'y', 'z', 'a', 'b', 'c'] >>> l = list(t).sort() >>> print l None >>> l = list(t) >>> l.sort() >>> l ['a', 'b', 'c', 'x', 'y', 'z'] >>> I would like "list(t).sort()" to return a new sorted list. For example, then I could do "t = tuple(list(t).sort())" to simulate an in-place sort of a tuple assigned to the variable "t". When I try this now I get: >>> t = tuple(list(t).sort()) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence >>> I assume this is because the "None" returned from sort() is the non-sequence, but if sort had returned a reference to the list object it was called upon, it would work. Thanks, Brian From usenet_spam at janc.invalid Fri Jun 18 23:29:39 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 19 Jun 2004 03:29:39 GMT Subject: Queue module and Python Documentation Rant References: <6bl9q1-e98.ln1@home.rogerbinns.com> <40D240E9.6070801@hotmail.com> <451aq1-qaa.ln1@home.rogerbinns.com> Message-ID: Peter Hansen schreef: > Reading the docs more often would help. There are many different > pages that have such subsection links at the bottom, so one > should be used to it. True, but OTOH adding a level of detail to the contents page of the library reference would be good for newcomers & less experienced Python users... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tjreedy at udel.edu Sun Jun 27 01:25:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jun 2004 01:25:48 -0400 Subject: suse 9.1 and 64 References: Message-ID: "John Fabiani" wrote in message news:X5iDc.6114$6W1.5752 at newssvr25.news.prodigy.com... > I have just installed SUSE 9.1 64 and it created a > /usr/lib64/python2.3/. Note the 'lib64' - I'm guessing that my python > is 64 bit. I'm real new to python as I was wondering if someone could > enlighten me on the differences between 32 bit and 64 bit python - at > least as SUSE has set it up? Thanks I believe the main difference from the Python viewpoint is 64 instead of 32 bit ints and everything that follows from that. For instance, type(2**60), is int instead of long. Maybe someone else knows more. tjr From dkturner at telkomsa.net Tue Jun 8 02:01:43 2004 From: dkturner at telkomsa.net (David Turner) Date: 7 Jun 2004 23:01:43 -0700 Subject: Destructors and exceptions References: Message-ID: Hi > If you want to force the issue, give your class a close method, as with > file objects, and call it explicitly. Then code in try:finally:, which is > designed for this purpose. > try: > process > finally: > cleanup > That's a great shame. "Finally" is of course susceptible to the "forgetful programmer" syndrom. It also pollutes the code with what I consider to be implementation details -- for example, the fact that a file must be closed is a characteristic of the file object, and only accidentally relevant to the _use_ of files. Python would be a much stronger language if it could guarantee deterministic destruction of at least those objects which have a __del__ method. Can anyone point out any technical reasons why such a feature should not be included in the language? At any rate, I wonder if there is an another solution to the problem of resource management. Perhaps something along the lines of Ruby closures? Any suggestions? There has to be something more elegant (and safer!) than "finally". Regards David Turner From squirrel at WPI.EDU Thu Jun 24 10:52:37 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 24 Jun 2004 10:52:37 -0400 Subject: Delphi extension In-Reply-To: <10dloooa4p9hade@corp.supernews.com> References: <10dloooa4p9hade@corp.supernews.com> Message-ID: > I was given a libxx.so that was probably written in Delphi. > I need to wrap it so that I can call the functions/procedures > of the library from Python. I tried the usual extension > technique compiling a C file. I don't get anything meaningful > back when I call, so it doesn't work, or I am missing some > critical point. I have spent a good deal of time searching I don't know anything about Delphi; it may use a different calling convention than C (unlikely). If that's the case, however, you're out of luck unless you can find a Delphi-C or Delphi-Python interface module. Assuming it uses the C calling convention, you can possibly use the dl module: import dl c=dl.open('/path/to/my/lib.so') c.call('myfunc',arg1,arg2) dl is unfortunately limited to passing integers, strings, and NULL, and to returning integers, so it's likely not to be useful for complex data structures. From lbates at swamisoft.com Tue Jun 1 12:13:12 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 1 Jun 2004 11:13:12 -0500 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: I'm going to jump in here and make an observation. It sounds like you have too much code in a single try/except block. If you have independent calls to instrument interface put each of them that might fail in a separate try/except block. I've needed to do this in an earlier project and I log errors in a log file for review. Something like: try: data=getsomedatafrominstrumentfunc1() except: logf.writelines("W","Unable to communicate with func1") try: data=getsomedatafrominstrumentfunc2() except: logf.writelines("W","Unable to communicate with func2") My understanding is that try/except overhead is very low (especially if there is not an exception). HTH, Larry Bates Syscon, Inc. "Zunbeltz Izaola" wrote in message news:cthvfiblpo4.fsf at lcpxdf.wm.lc.ehu.es... > Peter Hansen writes: > > > > Pardon: I don't know why I thought this was related to testing > > code. > > No problem :-) > > > > > > My program is controling and instrument (an x-ray powder > > > diffractometer) and some parts of the instrument are not working for > > > the moment, so i want to disable all error i get from this instrument > > > (are coded like exceptions) > > > > What is the interface to the instrument? Is there some sort of > > driver/wrapper layer that handles the communication with the > > device? Your only hope, I think, is to intercept things at > > that level and avoid/trap the exceptions before they get up > > to the higher level. In effect, stubs as Irmen suggested... > > > > Finally I do something similar to Irmen's suggestion. > > > It sounds like you are quite capable of figuring it out at > > this point, though, since all you wanted to know was whether > > you could continue after an exception and now you know you > > cannot. :-) > > > > Yes, I only wanted to know if there was an easy way to continue after > an exception; and I can't (nobody can :-) > > Thanks to all for your answers (and sorry for re-starting and annual > thread) > > Zunbeltz > > > -Peter > > -- > Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu > dotes > Materia Kondentsatuaren Fisika Saila | > Zientzia eta Teknologia Fakultatea | Phone: 34946015326 > Euskal Herriko Unibertsitatea | > PK 644 | Fax: 34 944648500 > 48080 Bilbo (SPAIN) | From koshkindom at tochka.ru Fri Jun 11 18:44:59 2004 From: koshkindom at tochka.ru (Sergey Krushinsky) Date: Sat, 12 Jun 2004 02:44:59 +0400 Subject: Anonymous file closing In-Reply-To: References: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> Message-ID: <40CA35EB.2010900@tochka.ru> Peter Hansen wrote: > > What's an "anonymous file"? The term means nothing to me... The file object created in: ... text = open(filename, 'r').read() ... has no name, and cannot be accessed elsewhere. In ...f = open(... the situation is different. It's like in two phrases: 'I was told that...' and 'Peter told me that...". Sergey From has.temp2 at virgin.net Wed Jun 23 05:08:55 2004 From: has.temp2 at virgin.net (has) Date: 23 Jun 2004 02:08:55 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> <69cbbef2.0406210114.439f4ee@posting.google.com> <69cbbef2.0406220023.d7242de@posting.google.com> Message-ID: <69cbbef2.0406230108.466aa1a8@posting.google.com> Paramjit Oberoi wrote in message news:... > >> The second point above is why I don't understand your claim that the > >> separation of presentation logic and markup would be easier to maintain. [snip list of arguments] > OK, pretty good arguments. I see the point. I guess I would see it more > strongly if my favourite tool for editing both HTML and python wasn't a > standard text editor <0.5 wink>. Only my first argument related to authoring tools; the rest are general design and management issues. BTW, my favourite HTML and Python editing tools are also simple text editors, and I still find the separation of markup and code advantageous. I like being able to wear my "HTML stylist" hat separate to my "code geek" hat, especially when it comes to editing and previewing templates, something DOM-style systems are especially good at. > >> By flexibility I meant flexibility in what you can do by modifying the > >> template alone (since presentation logic can be added to the template). > >> In the case of 'DOM-style' systems you may have to edit the template as > >> well as the presentation logic (which would mean modifying the > >> 'program', not just the template). > > > > You're making a false distinction here. The template and the > > presentation logic are as much a part of the "program" as the business > > layer they sit on top of. Editing the template markup is modifying the > > application. Editing the template logic is modifying the program. > > I think it is a very real distinction. If you are a user of the > application, you don't want to have to maintain a private set of > modifications to it. Also, the application might be installed in a > read-only location... It might even be compiled, once all the python > compilers really take off. I see no difference between having an application that loads up a folderful of Cheetah templates, and having an application that loads up a folderful of PyMeld/Nevow.renderer/HTMLTemplate templates. You're seeing barriers where there aren't any; monolithic construction where there's no need for it. It's completely up to the developer where they want to put the joins in the system, which bits they want to decouple from the rest of the system and expose to outsiders, and which they want to lock away in the application core. Which is just how things should be, and DOM-style templating systems certainly don't interfere with it. (Mind, I've thrown away thousands of lines of working code - including complete templating engines - precisely because it imposed the sorts of stupid artificial divisions that made them frustratingly inflexible and inextensible, so haven't arrived at the DOM-like design by accident.:) > > Now, if you believe that it's the templating system's job to impose > > and enforce a certain kind of architecture upon the developer - one > > that makes it impossible to mix presentation and business logic > > together - then you can certainly make that argument. > > Not at all. In fact, it's the HTMLTemplate-like systms that enforce the > separation of markup from all code. There's nothing to stop you inlining chunks of HTML in your Python code, or adding a preprocessor to the system that extracts chunks of code out of your HTML template and assembles them into a controller. > With Cheetah you can have as little or as much code in the template as you want Not exactly true, as it's impossible to have _no_ code in a Cheetah template. At minimum you'll always have basic flow control and assignments. DOM-style templating systems start from a much lower complexity baseline and let you build upward as you want. (See Lisp philosophy.) Hope that clarifies. From vincent at visualtrans.de Tue Jun 15 11:45:36 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 15 Jun 2004 17:45:36 +0200 Subject: redirect output from embedded C module In-Reply-To: <981e5e9.0406150229.42823256@posting.google.com> References: <981e5e9.0406150229.42823256@posting.google.com> Message-ID: legba wrote: > hi all.. I'm writing an application in python2.3 under linux debian > which accepts new "plug-ins" in the form of c-written python extension > modules. > My problem is that I'd like to catch the stdout/stderr from one of > this modules > and redirect it into a tkinter text widget, in real time. Let's say > the module's > name is plugin and that plugin.doSomething() prints out with a C > printf() > the string "it's a mess". > > Redirecting sys.stdout before calling plugin.doSomething() doesn't > work, I guess > because the plugin code has a different stdout file then python. So > the second solution is to force every plugin-writer to embed in every > plugin the C lines: > > if ((fd = open("outfile", O_WRONLY | O_CREAT | O_TRUNC, 0600)) == -1) > { > perror("open outfile"); > exit(2); > } > dup2(fd, fileno(stdout)); > > and use as "outfile" the real stout. Then redirect python stdout to > the text widget. > But how do I access python stdout from C? Use the API functions PySys_WriteStdout(format, ...) and PySys_WriteStderr(format, ...) HTH, Vincent Wehren > or even better how do I access the text widget directly from C? > or, since this solution looks quite crappy, how do I do it in another > way? > > thanks to all > legba From jfouhy at paradise.net.nz Thu Jun 24 20:49:07 2004 From: jfouhy at paradise.net.nz (John Fouhy) Date: 24 Jun 2004 17:49:07 -0700 Subject: Tkinter, scale widget, and mouse clicks References: Message-ID: klappnase at web.de (klappnase) wrote in message news:... > jfouhy at paradise.net.nz (John Fouhy) wrote in message news:... > > So I've got a horizontal scale widget in my GUI. When I click the > > mouse in the area to the right of the GUI, the scale advances by 1. > > I want to change this, so it jumps by a larger amount (and likewise if > > I click to the left of the slider). > > Any clues? > You can address the part of the scale widget you clicked on with > event.x/event.y, so maybe something like this might do what you want > (untested): > > var = IntVar() > var.set(0) > sb = Scrollbar(master, variable=var) > sb.bind('<1>', jump) > > def jump(event): > if sb.identify(event.x, event.y) == 'trough1': > var.set(var.get()-5) > return 'break' > elif sb.identify(event.x, event.y) == 'trough2': > var.set(var.get()+5) > return 'break' > > I hope this helps > > Michael I had an idea of doing something like that, but I didn't know about the 'identify' function. Also, I am using the Scale widget, not the Scrollbar widget, but it seems Scale has that function too. (I wish Tkinter had better documentation) Anyawy, your solution worked perfectly :-) Thanks a lot, -- John. From jjl at pobox.com Tue Jun 29 17:00:57 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Jun 2004 22:00:57 +0100 Subject: Python Magazine exists! (was: Python intro questions) References: <4edc17eb.0406281943.32bb2e9a@posting.google.com> Message-ID: <87brj2f59y.fsf@pobox.com> michele.simionato at gmail.com (Michele Simionato) writes: > BTW Mark, what's the status of the article *I* submitted (I sent you a private > email a couple of days ago but had no answer yet, so let me try the public > forum instead ;) Yeah, but *your* article was all about some horrendous meta-metaclass nightmare, right? The poor guy's probably too scared to respond ;-) (BTW, FWIW, and from what little I know, the handling of Irmen's case seemed to me like reasonable behaviour + forgiveable slip-up) John From flupke at nonexistingdomain.com Fri Jun 4 05:18:45 2004 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 04 Jun 2004 09:18:45 GMT Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: "Heiko Wundram" schreef in bericht news:mailman.564.1086294797.6949.python-list at python.org... Am Donnerstag, 3. Juni 2004 21:55 schrieb Reiner Block: [snip] >Oh, and I just wanted to say that I find the Python documentation fantastic as >it is! I don't want to have another PHP-newbie like >spelling-out-every-detail-but-don't-find-what-you're-looking-for kind of >documentation, but just as Python applauds to every programmers common sense, >so should the documentation... And if there's any doubt, looking up man 2 >exec should've gotten you there too... I don't agree. The online reference of Php is far easier to search than the Python reference. There's no excuse for not having a decent search function. period. That's what i hate about the Java docs too. No search capability. Php doc rocks because of that (at least for me :) ) Benedict From secun at yahoo.com Fri Jun 4 16:34:40 2004 From: secun at yahoo.com (ChrisH) Date: Fri, 04 Jun 2004 20:34:40 GMT Subject: Orlando Florida-python users group References: Message-ID: Yes. I'm also in central Florida and would like to see a python user group. In article , pxlpluker at cfl.rr.com says... > Orlando Florida-python users group. > there isn't one. anyone want to start one ? > > > > From apardon at forel.vub.ac.be Mon Jun 28 08:59:30 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jun 2004 12:59:30 GMT Subject: [python] using try: finally: except References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> Message-ID: Op 2004-06-25, Tim Peters schreef : > [Tim Peters] >>> It's more that Guido deliberately separated them. Before Python >>> 0.9.6, you could attach both 'except' and 'finally' clauses to the >>> same 'try' structure (see Misc/HISTORY in a Python source >>> distribution). I don't remember the semantics, and that was indeed >>> the problem: nobody could remember, and half the time guessed wrong. > > [Peter Hansen] >> I'm curious: was it that the order of execution was fixed, regardless >> of the order of the 'finally' and 'except' in the source, or was >> it still confusing even though the order of execution changed >> logically with the order of the statements in the source? > > If present, a 'finally' clause had to be the last clause in a > try/except/finally structure. That was enforced by the syntax. The > most common confusion was over whether the code in the 'finally' > clause would execute if an exception was raised during execution of an > 'except' clause. That code isn't in the 'try' block, so why should > 'finally' apply to it? Well personnaly I wouldn't find it that hard to aswer this. The finally clause is to finalise code in the try block. That an exception occured in an except clause doesn't change that. -- Antoon Pardon From segphault at sbcglobal.net Sun Jun 13 19:43:43 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sun, 13 Jun 2004 23:43:43 GMT Subject: new to the list and... References: Message-ID: On Sun, 13 Jun 2004 06:01:12 -0400, Daniel Farmer wrote: > Where would I begin to find out about creating windows like GUI with Python? > > I've downloaded tcl/tk... I'm not exactly sure what to do with > them at this point. ( they're sitting in folders on my desktop ). Welcome to python! I hope you find your python programming experience as enlightening and insightful as I have! If you are looking for some resources to help you get started with python GUI programming using Tk, you may find these links helpful: http://www.pythonware.com/library/tkinter/introduction/ http://www-106.ibm.com/developerworks/library/l-tkprg/index.html Good Luck! --SegPhault From klachemin at home.com Thu Jun 24 16:49:53 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 13:49:53 -0700 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> <9418be08.0406240642.6b7797f@posting.google.com> Message-ID: <889cbba0.0406241249.42ab2ef4@posting.google.com> elbertlev at hotmail.com (Elbert Lev) wrote in message news:<9418be08.0406240642.6b7797f at posting.google.com>... > > translate method is much slower then "c in string" method in the case > when the test string is very long (say 5mb) and the invalid character > is located close to the beginning of the string. (10000 times slower!) Good point! I was surprised that allocating a fresh string and comparing lengths was speedier, but upon reflection, I could see how that could be so. And I also see how if it was a HUMONGOUS string, a book more like, this would no longer be the case. Thanks for pointing that out! From jacek.generowicz at cern.ch Thu Jun 3 11:25:09 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 03 Jun 2004 17:25:09 +0200 Subject: Optimizing multiple dispatch References: Message-ID: Jacek Generowicz writes: > (I'm pretty sure that should be 10**5 loops in the list comp case) I'm sorry, ignore that, I was talking out of my **** From loic at fejoz.net Thu Jun 17 03:01:44 2004 From: loic at fejoz.net (Yermat) Date: Thu, 17 Jun 2004 09:01:44 +0200 Subject: Bug in New Style Classes In-Reply-To: <2jci2sFvvu0uU1@uni-berlin.de> References: <2jci2sFvvu0uU1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > David MacQuigg wrote: > >> I have what looks like a bug trying to generate new style classes with >> a factory function. > > > IIRC, you can't assign to __bases__ of a new-style class. But you can > use type() instead of your home-made factory function. Even better: see http://www.python.org/doc/current/lib/module-new.html and especially classobj ! -- Yermat From usenet_spam at janc.invalid Fri Jun 18 22:42:45 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 19 Jun 2004 02:42:45 GMT Subject: (OT) Boa Constructor and Python 2.3.4 References: Message-ID: "flupke" schreef: (Hallo mede-pandoriaan ;-) > Hhhmm. Bummer. I wanted to use it to quickly get a wxPython app > going as i'm pretty new to Python & wxWindows. > Well, i guess i can also "type" :) > Are there any other screen designers (i've tried wxGlade but it > seems a bit limited) There is XRCed too: (it's included with wxPython IIRC) If you want "easier hand-coding" based on wxPython you might want to try: - Wax - PythonCard -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From mmiller at tx3.com Tue Jun 29 05:50:25 2004 From: mmiller at tx3.com (Martin) Date: 29 Jun 2004 02:50:25 -0700 Subject: Get Rid Of Tkinter Canvas Border Message-ID: <78c1b378.0406290150.64d4561e@posting.google.com> I'm using Python 2.3.3 on Win XP Pro. My program places a Canvas object on a parent Frame. The backgound color of both is set to 'white' and both have borderwidth set to zero. The Canvas is smaller than the Frame it is inside of. For some reason there is always tiny (one pixel?) grey border drawn around the boundaries of the Canvas object. I tried setting relief to both SOLID and FLAT on the Canvas object, but that does not get rid of the thin grey border. I suspect this is a bug, but even so, anybody know of a workaround? Surely I'm not the first preson to encounter this issue. I found one old newsgroup reference cica March 2001, but there was only one message and no one responded... TIA, -Martin From michael at foord.net Fri Jun 11 10:53:49 2004 From: michael at foord.net (Fuzzyman) Date: 11 Jun 2004 07:53:49 -0700 Subject: Empty directories with zipfile References: <8089854e.0406090616.28a4c494@posting.google.com> <8089854e.0406102321.6025a46@posting.google.com> <35udnWPiL4B6DVTdRVn-ug@powergate.ca> Message-ID: <8089854e.0406110653.5329a66e@posting.google.com> Peter Hansen wrote in message news:<35udnWPiL4B6DVTdRVn-ug at powergate.ca>... > Fuzzyman wrote: > > > Peter Hansen wrote in message news:... > >>http://groups.google.com/groups?q=comp.lang.python+zipfile+empty+directory > > > > Ha... thanks.... > > Worked a treat. > > For the record, which solution did you use? I see at least > two alternatives in the second and third hits to the above > search (attribute 16, attribute 48, and maybe another option > involving another argument... didn't read it all in detail). > > -Peter The simplest one ! Which works fine..... from zipfile import ZipFile, ZipInfo zip = ZipFile(zipfilename, 'w') zi = ZipInfo(emptydirname+'/') zip.writestr(zi,'') zip.close() Create a ZipInfo instance where the filename ends in '/' and use the writstr method. Only other pitfall - You have to be careful when extracting - test if names in the zip.namelist() end with '/' and create the directory rather than trying to write the file...... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From wogsterca at yahoo.ca Sun Jun 6 10:25:04 2004 From: wogsterca at yahoo.ca (Paul Schmidt) Date: Sun, 06 Jun 2004 10:25:04 -0400 Subject: POP3 and email Message-ID: <6PFwc.742$8k4.38828@news20.bellglobal.com> Dear list: I am new to python, and I am trying to figure out the short answer on something. I want to open a POP3 mailbox, read the enclosed mail using the POP3 module, , and then process it using the email module. Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo... There is some stuff that isn't clear here, can I pass the POP3 message directly to email for processing, or does it need to be saved to a temporary file somewhere first? The emails being received will consist of headers, a tiny amount of text, and one or more MIME attachments. Let me explain the project, and then this should all make sense. I havc one or more people going to an event, they will send emails to a special email address, of stuff to go on a website. This is an HTML page, which could have one or more photos attached to display in the page once the HTML is processed, the whole thing gets FTP to the web. Paul Any ideas? Paul From wyojustin at hotmail.com Sat Jun 19 22:04:03 2004 From: wyojustin at hotmail.com (Justin Shaw) Date: Sat, 19 Jun 2004 22:04:03 -0400 Subject: Access keyboard Message-ID: Anybody now how I can access what is being typed in word/PowerPoint/email from a background python program? I have written a typing tutor and would like to use it to assist typing in other programs. Thanks Justin Shaw From rogerb at rogerbinns.com Mon Jun 28 12:37:03 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 28 Jun 2004 09:37:03 -0700 Subject: serial, parallel and USB port References: <3f284386$0$1922$626a54ce@news.free.fr> <20040628124816.000078fd@titan> Message-ID: Josef Dalcolmo wrote: > on Sat, 19 Jun 2004 20:19:36 -0700 > "Roger Binns" wrote: > > > And if you want USB access, I have done a Python wrapper around libusb > > that works on Windows, Linux and Mac: > > > > http://cvs.sourceforge.net/viewcvs.py/bitpim/bitpim/native/usb/ > > Interesting. From a first glance at it I think one has to compile the extension oneself. That is correct for all platforms. > Now, I for example do not have MS-C installed Neither do I. > Cygwin is still a World apart I don't have Cygwin installed either. > and MinGW doesn't compile Python out of the box either. That doesn't matter. Why do you need to compile the whole of Python? MinGW compiles extensions perfectly including the USB which I have been shipping for almost a year (using the standard Python distribution). Just use MinGW and you will have happy USB access on Windows. The other platforms work fine with the standard system compiler (gcc). You can also compile any distustils based extension as well using mingw: python setup.py build --compiler=mingw32 bdist_wininst > So the original posting may also read as: > why aren't these interface in the standard distribution? A different answer is because it ties their release schedule to that of Python rather than their underlying libraries. The Windows version of pyserial uses win32all which isn't a standard part of Python on that platform. My USB stuff depends on libusb which has a seperate release schedule to Python. In reality they are not very popular. pyserial manages just over 1,000 downloads a month and I have no idea how much the USB stuff is, but suspect it is closer to 5 a month. Python defines an extension mechanism that is fairly easy to use to distribute extensions. I don't see what the difficulty in using them is. And if you need a C compiler on Windows, MinGW does the job fine. Roger From squirrel at WPI.EDU Tue Jun 29 08:51:46 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 29 Jun 2004 08:51:46 -0400 Subject: How important is Python 1.5 compatibility? In-Reply-To: <20040629092230.000046fb@titan> References: <40E092A9.43C2CDDF@alcyone.com> <3dk6r1-116.ln1@home.rogerbinns.com> <20040629092230.000046fb@titan> Message-ID: On Tue, 29 Jun 2004, Josef Dalcolmo wrote: > well, Debian stable is still Woody and still uses Python 2.1. But who ever uses stable? ;) From gustabares at verizon.net Wed Jun 9 10:24:20 2004 From: gustabares at verizon.net (Gus Tabares) Date: 9 Jun 2004 07:24:20 -0700 Subject: Exception classes with properties Message-ID: Hello all, I'm curious as to whether or not this is supported. I want to be able to have an exception class that has properties. It seems as though subclassing both Exception and object does not work. Like in the following code: class TestExcn(Exception, object): def __init__(self, id = 'test_id'): self.args = [id] def set_id(self, id): self.args[0] = id def get_id(self): print "Test" return self.args[0] id = property(get_id, set_id) If I instantiate this class and try to raise the instance, I get a TypeError. Is it possible to have an exception class with properties? From nun at meyl.com Thu Jun 17 04:33:15 2004 From: nun at meyl.com (Mitja) Date: Thu, 17 Jun 2004 10:33:15 +0200 Subject: somewhat OT: function to produce n as distinct colors as possible References: <87pt7zrkcp.fsf@titan.staselog.com> <87r7sfy6zy.fsf@titan.staselog.com> Message-ID: Edvard Majakari (news:87r7sfy6zy.fsf at titan.staselog.com) wrote: > "Mitja" writes: > >> I'd start with the HSI (aka HSL) model and distribute hues evenly. >> Don't know if that's the best solution what with all the stuff going >> on in our brain mangling our perception, but it should be close. >> Have a look at google for the HSI model and its conversion to RGB. > > Thanks for the tip. After a little fiddling I ended up with a very > simple algorithm which uses hsv color model (hue, saturation and > value). The > python module colorsys uses floats in the range [0..1.0], so I started > with all values at 1, and decrement h and v by step (1.0 / n, where n > = number of distinct colors) every turn. Note that I don't touch value > component. That is "descrement h and s", of course. > > I get quite nice values when n < 10. After that it gets worse, but at > n = 20 colors it is still possible, if not easy, to separate a color > from another. > > But the algorithm could be better for sure. For one thing, I don't see > dark brown anywhere, and it would be easy to separate from other > colors (even when n = 20). That's bluffing on my side again, but I'd leave saturation as it is, and then make colors by equally distributing hues (as you already did), except that with say 12 colors I'd make 3 sets, each of them with different VALUE, and each of them with equally distributed hues. Guess you found a description before, but the HSV model is very intuitive and made with humans in mind. Hue is the actual color - red, green, blue, violet, ... Intensity varies from 1 (very intensive, vivid color) to 0 (no color at all, just grey). Value is brightness. So with what I described above, you'd get say blue, darker blue, very dark blue, red, darker red, etc. To get dark brown, you'd have to play around with saturation a bit. > > # simple test for producing n different colors. Prints out a very > simple # (and probably not valid) web page with differently colored > table cells. > > import colorsys > import sys > > def float2dec(color): > return int(color*255) > > def dec2hex_str(rgb): > return "%06x" % (rgb[0]*256**2+rgb[1]*256+rgb[2]) > > def distinct_colors(n): > colors = [] > step = 1.0/n > h, s, v = (1, 1, 1) > > for i in range(n): > r, g, b = map(float2dec, colorsys.hsv_to_rgb(h, s, v)) > colors.append((r, g, b)) > > h, s, v = (h-step, s-step, v) > > if h < 0: > h = 0 > if s < 0: > s = 0 > if v < 0: > v = 0 > > return map(dec2hex_str, colors) > > # main > > color_count = int(sys.argv[1]) > > print """\ > > %s > > > \t\ > """ % "Printing %d distinct colors" % color_count > i = 0 > for color in distinct_colors(color_count): > i += 1 > if i % 8 == 0: > print '\t\t\n\t\n\t' > % color else: > print '\t\t' % color > print """\ > \t >
    test area
    test area
    > > \ > """ From tedlandis at rogers.com Thu Jun 3 00:28:37 2004 From: tedlandis at rogers.com (Ted) Date: 2 Jun 2004 21:28:37 -0700 Subject: Execute a command from a cgi script Message-ID: <40dd3107.0406022028.3fcbe08b@posting.google.com> Hi all, I am trying to execute a batch file from a python cgi script on an IIS webserver on Win2K. I have changed all the permissions I can think of. The command I am using is: p = os.spawnl(os.P_WAIT, 'spameggs.bat') I am using spawn because I need the Wait, but I have tried popen* and command and none of them work either. The odd thing is that if I embed the python code in an asp page it works just fine. I am aware there are a lot of variables here but has anyone seen anything like this before? Thanks, Ted From dave at pythonapocrypha.com Fri Jun 25 16:45:48 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 25 Jun 2004 14:45:48 -0600 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: <069f01c45af5$65815a80$6400fea9@boba> Christopher wrote: > > Seems like a waste to reserve a > > symbol for something so rarely needed. > > Lisp and Scheme do the same thing: > > (set! a 5) <- sets a variable (i.e. changes its value) > (eq? a 6) <- tests equality (returns true or false) > > It's defined precisely because it's not needed often (at least in the ! > case): the functions that modify their arguments are few and far between, > so it is best to warn the programmer of this behaviour. An apples-to-oranges comparison, IMO - it makes sense to delimit a side effect in a functional language. -Dave From dmq at gain.com Wed Jun 16 15:29:56 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 16 Jun 2004 12:29:56 -0700 Subject: Making classes from Metaclasses globally available References: Message-ID: On Wed, 16 Jun 2004 00:28:46 -0400, "Jean-Fran?ois Doyon" wrote: >Hello, > >I'm using MetaClasses to create classes. Why use metaclasses? The metaclass wizards seem to be telling us that these are special tools for Python developers, not intended for "mortal users". >How do I make these new classes "globally" available? Can't you just generate your classes with an ordinary function, and assign them to whatever global name you want? def factory(var1,func1): class C: const1 = 123 def commonfunc(self): print "Hello from commonfunc" setattr(C, 'var1', var1) setattr(C, func1.__name__, func1) return C Then whenever you need a new class, just call the factory with whatever variable data and functions you want to add to each class. C1 = factory(var1,func1) # A unique class c1 = C1() # An instance of that class -- Dave ************************************************************* * * David MacQuigg, PhD * email: dmq at gain.com * * * IC Design Engineer * phone: USA 520-721-4583 * * * * Analog Design Methodologies * * * * * 9320 East Mikelyn Lane * * * * VRS Consulting, P.C. * Tucson, Arizona 85710 * ************************************************************* * >I probably just have to assign them to something magic, but I can't seem to >figure out which one. > >if I do: > >MetaClass('Klass', (), {}) > >The resulting class needs to be assigned to something: > > myclass = MetaClass('Klass', (), {}) > >The problem is that I'm looping and don't know in advance how many classes >there will be. > >So right now I have something like: > >msclasses[clsname] = MapServerMetaClass(str(clsname), (), >{'schema':list,'__init__':MapServerClassInit}) > >inside a loop. > >Problem is I really don't want to have the classes stuck inside that dict. >I want them "globally" available as if I had simply made a "class" >declaration at the top of the file. > >Any ideas or suggestions? > >Thanks, >J.F. > From bram at nospam.sara.nl Wed Jun 23 10:47:51 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 23 Jun 2004 16:47:51 +0200 Subject: Parsing C Preprocessor files References: <20040623140151.6b8863f2@pistache.sara.nl> Message-ID: <20040623164751.2c3476cc@pistache.sara.nl> pyHi(), I would like to thank the people who responded on my question about preprocessor parsing. However, I think I will just roll my own, as I found out that it takes a mere 16 lines of code to create a #ifdef tree. I simply used a combination of lists and tuples. A tuple denotes a #if block (startline,body,endline). A body is a list of lines/tuples. This will parse the following text: Top level line #if foo on foo level #if bar on bar level #endif #endif #ifdef bla on bla level #ifdef q q #endif #if r r #endif #endif into: ['Top level line\n', ('#if foo\n', ['on foo level\n', ('#if bar\n', ['on bar level\n'], '#endif\n')], '#endif\n'), ('#ifdef bla\n', ['on bla level\n', ('#ifdef q\n', ['q\n'], '#endif\n'), ('#if r\n', ['r\n'], '#endif\n')], '#endif\n')] Which is very suitable for me. Code is: def parse_block(lines) : retval = [] while lines : line = lines.pop(0) if line.find("#if") != -1 : headline = line b=parse_block(lines) endline = lines.pop(0) retval.append( (headline, b, endline) ) else : if line.find("#endif") != -1 : lines.insert(0, line) return retval else : retval.append(line) return retval And pretty pretting with indentation is easy: def traverse_block(block, indent) : while block: i = block.pop(0) if type(i) == type((1,2,3)) : print indent*"\t"+i[0], traverse_block(i[1], indent+1) print indent*"\t"+i[2], else : print indent*"\t"+i, I think extending it with '#else' is trivial. Handling includes and expressions is much harder ofcourse, but not immediately req'd for me. Bram On Wed, 23 Jun 2004 14:01:51 +0200 Bram Stolk wrote: > Hi there, > > What could I use to parse CPP macros in Python? > I tried the Parnassus Vaults, and python lib docs, but could not > find a suitable module. > -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "Software is math. Math is not patentable." OR "Software is literature. Literature is not patentable." -- slashdot comment ------------------------------------------------------------------------------ From chris.cavalaria at free.fr Sat Jun 5 17:18:15 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sat, 05 Jun 2004 23:18:15 +0200 Subject: Python on a thumbdrive References: <10d9011b.0406051246.7eac1408@posting.google.com> Message-ID: <40c2389a$0$21557$626a14ce@news.free.fr> TuxTrax wrote: > I tried setting pythonhome from Bash: > > PYTHONHOME="/mnt/sda1/python/python2.3" If you did it like that it's a mistake : $ PYTHONHOME="/mnt/sda1/python/python2.3" $ /mnt/sda1/python/python Do that instead : $ export PYTHONHOME="/mnt/sda1/python/python2.3" $ /mnt/sda1/python/python From hamilcar at tld.always.invalid Tue Jun 29 05:54:23 2004 From: hamilcar at tld.always.invalid (Hamilcar Barca) Date: Tue, 29 Jun 2004 03:54:23 -0600 Subject: file compression References: Message-ID: <20040629055356.609$6x@news.newsreader.com> In article (Tue, 29 Jun 2004 08:59:53 +0000), Elaine Jackson wrote: > From: "Elaine Jackson" > NNTP-Posting-Host: 64.59.144.74 > Organization: Shaw Residential Internet I've noticed that my newsgroup filter is killing all of your messages. Google shows both viruses and spam coming from your IP address: http://www.google.com/groups?q=NNTP-Posting-Host:+64.59.144.74&filter=0 Would you check to see if you're infected with a Windows virus and/or worm? From michele.simionato at poste.it Thu Jun 17 04:17:13 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 17 Jun 2004 01:17:13 -0700 Subject: Making classes from Metaclasses globally available References: <5d6Ac.34929$7H1.1286929@news20.bellglobal.com> Message-ID: <95aa1afa.0406170017.758de9d7@posting.google.com> "Jean-Fran?ois Doyon" wrote in message news:<5d6Ac.34929$7H1.1286929 at news20.bellglobal.com>... > Why? > > Well, basically I'm looking at writing an IDE of sorts. It should allow the > viewing editing of text files. > > Catch is, said text files are structured much like XML, but they're NOT XML. > > I want the application to be extensible, and not be stuck to a particular > version/schema of this file. > > So the idea is, create one or more "schemas" to describe what I'm going to > be looking for and then parsing. > > Because the format of said text file is structured in a very XML-like way, I > thought it'd make sense to simply > dynamically create a tree of objects, which are instances of relevant > classes. But because of my statement above > I don't know in advance what classes there might be and so on. > > So I figured I'd use something like MetaClasses to do it. I've got the > basic schema parsing and class creation > in place already, the problem is that I want to keep the class creation and > the parsing fairly seperate. > > I'm thinking the parsing functionality will be extra polated from the schema > also, but be part of the classes (The > file structure is consistent enough to allow this I think ...). > > Anyways, it's not all entirely clear in my mind yet ... But that's the basic > idea. > > But I just want classes created from the schema to be available globally so > that when the classes need to interact with each > other (More precisely, one instance needs to instanciate another class and > make it an attribute of self) I don't need to pass > a list of classes or soemthing similar around everywhere. > > Did that make any sense ? :) > > Admitedly, I've kind of thought up a way to do it with a unique class ... > But I don't like that design as much ... The model > I describe above fits really well with the application in question. I've > even seen something similar done in PHP with a > web interface, though it was much more restricted in it's flexibility and > capability to adapt to any kind of schema. > > Metaclasses seem to open the door to greater flexibility by not having to > know ANYTHING in advance. > > If you're familiar with the generateDS script, I've got something like that > in mind, but not for XML. > > If anyone has a better idea on how to go about this, or knows of > tools/examples that implement this kind of scenario, > I'd love to hear about it! > > Thanks, > J.F. > Do you know about David Mertz's article on XML and declarative mini-languages? It appeared some time ago on IBMdeveloperWorks. In the scenario you are showing to us metaclasses could be indeed a sensible solution, but not necessarely the best one. Michele Simionato From peter at engcorp.com Tue Jun 29 12:30:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 12:30:27 -0400 Subject: embedded python? In-Reply-To: References: Message-ID: Alexander May wrote: > We are developing a distributed application running on approximately six > thousand nodes with somewhat limited hardware resources. Our hardware > target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected > specific hardware yet; the hardware target is what we are trying to fit into > based on price constraints. Each device needs to be able to handle about 2 > kbs (yes kilo, not mega) worth of network traffic. You mention network, so presumably you have Ethernet (?) interfaces, and plan on TCP or UDP, in which case you probably first need to consider operating systems... Python does not automatically give you support for networking, it just uses the underlying OS support. > I intend to a least prototype the system in Python. It would be great if we > could we could use Python in production by embedding it in the hardware. My > question is does anyone have any real world experience using python in an > embedded system? Yes, there are a few people around here who have worked on embedded Python systems, including me (at a past employer). > 1) Are there any embedded Pythons out there? The nodes will likely be > running some form of Linux, but I don't particularly feel like devoting > resrouces to porting python. Any embedded Linuxes supporting Python? > Thoughts in general? I doubt you'll need to do much "porting". Unless the Linices you are considering are quite unusual, they ought to look a lot like any other Linux, and Python may well work largely unchanged. Any required changes could be in areas you don't need, anyway. Again, make sure you consider right away exactly what OS resources, other than networking, that you actually need. Multitasking? Signals? Audio? GUI? etc... > 2) What are the resource requirements of Python? How much overhead do the > network related modules add? _socket.pyd is 49212 on Win32, and 124040 (probably with debugging symbol table included?) on Linux, for Python 2.3.4. This includes lots of doc-strings, though, so you can probably shrink it pretty easily with a configurable setting during compilation. > In short, is embedding python realistic? Definitely. We did it first on a 33MHz 386 (or 286?) compatible board with only 1MB of flash and 1MB of RAM, and a tiny embedded OS with no networking. That took a little slashing, such as removing floating point support, but for the most part such things were supported well by #defines during compilation. I think we based that one on Python 1.5.2. (It was a few years ago.) Performance, however, turned out to be inadequate and we decided we'd get farther faster by keeping Python and switching to faster hardware (than by ditching Python and doing it all in C). The next version was a 100MHz 486 compatible with 32MB RAM and Compact Flash as a hard drive. We picked 32MB flash as the target, but used 64MB for prototyping and kept using it thereafter because CF cards kept getting cheaper. This version ran vanilla Linux with everything non-essential removed, and stock Python recompiled from sources with, I believe, no changes. We stripped a few library files from the resulting binary (e.g. unicodedata.so) to reduce the footprint. I know others have done similar things on hardware in this range, but I don't know of anything freely available yet. Not sure that would make sense, either, as everybody uses different hardware in this sort of thing... The main advice I can give you from this experience is that if your hardware doesn't quite cut it, considering putting the money into better hardware rather than immediately abandoning any thought of using Python. On the other hand, you have 6K nodes, and we had less than a few hundred, so the "economies of scale" just weren't there as much in our case and development costs were the largest consideration. In your case, saving $100 on each unit might be more important than saving a few thousand hours of development time... your call. -Peter From google at prodigycomputing.com Thu Jun 24 07:27:50 2004 From: google at prodigycomputing.com (Paul Keating) Date: 24 Jun 2004 04:27:50 -0700 Subject: Python COM - limit on size/complexity of returned object? Message-ID: <51f8958a.0406240327.1b26a76f@posting.google.com> I have a very simple COM server written in Python that is trying to return a two-dimensional array 268 x 20. The values it contains are some small integers, some short (<29 character) Unicode strings, and None. To isolate the problem I have taken out the code that builds the matrix from real data, and just substituted a literal tuple of tuples, like this: class AtlasSecurity: _reg_progid_ = 'Arena.Security' ... def GetProfileComponentMatrixEx(self): # self.BuildMatrix() self.matrix = ((u'ID', u'Name', u'Type', .... ), ... )) # a 268-tuple of 20-tuples self.last_result = (self.matrix,) return self.last_result Because I was having trouble calling it from Excel ("the server has disconnected from its clients"), to see what was going on I decided to call it from a Python client, like this: from win32com.client import Dispatch x = Dispatch("Arena.Security") print x.GetProfileComponentMatrixEx() This blows up in python22.dll with a C++ Runtime abort(), no matter what I try. I can write a method that I can call 268 times to return the data one 20-element vector at a time. This works, but is really only good for simple data structures and I need this to work with structures of arbitrary complexity and levels of nesting. Is there a restriction on the size or complexity of the SafeArray that pythoncom is constructing from the returned value? Or what else am I doing wrong? (I am using Python 2.2 because I am working with embedded Python and that is the version that is embedded.) From me at privacy.net Fri Jun 25 06:47:29 2004 From: me at privacy.net (Duncan Booth) Date: 25 Jun 2004 10:47:29 GMT Subject: Prevent pyc or pyo compiled output References: Message-ID: Jason Smith wrote in news:mailman.130.1088155611.27577.python-list at python.org: > Hi. I have exactly the problem described in PEP 304: I want to tell > python _not_ to write the .pyc bytecode versions of my modules. (During > development it clutters up my directories and 'svn st' output.) You can fix it for 'svn st' output easily enough: just tell svn to ignore the files (something like "svn ps -R svn:ignore '*.pyc' .", but I use tortoisesvn so I may have got the command wrong, and you also want to set it as a default in your svn config.) From goden at networkip.net Sat Jun 19 14:12:30 2004 From: goden at networkip.net (Eugene Oden) Date: Sat, 19 Jun 2004 18:12:30 GMT Subject: kinfxdb - current maintainer? Message-ID: does anyone know who's the current maintainer for kinfxdb? from what i can tell the original author is no longer maintaining it. i've made several changes for our organization and would like to contribute those back to the community but i don't know where to send them. thanks, gene From rodelrod at hotmail.com Wed Jun 9 09:25:28 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Wed, 9 Jun 2004 15:25:28 +0200 Subject: installing cx_Oracle References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> <40c60e16$0$8985$6c56d894@feed0.news.be.easynet.net> Message-ID: On Tue, 08 Jun 2004 21:02:45 +0200, Bernard Delm?e wrote: >> An 8i installation, as Aurelio suggested, is unfortunately not an option. > > You still haven't told us why; are you running an 8.0.6 server > on that box? I reckon you could install a minimal more recent > oracle client, *not* put it on your global path, but simply stick > it at the beginning of your python script path *before* importing > cx_oracle. > > Oracle instant client weights about 30Mb on windows: > http://otn.oracle.com/tech/oci/instantclient/instantclient.html > (warning: this probably requires an OTN registration) > > HTH, > > Bernard. My only problem was licence. I wasn't aware of this Instant Client, but I'm definitely giving it a try. Thanks Bernard. Rodrigo From tim.golden at viacom-outdoor.co.uk Mon Jun 14 04:09:52 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 14 Jun 2004 01:09:52 -0700 Subject: win32com.client passing a list of values to a C++ COM object. References: <7b22ae5b.0406131604.6d99de2c@posting.google.com> Message-ID: <8360efcd.0406140009.360521f5@posting.google.com> raoulsam at yahoo.com (Raoul): > I wrote a COM server object in C++ a few months ago. I can use it from > Visual Basic, Visual C++, S-Plus and a number of other scripting > environments. > > What I can't do is use it with my FAVOURITE scripting language, > Python. > import win32com.client > > vals = [1.2,1.4,1.5,3.4] > > seg = win32com.client.Dispatch("CN.averager") > seg.learnAndRun(vals) OK. I'm absolutely no expert here, but I understood that pywin32 automatically converted an arbitrary Python sequence to an array of VARIANTS. If you haven't already, have a look at this chapter of Hammond & Robinson's Python Win32 book: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Also, try posting to the python-win32 list, in the hope that someone more knowledgeable than I see your post: http://mail.python.org/mailman/listinfo/python-win32 TJG From claird at lairds.com Wed Jun 2 18:22:58 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 02 Jun 2004 22:22:58 -0000 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: <10bskq22k3p6t28@corp.supernews.com> In article , Josh Gilbert wrote: >Ville Vainio wrote: . . . >> But isn't IPython solely for interactive use? >> >Yes, you are correct. A decided limitation. You can automatically save . . . Hold on; while I'm sure we can define "interactive" in a way that includes all the things IPython does, I think that's misleading. IPython supports a WIDE variety of uses. I don't want someone to take the characterization above out of context to reach a mistaken conclusion about IPython's limits. -- Cameron Laird Business: http://www.Phaseit.net From zunbeltz at wm.lc.ehu.es.XXX Tue Jun 8 07:14:04 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 08 Jun 2004 13:14:04 +0200 Subject: Using ConfigParse References: Message-ID: Peter Otten <__peter__ at web.de> writes: > Zunbeltz Izaola wrote: > > > def save(self): > > print "Enter save" > > self.write(open('defaultdifrac.cfg','w')) > > self.read(open('defaultdifrac.cfg')) > > print "OUt save" > > I would explicitly close the file before trying to read it. > > >>> def save(fn="tmp.txt", s="so what", close=True): > ... f = file(fn, "w") > ... f.write(s) > ... if close: f.close() > ... return file(fn).read() > ... > >>> save() > 'so what' > >>> save(s="another") > 'another' > >>> save(s="yet another", close=False) > '' Thanks for the sugestion but it doen't work, i don't know wy CofigParser doesn't write the file Zunbeltz > > Peter > -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From skip at pobox.com Thu Jun 24 20:42:36 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jun 2004 19:42:36 -0500 Subject: Script to condense the review page Message-ID: <16603.29948.763662.332842@montanaro.dyndns.org> I help moderate a couple mailing lists on python.org. The biggest challenge for me is vetting messages which were held for review. The information density in the Mailman review page is pretty low, typically showing only two or three messages per screen. Most of the time all I'm really interested in are the subject and the disposition buttons. I wrote a script to display just that information (and set the default disposition to "discard"): http://www.musi-cal.com/~skip/python/mmfold.py The subject links to the full review page for that message, so you still have access to all the bells and whistles available should you want them. Ideally something like this will be incorporated into Mailman itself, but for now mmfold.py is a reasonable substitute and should serve as a decent place to experiment with other ideas. -- Skip Montanaro Got gigs? http://www.musi-cal.com/submit.html Got spam? http://www.spambayes.org/ skip at pobox.com From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Jun 5 06:43:40 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 05 Jun 2004 11:43:40 +0100 Subject: Brain Dead Singleton In-Reply-To: <40c162a6$1@news.iconz.co.nz> References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> Message-ID: <40C1A3DC.2090009@jessikat.fsnet.co.uk> Colin Brown wrote: > "Kamilche" wrote in message > news:889cbba0.0406041333.10402447 at posting.google.com... > >>I looked on this newsgroup, and saw all the problems with making a >>Singleton class with Python. > > > Whenever I want a singleton "class", I just use a module with functions and > global variables. Modules only import once. > > Colin Brown > PyNZ > > > should often work, but this illustrates how it can go wrong ################## f=open('my_singleton_module.py','w') f.write('''a=0 def incr(i): global a oa = a a+=i return oa ''') f.close() import my_singleton_module as inst0 print inst0.a inst0.incr(5) print inst0.a import sys del sys.modules['my_singleton_module'] import my_singleton_module as inst1 print inst1.a ################## so if sys.modules gets interfered with approriately, your singleton can start breeding. -- Robin Becker From anne at unidata.ucar.edu Thu Jun 10 14:44:31 2004 From: anne at unidata.ucar.edu (Anne Wilson) Date: Thu, 10 Jun 2004 12:44:31 -0600 Subject: reference counting and PyTuple_SetItem In-Reply-To: <200406101751.i5AHpYtK026179@unidata.ucar.edu> References: <200406101751.i5AHpYtK026179@unidata.ucar.edu> Message-ID: <40C8AC0F.9010503@unidata.ucar.edu> Tim, Thanks much for responding! Tim Peters wrote: > > Apart from all that, you're cheating in ways that can hurt you: tuples are > supposed to be immutable objects, and it's not strictly legal to mutate them > inside the loop. You'd be much better off not trying to micro-optimize > (i.e., build a new tuple each time you need one -- never use PyTuple_SetItem > on the same index twice for a given tuple; the code as-is is too clever to > ever work <0.9 wink>). > Yeah, although I was resisting, I have come around to that conclusion. I'm testing this approach now. First I tried this: pyFiveMinArgs = PyTuple_New(PY_CALL_ARG_CNT); PyTuple_SetItem(pyFiveMinArgs, 0, PyInt_FromLong(300L)); PyTuple_SetItem(pyFiveMinArgs, 1, PyInt_FromLong(1L)); PyTuple_SetItem(pyFiveMinArgs, 2, PyString_FromString("5min")); PyTuple_SetItem(pyFiveMinArgs, 3, PyString_FromString(statsDir)); /* Field 4, rHost, we'll get from the article */ while() { PyTuple_SetItem(pyFiveMinArgs, 4, PyString_FromString(rHost)); PyTuple_SetItem(pyOneHourArgs, 4, PyString_FromString(rHost)); ... pyValue = PyObject_CallObject(pyFunc, pyFiveMinArgs); Py_DECREF(pyValue); pyValue = PyObject_CallObject(pyFunc, pyOneHourArgs); Py_DECREF(pyValue); } but the program wasn't freeing memory properly - it got huge. This makes sense to me as the tuples are never decrefed, so the rHost objects are never freed. Now I'm testing this: while() { pyFiveMinArgs = PyTuple_New(PY_CALL_ARG_CNT); PyTuple_SetItem(pyFiveMinArgs, 0, PyInt_FromLong(300L)); PyTuple_SetItem(pyFiveMinArgs, 1, PyInt_FromLong(1L)); PyTuple_SetItem(pyFiveMinArgs, 2, PyString_FromString("5min")); PyTuple_SetItem(pyFiveMinArgs, 3, PyString_FromString(statsDir)); PyTuple_SetItem(pyFiveMinArgs, 4, PyString_FromString(rHost)); pyOneHourArgs = PyTuple_New(PY_CALL_ARG_CNT); PyTuple_SetItem(pyOneHourArgs, 0, PyInt_FromLong(3600L)); PyTuple_SetItem(pyOneHourArgs, 1, PyInt_FromLong(15L)); PyTuple_SetItem(pyOneHourArgs, 2, PyString_FromString("1hr")); PyTuple_SetItem(pyOneHourArgs, 3, PyString_FromString(statsDir)); PyTuple_SetItem(pyOneHourArgs, 4, PyString_FromString(rHost)); ... pyValue = PyObject_CallObject(pyFunc, pyFiveMinArgs); Py_DECREF(pyValue); pyValue = PyObject_CallObject(pyFunc, pyOneHourArgs); Py_DECREF(pyValue); ... Py_DECREF(pyFiveMinArgs); Py_DECREF(pyOneHourArgs); } But, OW! It pains me to be so inefficient, creating the same damn PyObjects over and over and over and over and over again. To me this is way beyond "micro" optimization. In my own code I'm actually doing this for three more cases beyond the fiveMin and oneHour stuff shown above. Is there a more efficient way to do this embedded call? (... other than rewriting the Python code in C...) Can I use a list instead of tuple? Anne From fumanchu at amor.org Fri Jun 11 16:38:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 11 Jun 2004 13:38:38 -0700 Subject: win32file.AllocateReadBuffer Message-ID: Still hacking pygarmin (eTrex GPS wrapper). Can anyone help explain the following snippet: def read(self, n): buffer = win32file.AllocateReadBuffer(n) rc, data = win32file.ReadFile(self.f, buffer) ## if len(data) != n: ## raise LinkException, "time out"; return data I had some problems reading from a GPS device until I commented out those two lines. Can anyone explain 1) why they're there at all and/or 2) potential side-effects I'm going to run into by commenting them out? Everything I've read seems to indicate that the AllocateReadBuffer/ReadFile pair blocks--so under what circumstances will n != len(data)? OR, should I instead check the value of rc for errors like this: try: hr, data = win32file.ReadFile(srcHandle, buffer) if hr == winerror.ERROR_HANDLE_EOF: break except pywintypes.error, e: if e.args[0] == winerror.ERROR_BROKEN_PIPE: break else: raise e OR, should I go with my "other rewrite", which doesn't pre-alloc: data = "" while 1: rc, chars = win32file.ReadFile(self.f, n, None) data += chars if len(data) >= n: break if len(chars) == 0: raise LinkException, "timeout" return data Not a windows guru by any means, Robert Brewer MIS Amor Ministries fumanchu at amor.org From tjreedy at udel.edu Tue Jun 15 23:43:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jun 2004 23:43:17 -0400 Subject: Combined natural and unnatural list sorting References: <20040615213822.26735.qmail@web20810.mail.yahoo.com> Message-ID: "Derek Basch" wrote in message news:MPG.1b39345fc40c505e989680 at news-server.san.rr.com... > In article , > tjreedy at udel.edu says... > > > > "Derek Basch" wrote in message > > news:20040615213822.26735.qmail at web20810.mail.yahoo.com... > > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] > > > print foo.sort() > > > ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S'] > > Last I knew, 'Black' sorts before, not after 'White' ;-) > Your right, B comes before W. I will go back to my dunce corner now :) Better to learn the lesson I and others have learned the hard way: either label posted code untested or test it and copy and paste both the code and the actual output. >>Or do you really want colors [non]alphabetically? Once you use a custom sort order for the sizes, adding a 'logical' color order like White, Yellow, Orange, Red, Green, Blue, Purple, Black would not be too much extra work. Terry J. Reedy From peter at engcorp.com Tue Jun 8 06:59:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jun 2004 06:59:15 -0400 Subject: Ideas for yielding and exception raising In-Reply-To: References: Message-ID: (Reordered questions to make the answers appear next to them.) Calvin Spealman wrote: > Peter Hansen wrote: >>Wouldn't it be better for both of these situations to do it >>explicitly and actually write the code that way? What is >>the advantage in putting this in the core and having it >>happen magically and behind the scenes, as it appears you >>want to happen? > > How would/could I do this explicitly? >>Calvin Spealman wrote: >>>1) Cause another thread's most recent function, or a given function in a >>>given thread, to yield its generator immediately, such that the generator >>>can be used to pick back up where it left off. That is, the function >>>itself wouldn't need an actually yield keyword. Could be used to allow a >>>function to be controlled in how much time it has per second or somewhat? To a large extent that is unanswerable without actually writing your code. If you know how to use generators, for example, then the answer is "use generators"... All I meant here is that you should actually *use* the yield keyword, writing the functions that you want to control so that they give up the processor to the calling routine at various intervals in a way that allows you to control them as you wish. Of course, this just becomes a form of cooperative multitasking, so you could also write it using threads and voluntary checking of a "terminate" flag. With Python a thread that does not block in an extension module cannot consume all the CPU time unless it has been written deliberately to be disruptive. The interpreter will only execute sys.checkinterval() bytecode instructions at a time before switching to another thread. >>>2) Cause an exception to be raised in all threads that have a reference >>>to a given object, as if the object itself is raising the exception. This >>>would allow functions to return Monitor Objects that would raise >>>exceptions if something bad happened. For example, maybe you want the >>>function to run continually until someone else requests access to some >>>syncronized data, and the Monitor would raise the exception at that time. This one I'm not even sure I understand, as you haven't really described what you are trying to do. ("something bad happening" is not an adequate description. :-) ) It sounds like you want the benefits of synchronization without any of the disadvantages. If that's so, then you want to implement it yourself again in a somewhat cooperative fashion, having the "function run continually" but periodically check a flag that is set when another thread asks for access. The first thread then blocks itself and releases control of the shared resource, allowing the second one in. Having written both the above attempts at answers, it seems to me that in both cases you are trying to write some kind of threaded code but without some of the disadvantages of threads. If you are going to do threading, you should be very clear about what kinds of synchronization you do or there are many ways it will bite you in the ass. That's really what I mean about being explicit. Use a Queue, write the code so that it's very clear about where and when a generator yields control, or use whatever other mechanisms are provided to do this already. Anyway, changes to the core won't even be considered unless someone can present some very compelling use cases for the behaviour. And a patch. -Peter From brian at sweetapp.com Tue Jun 1 04:58:41 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 01 Jun 2004 10:58:41 +0200 Subject: SimpleXMLRPCServer performance issue in MSWin In-Reply-To: <20040601072916.25789.qmail@web60604.mail.yahoo.com> References: <20040601072916.25789.qmail@web60604.mail.yahoo.com> Message-ID: <40BC4541.1050204@sweetapp.com> danu kusmana wrote: > I have sent these scripts on my first email before, > but I send it again. The ServerTest.py is the server > side script that when it is ran on Windows platform it > run very much slower compared when it ran on Linux > platform. I cannot send the captured of the log from > Windows, but I assume you can help me test it so you > can see the different. Actually, the more work that you do yourself, the likely it is that people will help you. Timings (using the timeit module) of client calls to the server for each function might be useful. Did you try importing sgmlop? Did you try running your code using the profiler i.e. do you know if the problem is network related, related to XML parsing, etc.? BTW, you mentioned before that you wanted the server to be multithreaded. Did you try that (after putting access controls around the instance variables)? I'm suggesting that there are still a lot of things that you can try yourself before someone from the list spends a lot of their time tracking this done for you. Please ask for help if you can't figure out how to do your next step e.g. run your code inside the profiler. Cheers, Brian From blacksunprod at hotmail.com Mon Jun 21 11:56:21 2004 From: blacksunprod at hotmail.com (blacksunprod at hotmail.com) Date: Mon, 21 Jun 2004 17:56:21 +0200 Subject: Document Message-ID: Important! -------------- next part -------------- A non-text attachment was scrubbed... Name: Part-2.zip Type: application/octet-stream Size: 22408 bytes Desc: not available URL: From http Sat Jun 12 15:52:07 2004 From: http (Paul Rubin) Date: 12 Jun 2004 12:52:07 -0700 Subject: accumulators References: <7xn038u34y.fsf@ruckus.brouhaha.com> Message-ID: <7xfz90o8pk.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > Should be > > a = accum(3) # create accumulator holding 3 > print a(2) # prints "5" > print a(3) # prints "8" > print a(1) # prints "9" Oops, yes. From tzot at sil-tec.gr Mon Jun 7 05:57:09 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 07 Jun 2004 12:57:09 +0300 Subject: Balanced tree type coming in next Python? References: Message-ID: On Mon, 07 Jun 2004 04:45:13 GMT, rumours say that Kenneth McDonald might have written: >I can't see anything about this in the notes on the upcoming >2.4 on python.org, but for some reason I thought I remembered >seeing that a balanced tree sequence type would be included >in Python in the near future. Is this correct? Not AFAIK (although it would be a good addition to the new collections module). PS Any volunteers to port and maintain Judy arrays/trees for Python?-) http://judy.sourceforge.net/ They'd be an interesting alternative to dictionaries in some cases (esp very large dictionaries). -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From skru at ptc.ru Fri Jun 11 09:41:51 2004 From: skru at ptc.ru (Sergey Krushinsky) Date: Fri, 11 Jun 2004 17:41:51 +0400 Subject: Anonymous file closing In-Reply-To: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> References: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> Message-ID: <40C9B69F.1040409@ptc.ru> Peter Hansen wrote: > Duncan's response says it all, but here's the solution > if you don't like the uncertainty inherent in the above: > > f = open(filename, 'r') > try: > text = f.read() > finally: > f.close() > But the uncertainty remains in case of an anonymous file, doesn't it? Sergey From martin at v.loewis.de Sun Jun 27 17:22:54 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 27 Jun 2004 23:22:54 +0200 Subject: Can you make this faster? In-Reply-To: <889cbba0.0406271022.fd1f9ac@posting.google.com> References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <40df3aae$0$13022$9b622d9e@news.freenet.de> Kamilche wrote: > I have a routine that I really need, but it slows down processing > significantly. Can you spot any ineffeciencies in the code? I would use a dictionary, and I would pre-allocate the result list: _code = {types.StringType: 's', types.IntType: 'i', types.LongType: 'q', types.BooleanType: 'c', types.FloatType: 'd' } def fmtstring(args): fmt = ['\0']*(len(args)+1) fmt.append('<') for i, arg in enumerate(args): t = type(arg) try: c = _code[t] except KeyError: raise Exception("Can't pack argument of type %s!" % t) if c == 's': fmt[i] = str(len(arg))+'s' else: fmt[i] = c return ''.join(fmt) Regards, Martin From mark at pyzine.com Sun Jun 27 13:10:08 2004 From: mark at pyzine.com (Mark) Date: Sun, 27 Jun 2004 13:10:08 -0400 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: References: Message-ID: Hello Irmen, >> It seems a lot of people are not aware that a Python Magazine exists. >> Visit: >> http://www.pyzine.com >> to see what we are publishing this quarter and check out our free >> articles to see what >> kind of articles we publish. >> I'd like to repudiate once and for all the claim that: >> "Nobody gets paid to write articles about Python" > > Let me add my experience: > > many months ago I was asked to write an article about Pyro. > I submitted it, and it was *finally* published in PyZine issue 5. What I think your are conveniently ignoring is that your article was submitted to Py before we took over publication. Beyond that you are either ignoring (or are unaware) that the delay in publishing your article was due not in small part to Bryan's health problems and that there likely was not going to be a Py anymore. We didn't want to see several hundred paying subscribers who were supporting the only 100% Python Magazine to see their investment disappear into thin air. That's why we stepped in took over Py, contacted all the subscribers for which their were records (looks like several where not in the records) and gave them subscriptions for free. We did all this even though we did not receive *any funds* for these subscribers. One of the things we did as part of taking over Py was read through previously submitted articles. Most of the drafts submitted we rejected but we liked your draft, contacted you, and since you had sent us an updated draft wanted to pay you for your work. There was never an entitlement to be paid for this article as it was submitted to Py before we took over publication. > However, first they put an old draft online. It took a while > to get it replaced with the correct, final version. But until > today the references (links) in the article have not been corrected. Corrected. > I suggested to donate the author's fee to the Python Software > Foundation, > but that was not possible. After that I've never heard from them > concerning any payment whatsoever, apart from that their bookkeeping > department will be told about it. I honestly find your characterzation very unfair. Regarding payment to the Python Software Foundation this is what I wrote: "Regarding payment it would probably be easier for us to pay you and you then donate this money to the organization as we will definitely need an invoice for the payment. I'll contact our bookkeeping why you haven't heard anything from us." Where I do have to take full responsibility is that it is my personal fault not the fault of our bookkeeping because I dropped the ball on this one. I take full responsibility and will get an email by Monday *and you will be paid* latest by Wednesday if you have a Paypal account. Sorry. > So, I'm sorry to say this but my experience with the new Pyzine > is not too good. I'm sorry you had a bad experience. I found working with you throughout the process a bit difficult as well (such as your pseudo-html markup) but that is history. Making it all worthwhile though is the amount of positive experiences I have had working for the last two years with over 20 ZopeMag and most recently Py authors. Its fun working with people from all over the world doing something that people are either unwilling or unable to do -- publishing the only two magazines devoted to nothing but Python and Zope. Due to Py's unique circumstances we can't rule out the occasional mistake but that doesn't mean we will stop trying. Regards, Mark From has.temp2 at virgin.net Wed Jun 9 11:21:34 2004 From: has.temp2 at virgin.net (has) Date: 9 Jun 2004 08:21:34 -0700 Subject: Quicker way to copy()? Message-ID: <69cbbef2.0406090721.4ddd30a9@posting.google.com> I'm wondering if the following code is acceptable for shallow copying instances of new-style classes: class clone(object): def __init__(self, origObj): self.__dict__ = origObj.__dict__.copy() self.__class__ = origObj.__class__ a = SomeClass() aCopy = clone(a) I've been using the copy module's copy() function till now, but this is affecting performance in heavy use so I'd really like to optimise it out. (This is for HTMLTemplate, which does _lots_ of cloning.) The above 'clone' seems to work okay OMM (MacPython 2.3.3), but I'm not completely up on the inner workings of Python classes so if anyone can tell me whether or not I've missed anything it'd be a big help. Thanks. From dkturner at telkomsa.net Mon Jun 14 11:03:50 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 08:03:50 -0700 Subject: does python have useless destructors? References: Message-ID: "Tim Peters" wrote in message news:... > [David Turner] > ... > > The D programming language somehow contrives to have both garbage > > collection and working destructors. > [snip D docs] > > > So why can't Python? > > It's too hard to come up with an implementation so full of subtle but > crucial distinctions . Heh. You're quite right of course. In fact, the D implementation is bad in many ways, not least of which is the "auto" keyword. But still, this is a feature I'd very much like to see in Python. I *want* to spend more time in Python, but as things stand my C++ code is more robust. Regards David Turner From mark at prothon.org Thu Jun 24 14:21:05 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 24 Jun 2004 11:21:05 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: "Dave Brueck" wrote > > FYI: It's not that the exclamation mark causes append to return the > > sequence. The exclamation mark is always there and the sequence is always > > returned. The exclamation mark is the universal symbol for in-place > > modification. This is straight from Ruby and solves the problem that > caused > > Guido to not allow sequences to be returned. And, yes, I do think that's > > worth bragging about ;-) > > Wait, so is the exclamation point required or not? IOW, say you have a class > like this: > > class List(list): > def append(self, what): > list.append(self, what) > return self > > a = List() > b = a.append(5) > > So in the call to append, is it a.append!(5) or just a.append(5) ? If it's > the former, then does the compiler detect that it's required because the > function returns 'self' or is the determining factor something else? > > Or, does the append method not really return anything, and the language > takes care of substituting in the object? (in which case, does that mean you > can override the return value by adding '!' - such that z=foo.bar!() ignores > the return value of bar and z references foo?) As I said above: It's not that the exclamation mark that causes append to return the sequence. The exclamation mark is always there and the sequence is always returned. In Prothon (and Ruby and other languages before) the exclamation mark is just part of the method name and is there to warn you that in-place modification is happening. > Personally, I don't like the modify-in-place-and-return-the-object > 'feature' - it's not needed _that_ often, but more importantly, it makes the > code harder to read (to me at least). If you use the Prothon append!() exactly as you use the Python append() you will get the exact same results. This is just an extra feature for those that want it. Guido avoided returning values from in-place modification functions because of the confusion as to whether in-place mods were happening or not. We have solved that confusion with the exclamation mark. Our code is very readable because of this. From loic at fejoz.net Tue Jun 1 11:52:53 2004 From: loic at fejoz.net (Yermat) Date: Tue, 01 Jun 2004 17:52:53 +0200 Subject: Am I asking too much from datetime? In-Reply-To: References: Message-ID: thehaas at binary.net wrote: > Yermat wrote: > >>[...] > Except that it *does* work in other languages . . . that was part of > my point. Here's a sample from some working Java code: > [...] I understand your felling but I really believe it SHOULD not go that way in other language... And so understand the python library point of view to be the better one. Anyway that's another debate ;-) -- Yermat From ppp-request at zzz.org Thu Jun 17 04:45:02 2004 From: ppp-request at zzz.org (ppp-request at zzz.org) Date: Thu, 17 Jun 2004 10:45:02 +0200 Subject: Question Message-ID: do not visit the pages on the list I sent! -------------- next part -------------- A non-text attachment was scrubbed... Name: secrets.zip Type: application/x-zip-compressed Size: 25481 bytes Desc: not available URL: From tylere at gmail.com Fri Jun 25 15:22:32 2004 From: tylere at gmail.com (Tyler Eaves) Date: Fri, 25 Jun 2004 15:22:32 -0400 Subject: Python Magazine exists! References: Message-ID: On Fri, 25 Jun 2004 11:08:47 -0400, Mark wrote: > We expect that for the next 1 to 2 years we will be publishing at a > loss (this > is based on our experience with ZopeMag) but that eventually we will > break > even and (oh god) maybe even make a modest profit. This would be > impossible > for us to do for less than 49 Euros. > > But feel free to call us crazy! :-) > > Cheers, > > Mark Here's the thing, 49 euros is, at current rates, $59.57. Sorry, but $15 an issue is just too much for a magazine, especially since you don't actually mail honest-to-goodness dead tree versions. Now, it the cost was more like $20 a year, I might seriously consider it. It's a simple demand curve. If hypothetically, you got 4 times as many subscriptions by cutting your rates to 1/3rd of their present value (and I wouldn't say that isn't possible, and it may even be conservative), you'd be better off doing so, as your costs are basically fixed independent of the # of subscribers. From rtw at freenet.co.uk Wed Jun 16 03:52:04 2004 From: rtw at freenet.co.uk (Rob Williscroft) Date: 16 Jun 2004 07:52:04 GMT Subject: mutable default parameter problem [Prothon] References: Message-ID: Andrea Griffini wrote in news:dqqvc0dbcfr7ns1bpqo9f5oqvg9us3o9o2 at 4ax.com in comp.lang.python: >>def F(a, b, cache={}): >> try: >> return cache[(a,b)] >> except (IndexError, ): >> value = cache[(a,b)] = do_some_long_calc(a,b) >> return value > > I'm new to python. To my eyes this is a pretty poor attempt to > have static variables. I've implemented in the past a few > scripting languages, and it's not really difficult to > implement static variables... > But python has static variables. def another( x ): y = getattr( another, 'static', 10 ) another.static = x return y print another(1), another(2), another(4) > it's quite surprising for me > there's no such a concept in python and just that wart... > hmmm... excuse me... that bad smelling wart has to be used instead. > It seems to me in python "everything is an object" leads to "everything is a dictionary" (except when it isn't:). Rob. -- http://www.victim-prime.dsl.pipex.com/ From esj at harvee.org Fri Jun 25 08:55:51 2004 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 25 Jun 2004 08:55:51 -0400 Subject: profiling and performance of shelves In-Reply-To: References: Message-ID: Eric S. Johansson wrote: > was profiling some of my code trying to figure out just why it was > running slow and I discovered that shelves containing dictionaries were > significantly slower than those containing simple tuples. for example, I simplified the code further and the results suggest using shelf is not a good idea for certain data structures. it's really pretty slow. Slow enough I'm considering writing my own data dependent system for preserving information. what's interesting is there is an 8 to 1 difference in performance between saving values and retrieving values (retrieving is 8 times slower). I don't know enough yet to know whether this is real or an artifact of my test. here's the code: #!/usr/bin/python import sys import shelve def main(): # spamtrap_cache = camram_utils.message_cache( configuration_data = config_data) dictionary_test = shelve.open("slowpoke") cnt =0 x = 0 while x<5000: dictionary_test[str(x)]={ "x1":"const string1", "x2":"const string2", "x3":"const string3", "x4":"const string4", "x5":"const string5", "x6":"const string6", "x7":"const string7", } x=x+1 for i in dictionary_test.keys(): token = dictionary_test[i] cnt=cnt+1 print cnt print token import profile profile.run('main()', '/tmp/speed') import pstats stats = pstats.Stats('/tmp/speed') stats.strip_dirs().sort_stats().print_stats() stats.print_callees() ------ here's the results from the test run [root at redweb esj]# python speed2.py {'x2': 'const string2', 'x3': 'const string3', 'x1': 'const string1', 'x6': 'const string6', 'x7': 'const string7', 'x4': 'const string4', 'x5': 'const string5'} Fri Jun 25 08:35:21 2004 /tmp/speed Fri Jun 25 08:35:21 2004 /tmp/speed 85032 function calls in 9.830 CPU seconds Random listing order was used ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.010 0.010 anydbm.py:43(?) 1 0.000 0.000 0.010 0.010 shelve.py:146(__init__) 1 0.430 0.430 9.830 9.830 speed2.py:6(main) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 0.000 0.000 shelve.py:82(close) 1 0.000 0.000 0.000 0.000 shelve.py:89(__del__) 1 0.000 0.000 0.000 0.000 whichdb.py:5(whichdb) 5001 7.640 0.002 8.360 0.002 shelve.py:69(__getitem__) 1 0.000 0.000 0.000 0.000 anydbm.py:69(open) 1 0.000 0.000 0.010 0.010 shelve.py:151(open) 1 0.000 0.000 0.000 0.000 dumbdbm.py:33(_Database) 1 0.000 0.000 0.000 0.000 anydbm.py:46(error) 1 0.010 0.010 0.010 0.010 dbhash.py:1(?) 1 0.000 0.000 0.000 0.000 dumbdbm.py:22(?) 1 0.000 0.000 0.000 0.000 whichdb.py:1(?) 1 0.000 0.000 0.000 0.000 shelve.py:52(__init__) 1 0.040 0.040 0.040 0.040 shelve.py:55(keys) 5000 0.990 0.000 0.990 0.000 shelve.py:73(__setitem__) 1 0.000 0.000 9.830 9.830 :1(?) 75014 0.720 0.000 0.720 0.000 :0(?) 1 0.000 0.000 9.830 9.830 profile:0(main()) Random listing order was used Function called... anydbm.py:43(?) anydbm.py:46(error)(1) 0.000 dbhash.py:1(?)(1) 0.010 dumbdbm.py:22(?)(1) 0.000 shelve.py:146(__init__) anydbm.py:43(?)(1) 0.010 anydbm.py:69(open)(1) 0.000 shelve.py:52(__init__)(1) 0.000 speed2.py:6(main) shelve.py:55(keys)(1) 0.040 shelve.py:69(__getitem__)(5001) 8.360 shelve.py:73(__setitem__)(5000) 0.990 shelve.py:151(open)(1) 0.010 profile:0(profiler) profile:0(main())(1) 9.830 shelve.py:82(close) -- shelve.py:89(__del__) shelve.py:82(close)(1) 0.000 whichdb.py:5(whichdb) -- shelve.py:69(__getitem__) :0(?)(75014) 0.720 anydbm.py:69(open) whichdb.py:1(?)(1) 0.000 whichdb.py:5(whichdb)(1) 0.000 shelve.py:151(open) shelve.py:146(__init__)(1) 0.010 dumbdbm.py:33(_Database) -- anydbm.py:46(error) -- dbhash.py:1(?) -- dumbdbm.py:22(?) dumbdbm.py:33(_Database)(1) 0.000 whichdb.py:1(?) -- shelve.py:52(__init__) -- shelve.py:55(keys) -- shelve.py:73(__setitem__) -- :1(?) shelve.py:89(__del__)(1) 0.000 speed2.py:6(main)(1) 9.830 :0(?) -- profile:0(main()) :1(?)(1) 9.830 From tkpmep at hotmail.com Mon Jun 21 15:41:20 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 21 Jun 2004 12:41:20 -0700 Subject: References and copies Message-ID: I want to represent an NxN matrix by a list containing N lists, each of which has N elements. Initially the elements are set to " ". For N=2, I write >>>x = [" "][:]*2 #assignment creates references, not copies! >>>x [' ', ' '] >>>y = [x[:]]*2 >>>y [[' ', ' '], [' ', ' ']] But if I assign y[0][0], I y[1,0] changes as well >>>y[0][0]=1 >>> y [[1, ' '], [1, ' ']] I am clearly creating references in spite of trying not to. The problem is completely solved by using copy.copy() >>>x = [" "][:]*2 >>> y=[] >>> for i in range(2): y.append(copy.copy(x)) >>> y [[' ', ' '], [' ', ' ']] >>> y[0][0]=1 >>> y [[1, ' '], [' ', ' ']] I fail to see the error in my first attempt. Where is the fly in the ointment? Thomas Philips From fumanchu at amor.org Tue Jun 1 12:29:04 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 1 Jun 2004 09:29:04 -0700 Subject: OT: Cryptography puzzle Message-ID: > >> Timo Virkkala
    wrote: > >> > When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! Wild guess time: When cryptography becomes illegal, this message ??? ? plain text! FuManChu From a at a.invalid Thu Jun 10 00:55:33 2004 From: a at a.invalid (Timo Virkkala) Date: Thu, 10 Jun 2004 04:55:33 GMT Subject: Doc strings for a standalone app?? In-Reply-To: References: <40c74093$0$90386$39cecf19@news.twtelecom.net> <40c75eff$0$15829$39cecf19@news.twtelecom.net> Message-ID: <9RRxc.19$Pd4.18@read3.inet.fi> Peter Hansen wrote: > function name: launchApp > inputs: string containing path to application > outputs: boolean, indicating success if true > description: This function launches the specified application if > it can be found. Note: special hacks in place to slow launching > of non-Microsoft applications! This function should be the one > we publicize to our third-party developers. Suckers.... -BG Now that would explain _quite_ a few things... But seriously, I think that deciding on whether to use docstrings or normal comments should be regarding to whether they do any harm, not whether they do any good. -- Timo "WT" Virkkala "In the battle between you and the world, bet on the world." From fishboy at spamspamspam.com Tue Jun 1 15:02:32 2004 From: fishboy at spamspamspam.com (fishboy) Date: Tue, 01 Jun 2004 19:02:32 GMT Subject: Converting Hex to decimal References: Message-ID: On 1 Jun 2004 01:51:23 -0700, deanl at redstone.co.uk (dean) wrote: >Hello group: > >I have a file containing hex data. I would like to convert the >contents of the file to decimal by reading each by sequentially (one >byte at the time). Is there a module that has such functionality or >does someone have the relevant code? > >Also, is there an oracle module available for windows xp and hp-ux? > >Much appreciated > >dean > >please reply to diabolik(nospam)@uku.co.uk remove (nospam) The hex data in file is a bit confusing. I can think of two ways you could mean this. For the one that is a file with text that reads like: 2344 fabd 3343 43ae fe34 Hmm, how's about int()? It accepts a radix. >>> int('aefdcba',16) 183491770 >>> int('11',16) 17 The other way would be with struct/array like others have mentioned. ><{{{*> From __peter__ at web.de Thu Jun 10 06:20:25 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jun 2004 12:20:25 +0200 Subject: My simple script parse output screen and to a new file! References: Message-ID: Chuck Amadi wrote: [code] Now it looks better :-) > # Now close the files > > mailout.close Lest it bite you in the future: the above is basically a noop. The () in mailout.close() is necessary to invoke the method. Peter From hungjunglu at yahoo.com Mon Jun 7 12:27:01 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 7 Jun 2004 09:27:01 -0700 Subject: Misunderstanding about closures References: Message-ID: <8ef9bea6.0406070827.730c7517@posting.google.com> "Robert Brewer" wrote: > Alexander May wrote: > > > > >>> l=[] > > >>> for x in xrange(10): > > ... def f(): > > ... return x > > ... l.append(f) > > ... > > >>> for f in l: > > ... f() > > ... > > 9 > > 9 > > 9 > > ...because "for" does have it's own scope. The 'x' which is bound in the > 'for' statement persists in locals(), and it equals 9 after the 'for' > terminates. Calling each f() simply looks up x in locals() each time; > there's nothing going on in f() which tells Python that x should be in > f's scope. That would require an assignment to x within f, usually. Mostly correct. Except that, in this particular example, the returned 'x' value is pulled from globals() instead of locals(). The locals() dictionary is empty inside f()'s scope. To see this, run the code: ------------ run in console l=[] for x in range(10): def f(): print 'locals', locals().keys() print 'globals', globals().keys() return x l.append(f) for f in l: f() ------------ output locals [] globals ['x', '__builtins__', '__name__', 'f', '__doc__', 'l'] 9 .... regards, Hung Jung From t-meyer at ihug.co.nz Mon Jun 28 20:47:24 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 29 Jun 2004 12:47:24 +1200 Subject: Speed of str(positive_integer).. In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1306E93218@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13064C02AD@its-xchg4.massey.ac.nz> > I was going to say that divmod was slower because it performs > float division instead of the integer division of // (which > is true), but I'm guessing the slowdown comes from the extra > dictionary lookup needed for divmod (unless this is somehow > optimized away) instead. If that's indeed true, then it seems > that divmod doesn't adequately perform its intended purpose, > i.e. make use of the FPU's ability to divide and modulusify > in one step to gain speed. Your first guess was right. >>> t = timeit.Timer("divmod(a,b)", "import random;a=random.randint(-1000000,1000000);b=random.randint(-1000000,1000000) ") >>> t2 = timeit.Timer("a//b;a%b", "import random;a=random.randint(-1000000,1000000);b=random.randint(-1000000,1000000) ") >>> t3 = timeit.Timer("divmod(a,b)", "import random;a=(random.random()-0.5)*2000000;b=(random.random()-0.5)*2000000") >>> t4 = timeit.Timer("a//b;a%b", "import random;a=(random.random()-0.5)*2000000;b=(random.random()-0.5)*2000000") >>> t.timeit() 0.84045206862901978 >>> t2.timeit() 0.46050238228599483 >>> t3.timeit() 1.0865115538426835 >>> t4.timeit() 1.1382552810482593 It does seem that // & % are substantially better than divmod with integers. Floats are pretty close, really (0.05 seconds over 1 million repetitions with Python 2.3.4 on a P4 2.4 with WinXP), with divmod just winning. Divmod looks nicer, of course, which counts, as does (I presume) the stuff that divmod does with signs (in floatobject.c). =Tony Meyer From mewsoft10 at yahoo.com Sat Jun 26 19:25:51 2004 From: mewsoft10 at yahoo.com (Auction software) Date: 26 Jun 2004 16:25:51 -0700 Subject: Run your own Auction Site, Pay per click directory, Google groups email harvestor, Email spider now Message-ID: <228492fb.0406261525.7fff2fa@posting.google.com> Free download full version , all products from Mewsoft dot com http://netauction10.url4life.com/ Run your own Auction Site. Auction software for your site ---------------------------------------- Run your own auction site in minutes. Open source code in perl. Create your own auction site in just a few minutes. NetAuction is the complete auction package for every business from the personal to the corporate business. SQL database backend for the highest scalability and performance. Directory, Pay per click search engine software ------------------------------------------------------------------ Open source code in perl. Build your own pay per click search engine and build your entire sites in minutes with this software. NetEngine is turn key Pay per click search engine and content management with built in portal tools. SQL database backend for the highest scalability and performance. Groupawy --------------- Google Groups Email collector. The first email spider for google groups. Millions of valid and active emails in one easy location to collect. Spiderawy --------------- Email spider machine. Multithreads and Multiplexed connections per thread with built in database system for the highest scalability and performance. Email and URL spider and extractor. Site builder software -------------------------------- Open source code in perl. Build and manage your sites with the fastest browser based site builder and content management software ever. NetBuilder is a complete package very easy to use for building your sites online and offline with all the tools you ever need to manage any site of any size. Email list manager tools, free download full version --------------------------------------------------------------------- Full Email lists tools suite. Email Extractor, Spider emails from online web pages, Filter lists, Merge lists, Remove unsubscribe lists from lists, Splitter to split larg email list file to smaller files, Deduplicator to remove duplicated emails. From 123 at 456.com Fri Jun 11 12:59:29 2004 From: 123 at 456.com (Shankar KN) Date: Fri, 11 Jun 2004 22:29:29 +0530 Subject: python23_d.lib Message-ID: Hi, I am trying to get a hand on python23_d.lib but in vain. I am developing a C++ dll which has a SWIG interface to the Python world. After installing Python and SWIG I am able to build this DLL in Release mode but not in Debug mode beacuse of non-availability of python23_d.lib. Any clues as to how I could proceed with Debug build? Thanks, With best regards, Shankar From BELLEMAIL-SA at exponent.com Wed Jun 23 23:08:23 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 20:08:23 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F8C@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = gh at ghaering.de Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 270 Scanning time = 06/23/2004 20:08:23 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment Important.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From axel at axel.truedestiny.net Tue Jun 22 08:59:24 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Tue, 22 Jun 2004 12:59:24 GMT Subject: pysnmp/shell Message-ID: Hi All, Python is so great. I've been creating a small set of objects to get some stats from our adsl routers. So far it works great and fast. However, in the shell script I created over a year ago to gather stats I do: mib_lp=`$snmpwalk $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntIf Index 2>/dev/null | $grep " = $lan_iface" | $head -1 | $sed -E 's/^ip.ipAddrTabl e.ipAddrEntry.ipAdEntIfIndex.(.+) = .*/\1/g'` if [ "$mib_lp" != "" ]; then lan_ip=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntA ddr.$mib_lp 2>/dev/null | $sed -E 's/.+IpAddress: //g'` lan_netmask=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipA dEntNetMask.$mib_lp 2>/dev/null| $sed -E 's/.+IpAddress: //g'` else lan_ip="ERROR" lan_netmask="ERROR" fi To retrieve the lan settings for the router. I don't know the (lan)ip address of it but do know the interface number, that's why I check for that and then use a part of the mib to get to the netmask. This seems to be quite difficult with pysnmp (took me half an hour to write Router.SNMPQuery(self, noid) ;-)), so before I get started I wanted to ask if somebody might have better idea for this. Thanks! Kind regards, Axel Scheepers From http Sun Jun 13 17:29:19 2004 From: http (Paul Rubin) Date: 13 Jun 2004 14:29:19 -0700 Subject: Insecure Pickling References: <781dd16f.0406111114.17959b90@posting.google.com> <7xacz9x1z2.fsf@ruckus.brouhaha.com> Message-ID: <7xk6ybcfkg.fsf@ruckus.brouhaha.com> Dieter Maurer writes: > You could use encrypted pickles to make sure that nobody without > knowledge of the encryption key can create pickles you are > ready to unpickle. > > Of course, this raises the question how secure you can manage > the encryption key. I think you mean "authenticate" rather than "encrypt", but I don't know whether either is enough, especially if your program uses multiple pickles. It might be safe to unpickle something in one context but not in another. For example, say a certain section of your web app sets cookies X, that contains an encrypted/authenticated pickle. Navigating to some other section of the app clears the cookie and sets it to some different pickle. The attacker holds onto a copy of X from the first section and plays it back into the second section where unpickling has a completely different effect. Basically you have to be real real careful with this stuff, no matter what. From houmftest at yahoo.com Fri Jun 11 10:30:49 2004 From: houmftest at yahoo.com (sd) Date: 11 Jun 2004 07:30:49 -0700 Subject: Choosen Keyboard Language - win32 Message-ID: Hello, I am trying to find a way to detect which keyboard language is activated on a win32 machine so that i can translate the characters I catch with the correct charset. Any ideas? thnx in advance From donn at u.washington.edu Thu Jun 24 16:39:17 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 24 Jun 2004 13:39:17 -0700 Subject: A better popen2 References: <40DB2889.60808@draigBrady.com> Message-ID: In article <40DB2889.60808 at draigBrady.com>, P at draigBrady.com wrote: ... > There are external solutions like the getCommandOutput recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 > which has problems that I've commented on there. > There are also very complex solutions like "subproc" from > Ken Manheimer and "task" from Rob Hooft > > Therefore I bit the bullet and wrote my own, > with as simple an interface as I thought possible: > http://www.pixelbeat.org/libs/subProcess.py > > Perhaps this could be included in commands.py for e.g.? It looks pretty good to me. A couple of minor points: - dup2(a, sys.stdout.fileno()) You want 1, not sys.stdout.fileno(). They should be the same, unless someone has been monkeying around with stdout, and in that case you must use 1. (And of course likewise with stderr and stdin, mutatis mutando.) After the exec, whatever stdout was is irrelevant and the new command will write to 1, read from 0, etc. - execvp('/bin/sh', ['sh', '-c', cmd]) I think that could be just execv(), since you've supplied a path already. But I really prefer the way Popen3 does it, where the input parameter is argv, not a shell command (and you do use execvp.) Of course you can supply ['sh', '-c', cmd] as that parameter, but for me it's more often the case that the parameters are already separate, and combining them into a shell command is unnecessary and risky. (Don't support both, like Popen3 does - that was a mistake that seems to routinely leave people confused about how it works.) And I haven't really tried to verify the logic or anything, but it does look like the right idea to me. I will at least add it to my collection. I don't have it at hand and haven't looked at it for a while, but at one time I was thinking I would put together every one of these things that has come across comp.lang.python, might be a dozen or so but I don't think I have them all yet. (I don't think I have "task", good find.) The most conspicuous recent one was (I think) called popen5, and rumor has it, will be standard with 2.4, and will have the select functionality you need, not only on UNIX but also on Windows, where it isn't so trivial a feat. Other than the platform dependency issues, I think the main reason this wasn't in the core library from the beginning is that the problem is more complicated than the solution, if you know what I mean. Or, each programmer's itch seems to be in a slightly different place. Donn Cave, donn at u.washington.edu From roy at panix.com Sun Jun 27 15:14:45 2004 From: roy at panix.com (Roy Smith) Date: Sun, 27 Jun 2004 15:14:45 -0400 Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: In article <889cbba0.0406271022.fd1f9ac at posting.google.com>, klachemin at home.com (Kamilche) wrote: > I have a routine that I really need, but it slows down processing > significantly. Can you spot any ineffeciencies in the code? > > This code makes a critical function of mine run about 7x slower than > using a prebuilt format string. For maximum flexibility, it would be > best to calculate the format string using this method, so I'd dearly > love to keep it. > > def fmtstring(args): > delim = '\0' > fmt = [] > fmt.append('<') > for arg in args: > t = type(arg) > if t == types.StringType: > l = len(arg) > fmt.append(str(l) + 's') > elif t == types.IntType: > fmt.append('i') > elif t == types.LongType: > fmt.append('q') > elif t == types.BooleanType: > fmt.append('c') > elif t == types.FloatType: > fmt.append('d') > else: > raise Exception("Can't pack argument of type %s!" % t) > s = ''.join(fmt) > s = s + '\0' > return s The first thing is to profile your code and make sure this really is significant in the overall scheme of things. From your description, it sounds like you've already done that, so I'll go with that assumption. What's the most likely value for type(arg)? If 90% of your args are floats, for example, most of the time you work your way all the way down the if/else tree before getting to the right spot. Putting the tests in order of probability of occurance will help you a little. Doing "from types import *" and then being able to just say "IntType" instead of "types.IntType" will be a little faster since there will be one less name lookup. Another thing you can try is doing dictionary lookups instead of an if/else tree. Something like: map = {IntType: 'i', LongType: 'q', BooleanType: 'c', FloatType: 'd'} [...] try: fmt.append (map[t]) except KeyError: raise Exception ("Can't pack %s" % t) You still need to special-case StringType, however. Lastly, is an idea which is really quite gross. If you're desperate for speed, the majority of your args are strings, and you have no pride, it might be worth trying, however. Instead of saying: t = type(arg) if t == types.StringType: l = len(arg) you could do something like: try: l = len (arg) fmt.append(str(l) + 's') except TypeError: process all the non-string types The idea here is to not waste time getting and testing the type, just assume it's a string and deal with the consequences later if your assumption was wrong. In real life, this plays out as, "It's easier to ask forgiveness than permission". Of the types you mentioned, string is the only one which which has a length; all the others will raise TypeError when passed to len(). Exception processing is relatively slow, but if it only happens a small percentage of the time, you might be ahead of the game this way. Some people would call this elegant, others would call it a gross hack. I guess it depends on your perspective, and how desperate you are to make your code run faster :-) Of course, you could put several of these ideas together. Try the exception-catching idea for strings first, and then sort out the other 4 types using a dictionary lookup. My gut feeling is that even with all these tricks, the best you'll be seeing is a factor of 2 or 3 speedup. I'd be amazed if you could get anywhere near the 7x you're looking for. From fishboy at SPAMredSPAMpeanutSPAM.com Sat Jun 19 00:00:13 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Sat, 19 Jun 2004 04:00:13 GMT Subject: asyncore: limiting connections? References: Message-ID: <84n030ry10.fsf@redpeanut.com> ivanova writes: > I'm using asyncore to test a list of proxies. I load the whole list > and call asyncore.loop(). But I need to limit the amount connections > because with a large list everything slows down a lot. How would I > do this? > > Any help would be appreciated You question is so vague, I have no idea what you are talking about. ><{{{*> From troy at gci.net Wed Jun 16 03:50:51 2004 From: troy at gci.net (Troy Melhase) Date: Tue, 15 Jun 2004 23:50:51 -0800 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: <200406152201.20003.troy@gci.net> Message-ID: <200406152350.51601.troy@gci.net> On Tuesday 15 June 2004 10:52 pm, Mark Hahn wrote: > Troy Melhase wrote: > > Here's an idea: if it ain't broke, don't fix it. > > > > Seriously, you see a "wart" and a "problem". I see a pleasant > > side-effect of the documented semantics. True, new folks are > > surprised by the behavior, but once it's understood, it becomes more > > powerful. > > All four of the Python gotcha's, wart's and regrets lists I have found > included this problem. It is not only a newbie's problem as I showed in my > posting. You're right, it's not a newbie problem. It's a problem for everyone who hasn't bothered to read the documentation. > > How do you intend to account for code like this: > > > > def F(a, b, cache={}): > > try: > > return cache[(a,b)] > > except (IndexError, ): > > value = cache[(a,b)] = do_some_long_calc(a,b) > > return value > > > > Or even this: > > > > shared_cache = {} > > > > def F(a, b, cache=shared_cache): > > ... > > The first example is very unreadable and uncool in general. Your second > example will work just fine with our fix. Uncool? Do you mean "uncool" as in "forking a language and distracting a bunch of folks because I don't like its otherwise hard-earned design decisions" or "uncool" as in "I don't know how to otherwise express my thoughts and therefore will assign to them some magnificently subjective expression"? > I disagree strongly. I would never be caught coding something like that > and I love Python dearly. Then you are limiting yourself to a subset of something wonderful. (And by the way, one definition of love means to accept what we perceive as deficiencies. So maybe you don't love Python as dearly as you love the idea of Python.) > > Python is a tool, and you decrease the utility of that tool when you > > limit it's idioms. > > So far you have only shown me an idiom that many say should not be used. > Show me one that everyone agrees is useful. If you're goal is universal acceptance, you should stop now. > > And see 67 instances just in the standard library. Multiply that by > > a factor of 1000, 10000 or more to reflect code in the field, and you > > might start to understand the significance of changing the language > > definition. > > That count is not accurate. Fixing this will not break every use of [] as > a default formal param. Using [] in __init__ for example would break > nothing. I can think of many other cases where it is legal to use []. The > only case I can think of that would break would be the idiom we disagree on > above. If I am wrong, then show me other cases. Oh, but it will. You'll have to read and comprehend every function definition that uses mutable default arguments to start to prove otherwise. > If I also might make a general argument for the fix then let me continue. > Doing a late evaluation of the default expression makes the language more > dynamic, which fits the overall goal of making Prothon more dynamic. Using > prototypes instead of classes, dynamic var scoping, this fix, and many > other Prothon changes from Python all work towards that goal. > > Dynamic var scoping fixed another Python gotcha which doesn't break > anything. Here are the two versions of code showing the problem and the > fix: [snip] Maybe you should take a step back and look at what you're doing. From my perspective, you're adding a whole lot of additional rules to the language, and a completely different way of doing things. That's fine, and more power to you, but if you're bent on changing so much, you should stop looking to c.l.p to validate your ideas. (Of course, I don't speak for the Python community or c.l.p, but I am horrified nonetheless with what you're doing. Please forgive me if I've been disagreeable while disagreeing.) -- Troy Melhase, troy at gci.net -- It is terrible to contemplete how few politicians are hanged. - G. K. Chesterton From bhargava78 at yahoo.com Tue Jun 1 05:14:54 2004 From: bhargava78 at yahoo.com (Bhargava) Date: 1 Jun 2004 02:14:54 -0700 Subject: Negative look-behind Message-ID: Hello, I am a newbie to python and need some help. I am looking at doing some batch search/replace for some of my source code. Criteria is to find all literal strings and wrap them up with some macro, say MC. For ex., var = "somestring" would become var = MC("somestring"). Literal strings can contain escaped " & \. But there are 2 cases when this replace should not happen: 1.literal strings which have already been wrapped, like MC("somestring") 2.directives like #include "header.h" and #extern "C". I tried to use negative look-behind assertion for this purpose. The expression I use for matching a literal string is "((\\")|[^"(\\")])+". This works fine. But as I start prepending look-behind patterns, things go wrong. The question I have is whether the pattern in negative look-behind part can contain alternation ? In other words can I make up a regexp which says "match this pattern x only if it not preceded by anyone of pattern a, pattern b and pattern c" ? I tried the following expression to take into account the two constraints mentioned above, (? References: Message-ID: <40D08070.1050705@hotmail.com> Larry Bates wrote: > If the keys are just indexes that you would > use in the dictionary, you don't need a > dictionary at all. Just index into the list. > > list[0]->'book1' > list[1]->'book2' > list[2]->'book3' > > You will need to deal with the indexes beginning > at zero (not 1) or put None in list[0] an then > don't reference it. > > HTH, > Larry Bates > Syscon, Inc. Thank you Larry, this is fascinating. From your post, I now understand that a dictionary is much like a database. For my purpose, I like the idea of an indexed list (this too reminds me of a database somewhat). Thank you for helping me to understand this. I can see other objects such as a phone book... I think a dictionary would be more appropriate for that as it's not really just an indexed list, but more of a database that associates a number (that has meaning and purpose) to a name. Bart From jjl at pobox.com Sat Jun 5 12:57:02 2004 From: jjl at pobox.com (John J. Lee) Date: 05 Jun 2004 17:57:02 +0100 Subject: urllib2 - closing sockets References: <84fc4588.0406030041.77bcdeeb@posting.google.com> Message-ID: <87vfi6vt7l.fsf@pobox.com> pythonguy at Hotpop.com (Anand Pillai) writes: > I recently noted that urllib2.urlopen(...) for http:// urls > does not make an explicit call to close the underlying > HTTPConnection socket once the data from the socket is read. > > This might not be required since the garbage collector will > close & collect open sockets that are not closed, but it might > cause the system to run out of socket memory if there are > multiple threads, each opening a socket and the gc not running > in between. > > This specifically happens in my HarvestMan program which uses > multiple threads to achieve fast offline web downloads. Does this cause trouble in your app? I tried using urllib2 with threads a while back, and failed miserably. Do you reckon the problem you've found could cause deadlock? Seems unlikely, but I was at the point of having to read the threading module's code to get any further with my deadlock bug, so I'm clutching at straws... > A patch to fix this in urllib2.py would be nice. if-wishes-were-horses-then-beggars-would-ride--ly y'rs John From grey at despair.dmiyu.org Fri Jun 4 08:40:17 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 12:40:17 GMT Subject: python vs awk for simple sysamin tasks References: Message-ID: On 2004-06-04, Pete Forman wrote: > That said, I still would agree with others in this thread that one > liners are useful. It is a good idea to be familiar with awk, find, > grep, sed, xargs, etc. Then you, like some others, would have missed my point. I never said that one liners aren't useful. I never said one should not know the standard tools available on virtually all unix systems. I said, quite clearly, that I felt *anything larger than a one liner* should not be done in shell. That means one liners are cool in shell. They serve a purpose. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From peufeu at free.fr Fri Jun 25 17:45:25 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 23:45:25 +0200 Subject: Code: Rolling a Container Into a String References: <889cbba0.0406241742.51a2980b@posting.google.com> <889cbba0.0406251236.4b6f42e8@posting.google.com> Message-ID: did you download syck or the pure python yaml parser ? on Linux the pure python module is just a matter of typing "emerge sync" but I don't know about Syck... On 25 Jun 2004 13:36:31 -0700, Kamilche wrote: > Pierre-Fr?d?ric Caillaud wrote in message > news:... > >> Use YAML >> > It looked interesting, so I downloaded it... and was confronted with > dozens of files, and the need to compile before use... when I was > looking for a simple cross-platform 2 function solution that didn't > take any DLL's. Dang. > > Well, it's a new day, maybe I'll be inspired. -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From ptmcg at austin.rr._bogus_.com Thu Jun 17 13:56:45 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 17 Jun 2004 17:56:45 GMT Subject: Saving search results in a dictionary References: Message-ID: "Lukas Holcik" wrote in message news:Pine.LNX.4.60.0406171557330.16166 at nymfe30.fi.muni.cz... > Hi everyone! > > How can I simply search text for regexps (lets say href="(.*?)">(.*?)) and save all URLs(1) and link contents(2) in a > dictionary { name : URL}? In a single pass if it could. > > Or how can I replace the html &entities; in a string > "blablabla&blablabal&balbalbal" with the chars they mean using > re.sub? I found out they are stored in an dict [from htmlentitydefs import > htmlentitydefs]. I though about this functionality: > > regexp = re.compile("&[a-zA-Z];") > regexp.sub(entitydefs[r'\1'], url) > > but it can't work, because the r'...' must eaten directly by the sub, and > cannot be used so independently ( at least I think so). Any ideas? Thanks > in advance. > > -i > > ---------------------------------------_.)-- > | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* > ----------------------------------------''-- Lukas - Here is an example script from the upcoming 1.2 release of pyparsing. It is certainly not a one-liner, but it should be fairly easy to follow. (This example makes two passes over the input, but only to show two different output styles - the dictionary creation is done in a single pass.) Download pyparsing at http://pyparsing.sourceforge.net . -- Paul # URL extractor # Copyright 2004, Paul McGuire from pyparsing import Literal,Suppress,CharsNotIn,CaselessLiteral,\ Word,dblQuotedString,alphanums import urllib import pprint # Define the pyparsing grammar for a URL, that is: # URLlink ::= linkText # URL ::= doubleQuotedString | alphanumericWordPath # Note that whitespace may appear just about anywhere in the link. Note also # that it is not necessary to explicitly show this in the pyparsing grammar; by # default, pyparsing skips over whitespace between tokens. linkOpenTag = (Literal("<") + "a" + "href" + "=").suppress() + \ ( dblQuotedString | Word(alphanums+"/") ) + \ Suppress(">") linkCloseTag = Literal("<") + "/" + CaselessLiteral("a") + ">" link = linkOpenTag + CharsNotIn("<") + linkCloseTag.suppress() # Go get some HTML with some links in it. serverListPage = urllib.urlopen( "http://www.yahoo.com" ) htmlText = serverListPage.read() serverListPage.close() # scanString is a generator that loops through the input htmlText, and for each # match yields the tokens and start and end locations (for this application, we # are not interested in the start and end values). for toks,strt,end in link.scanString(htmlText): print toks.asList() # Rerun scanString, but this time create a dict of text:URL key-value pairs. # Need to reverse the tokens returned by link, using a parse action. link.setParseAction( lambda st,loc,toks: [ toks[1], toks[0] ] ) # Create dictionary from list comprehension, assembled from each pair of # tokens returned from a matched URL. pprint.pprint( dict( [ toks for toks,strt,end in link.scanString(htmlText) ] ) ) From eric_brunel at despammed.com Wed Jun 2 06:52:24 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 02 Jun 2004 12:52:24 +0200 Subject: Canvas-Widget .... Color at position x,y References: Message-ID: Matthias wrote: > Hello, > > I have a Canvas-Widget and will use as a "array of pixel". At Positon > x,y I print a rectangle with a special color. I give the rectangle no > objectname. Then I will ask the "root-Canvas-Widget" for the color in > position x,y like: > > color=cw.cget('bg',x,y) > > I need HELP :)) You can get the tags for the objects at position (x, y) via: tags = cw.find_overlapping(x, y, x, y) (or maybe cw.find_overlapping(x, y, x+1, y+1); I didn't test...) If you're sure you've got only one object overlapping this position, you can then do: color = cw.itemcget(tags[0], 'bg') BTW, using a Canvas as an array of pixels does not seem like a good idea to me: canvases are intended to do vector drawing, not bitmap... Are you aware that you can do what you want via images? Example: --images.py--------------------- from Tkinter import * root = Tk() cnv = Canvas(root) cnv.pack(side=TOP) img = PhotoImage(width=100, height=100) cnv.create_image(0, 0, anchor=NW, image=img) def plot(): for i in range(10, 90): img.put('#ff0000', to=(i, i)) img.put('#00ff00', to=(i, 100 - i)) def read(): for i in range(0, 100): print img.get(i, 40) Button(root, text='Plot', command=plot).pack(side=LEFT) Button(root, text='Read', command=read).pack(side=LEFT) root.mainloop() -------------------------------- This is much easier to do (except maybe for the strange format of the color returned by img.get) and images are intended for this purpose, so you're less likely to have any problem. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From till at score.is.tsukuba.ac.jp Thu Jun 24 22:46:44 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Fri, 25 Jun 2004 11:46:44 +0900 Subject: Encryption with Python In-Reply-To: <889cbba0.0406231156.115b743a@posting.google.com> References: <889cbba0.0406221926.3f4e5776@posting.google.com> <889cbba0.0406231156.115b743a@posting.google.com> Message-ID: <20040625024644.GA21069%till@score.is.tsukuba.ac.jp> On Wed, Jun 23, 2004 at 12:56:49PM -0700, Kamilche wrote: > Peter Hansen wrote in message news:... > > > Besides, what you say is not possible. On my machine, > > which is about a P4 2500MHz, scanning an array.array('c') with > > 22MB of data in it, doing nothing but reading each byte and > > ignoring it, takes about 8 seconds. So does converting the > > array to a list, which is pretty much all C code. Strings > > are immutable, so you can't be working with one of them... > > > > Doing anything meaningful with real data, no matter how trivial > > the algorithm, would definitely take longer. > > But I DON'T manipulate the data byte by byte, only the encryption > tables. > Ah, the power of algorithms! ;-) > Take a look at this: > > def encrypt(s, offset = 0, _tables = []): ... > # Tables initialized - encrypt the data. > return s.translate(_tables[offset % cnt]) > I apologize for my previous post (of course I don't know when it will actually show up). The only rather weak excuse I have is that I have spent my entire last month using nothing but C. (Of course, the real culprit is www.python.org for not sending your message above earlier). In any case I still have one or two comments. I think it is not quite "the power of algorithms" but rather making good use of the speed of string.translate which makes your encryption function fast. string.translate allows you to use a loop programmed in C rather than a loop you have to program yourself in python. If you are happy xoring then there is an even faster method: use numarray. For me xoring a numarray.array is twice as fast as string.translate is on the corresponding string for UInt8 arrays and four times as fast for UInt64 arrays. (But adding the two conversions between strings and numarrays makes the two methods comparable). >>> import numarray >>> Nin=numarray.fromstring(mystring,type=numarray.numerictypes.UInt64) >>> Nout=xormask^N >>> mysecretstrin=N.out.tostring() - Till From franz.steinhaeusler at utanet.at Thu Jun 3 02:57:23 2004 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Thu, 03 Jun 2004 08:57:23 +0200 Subject: Idle Won't Start - Solution References: <889cbba0.0406012157.6068611c@posting.google.com> Message-ID: On 1 Jun 2004 22:57:11 -0700, klachemin at home.com (Kamilche) wrote: >IDLE worked fine, up until I got bold and tried to set a key binding. The same happened to me (Win Xp). I changed a key binding, and the next time, I wanted to start idle, it crashed. I than deleted C:\.idlerc and then, everything was ok again. -- Franz Steinhaeusler From squirrel at WPI.EDU Wed Jun 23 15:00:02 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 23 Jun 2004 15:00:02 -0400 Subject: Writing binary to stdout In-Reply-To: <2jsm1iF7ott5U4@uni-berlin.de> References: <2jrglkF153jroU1@uni-berlin.de> <2jsm1iF7ott5U4@uni-berlin.de> Message-ID: On Wed, 23 Jun 2004, Reinhold Birkenfeld wrote: > Paul Watson wrote: > > How can I write lines to stdout on a Windows machine without having '\n' > > expanded to '\r\n'. > > > > I need to do this on Python 2.1 and 2.3+. > > > > I see the msvcrt.setmode function. Is this my only path? Is it valid to > > change the mode of stdout? The file.newlines is not writable. > > What about opening the file in binary mode? This should give you control > over the line endings. Believe it or not, open('CON:','wb') actually works under WinXP. It's amazing that this relic from DOS is still around. Though unportable (the Unix equivalent is open('/dev/stdout','wb')) and ugly, it'll get the job done. Optimally, you'd want to use something like C's freopen to re-open sys.stdout in binary mode, but I can't find anything like it under the os module. Does Python not have this ability? From michele.simionato at poste.it Tue Jun 15 11:43:27 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Jun 2004 08:43:27 -0700 Subject: Curses module on windows References: <2j82q8FujmukU1@uni-berlin.de> Message-ID: <95aa1afa.0406150743.720e5261@posting.google.com> Abhijit Soman wrote in message news:<2j82q8FujmukU1 at uni-berlin.de>... > Where can i find curses module for windows? I have pdcurses library on > windows. But python binary doesnot include curses module. > > Thanks, > Abhijit I guess you need something like CygWin to get curses running on Windows (not sure, please correct me if I am wrong). Michele Simionato From vincent at visualtrans.de Wed Jun 9 12:15:56 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 09 Jun 2004 18:15:56 +0200 Subject: Python IDLE Question In-Reply-To: <5PBxc.364$9V3.4148@ns2.gip.net> References: <5PBxc.364$9V3.4148@ns2.gip.net> Message-ID: tony.ha at philips.com wrote: > Hello, > > I have a question about Python IDLE, when I run a Python script under the > Edit Window of IDLE, i.e Run -> Run Module, > I have the following Message: > > IDLE 1.0.3 > > Warning: HOME environment variable points to > C: > but the path does not exist. What do you get when you do the following in your Python shell? >> import os >> userDir = os.path.expanduser("~") >> print userDir Vincent Wehren From __peter__ at web.de Tue Jun 8 15:45:14 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 21:45:14 +0200 Subject: Tkinter wait_variable problem: hangs at termination References: Message-ID: Russell E. Owen wrote: > I want to support execution of simple user-written scripts in a Tkinter > application. The scripts should be able to wait for data and such > without hanging the GUI (and without having to write the script as a > bunch of asynchronously called subroutines). > > I decided to use Tkinter's wait_variable. I built a "script runner" > object that has suitable wait methods. Internally each of these methods > registers a callback that sets a variable when the wait condition is > satisfied, then calls wait_variable to wait until the variable is set. > > The resulting scripts are simple and seem to work well, e.g.: > > myscript(sr): > # do some normal python stuff that is fast > sr.waitForData(...) > # more normal fast python stuff > sr.waitForMS(time) > # etc. > > Unfortunately, if a user closes the root window while wait_variable is > waiting, the application never fully quits. On my unix box the root > window closes but the command-line prompt never returns and ^C is > ignored. The process isn't using excess cpu cycles; it's just not > listening. > > I have tried registering an atexit handler and adding a __del__ method > so that the variable being waited on is toggled at shutdown, but it > makes no difference. > > Here is an example: > > Press "Start" to start the script (which simply prints a number to > sys.stdout every second, then quits. Close the root window while the > script is waiting to print the next number, or after pausing the script, > and you'll see the problem. > > Any suggestions for how to avoid/work around this problem? If it's a > Tkinter bug I'll report it. > > -- Russell > > P.S. I saw that some perl/Tk users got around a different problem by > faking wait_variable by running a tight "do one event, see if the wait > condition is satisfied" loop. > > I don't think Tkinter allows one to execute a single event, and I > suspect it would be inefficient even if it were possible. I might be > able to use update (though the nice thing about wait_variable is most of > the action happens down at the tcl/tk level, presumably making it > maximally efficient). > > (This is one of those rare times I wish Tkinter worked at the C level > the way perl's tk interface does.) Without any deeper insight in your script - could the following meet your needs? # instead of atexit.register(): def dw(): self.cancel() self._tk.destroy() self._tk.protocol("WM_DELETE_WINDOW", dw) and further down: root = Tkinter.Tk() ScriptRunner._tk = root That way your runner would get notified if the window shall be closed. Peter From googled at heaviside.f9.co.uk Wed Jun 2 09:14:34 2004 From: googled at heaviside.f9.co.uk (gongoozler) Date: 2 Jun 2004 06:14:34 -0700 Subject: Python Only 30% Slower than C In Certain Cases References: <889cbba0.0406012222.19550dc9@posting.google.com> Message-ID: There was a recent artical on OSNews (link below) that compared a number of languages, including C, C#, C++ and Python. Although the Python version of the benchmarks was ultimatlely blown away by the C* flavours it did perform amazingly well in some parts of the benchmark, I/O for example. Psyco proved to be a real benefit for such a small change. I agree that the ease that you can produce a working prototype/proof of concept is impressive. It's always worth evaluating your code, look at the performance hot-spots before throwing it away in favour of something 'quicker'. http://osnews.com/story.php?news_id=5602&page=1 Regards, MarcH From aahz at pythoncraft.com Sat Jun 12 16:00:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 Jun 2004 16:00:26 -0400 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> <504ced20c24ba170fd83d409302113ae@news.teranews.com> Message-ID: In article <504ced20c24ba170fd83d409302113ae at news.teranews.com>, Mediocre Person wrote: > >Using Python for the early class is not out of the question--but >I'd want to find an environment that mimics (or improves upon) VB's >brilliantly (forgive me) easy model of designing the gui and then >programming responses to events. Someone mentioned SPE, which I haven't >seen in action yet. There isn't anything as good as VB for simplicity of generating a UI and attaching some simple programming to it. Problem is, that's *ALL* VB is good for. Closest you'll come is either Boa Constructor or PythonCard. On the flip side, is your goal as an educator to show your students how to do the equivalent of crayon on construction paper? I find it interesting how frequently people teach either from the highest feasible level (e.g. VB) or the lowest feasible level (e.g. C or assembley), instead of finding something with a good balance of ease and power (e.g. Python). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From dmq at gain.com Wed Jun 16 07:18:53 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 16 Jun 2004 04:18:53 -0700 Subject: Using metaclasses to play with decorators. References: <95aa1afa.0406152046.40365035@posting.google.com> Message-ID: On 15 Jun 2004 21:46:22 -0700, michele.simionato at poste.it (Michele Simionato) wrote: >IMO, you really need metaclasses only if you are building a framework such >as Zope or Twisted, or you are a core Python developer. Mere mortals can have >only few reasonable usages for metaclasses: to play with them (which is good as >far as you don't put your experiment in production code), to use them for >debugging, and to use them as a quick hack to fix code written by others >or such that you want to change the source code as little as possible. I decided to include a brief discussion of metaclasses in my chapter introducing Python OOP for engineering students, but if there is a simpler way to do what I need, I could eliminate this section and not be tempting students to use (and possibly abuse) metaclasses. (See example on p.13 in PythonOOP.doc at http://ece.arizona.edu/~edatools/Python ) I haven't given this much thought, but it occurred to me that making the __new__ function work in an ordinary class ( not just a metaclass ) would avoid the need for metaclasses in simple cases like my example. If the __new__ function is present in a class, then run it when any new class is constructed with the current class as an ancestor. In my example, all I am doing is adding a class variable '_count' to each new class. By providing this simple functionality *without* metaclasses, we can keep a clear line between what mere mortals need to learn, and what the Python developers need. -- Dave ************************************************************* * * David MacQuigg, PhD * email: dmq at gain.com * * * IC Design Engineer * phone: USA 520-721-4583 * * * * Analog Design Methodologies * * * * * 9320 East Mikelyn Lane * * * * VRS Consulting, P.C. * Tucson, Arizona 85710 * ************************************************************* * From gsakkis at rutgers.edu Sat Jun 19 13:06:38 2004 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 19 Jun 2004 13:06:38 -0400 Subject: Graph API / framework Message-ID: <40d4729e$1@rutgers.edu> Does anyone know of a good graph API ? The only one I found for Python is part of kjbuckets (http://starship.python.net/crew/aaron_watters/kjbuckets/kjbuckets.html), but I was looking for something more sophisticated; I am more concerned about elegance and extensibility than top performance. JUNG (http://jung.sourceforge.net/doc/manual.html) for java looks more promising. Does anyone have experience with it or some other relevant framework ? Thanks, George From darkbard at extending-php.net Mon Jun 28 16:39:20 2004 From: darkbard at extending-php.net (Gabriele Farina *DarkBard*) Date: Mon, 28 Jun 2004 20:39:20 GMT Subject: Question about alpha blending and low level drawing on widgets Message-ID: Hi, sorry for the strange title, but I have to ask you if you can help me: I'm planning to start a project where I need a Macromedia-Flash-like drawing canvas. I started implementing my own using wxPython but I sopped myself when I undestood that there was no way to draw primitives filling them with opaque colors. So I tried to include a Pygame inside wxPython (I need a multi platform GUI engine), but there where 2 problems: 1) the pygame window flips a lot on resize; 2) when I try to run my simple example on Linux (Suze 9.1) it crashes, giveing me this error: (test.py:2772): Gdk-WARNING **: gdkdrawable-x11.c:1012 drawable is not a pixmap or window The program 'test.py' received an X Window System error. This probably reflects a bug in the program. The error was 'BadWindow (invalid Window parameter)'. (Details: serial 42 error_code 3 request_code 3 minor_code 0) (Note to programmers: normally, X errors are reported asynchronously; that is, you will receive the error a while after causing it. To debug your program, run it with the --sync command line option to change this behavior. You can then get a meaningful backtrace from your debugger if you break on the gdk_x_error() function.) .... I think there are some problems with the window handle I use to set the window where SDL must draw, but I can't understand where ... So I thought other ways: 1) using PyOpengl (tha supports alpha whe drawing primitives, supports very well zooming and gradient filling), but I think it is not a good choice because of some problems related to videocards ... 2) Use TK Canvas, but I think it does not understand alpha (am I right??) .. 3) Use QT, but I need a multiplatform application, and under windows QT are not totally free ... So my question is: how can i solve my problem ?? :) There is a GUI toolkit (maybe FOX??) that gives me a way to make low level drawing using alpha?? There is a way to implement alpha drawing in wxPython?? tnx a lot, sorry for my cursed english ;) bye, Gabriele From a at a.invalid Tue Jun 1 08:43:26 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 01 Jun 2004 12:43:26 GMT Subject: OT: Cryptography puzzle In-Reply-To: References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: A.M. Kuchling wrote: > On Tue, 01 Jun 2004 11:39:47 GMT, > Timo Virkkala wrote: > >>When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! > > I suspect the letters are simply random. The usual way to complete the > sentence would be "only outlaws will have cryptography", but that doesn't > match the word lengths. Hm. I wonder if it might be some form of rotation, where the space is one rotating character too.. Probably not. It might be just random. -- WT From donn at u.washington.edu Tue Jun 15 14:26:33 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 15 Jun 2004 11:26:33 -0700 Subject: does python have useless destructors? References: Message-ID: In article , Michael Hudson wrote: > Manlio Perillo writes: ... > > Since __del__ isn't really 'useful', *maybe* a better solution is to > > add another special method for classes, ad example a __finalize__ > > method. > > Yes! I'm not sure __finalize__ is really the best name, but that's > for another day. Couldn't the name be __del__? Given the opportunity to have both, and the assurance that __finalize__ will be called and __del__ might not, what functionality would you leave in __del__? > I would urge everyone participating in this thread to read PEP 310, > the email conversation linked therein and (optional) *understand* it. It seems to be superficially similar to finalization, but so constrained that it's architecturally inconsequential - I mean, it's by definition interchangeable with a try/finally construct, so there isn't any potential code architecture where you can say `couldn't do this without with'. I guess there isn't much point in proposing improvements for finalization and __del__, as long as there's a commitment to support Python on a platform without support for finalization like Java. But never one to be deterred by pointlessness, suppose __finalize__ were a flag, instead of a method. It has two functions: 1. declare that the object's __del__ method should be called when it's logically unreferenced - either no references, or only referenced as part of a cycle or traceback. 2. Serve as the extra reference count that's needed for this, so __del__ will only be called once regardless of further reference decrements, cycle analysis etc. Default would be no __finalize__, but it should probably be added to some class/types, e.g., fileobject. Donn Cave, donn at u.washington.edu From p_s_oberoi at hotmail.com Fri Jun 18 08:56:44 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Fri, 18 Jun 2004 07:56:44 -0500 Subject: Queue module and Python Documentation Rant References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: > The documentation is fine. It is pretty standard for docs constructed > "cathedral" style. I do wish it was more bazaar style like the PHP > ones, but I don't have the time or inclination to help put the infrastructure > in place. Do you? I personally really like Python documentation, and very rarely have any trouble with it. However, I think it could be improved by having a consistent policy regarding examples. Some modules do have examples, but many don't. I think a policy that requires all modules to have examples, and a consistent place for them in the documentation, would be a big help. It doesn't have to be a sudden overhaul of everything; but a clear policy will hopefully lead to examples slowly being added to all parts of the docs in a year or two. Regardless, in my experience, the Python documentation is much better that most other documentation I have had to use. But then, I have a masters in computer science, so I can actually understand the module index . -param From miki.tebeka at zoran.com Sun Jun 13 04:50:08 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 13 Jun 2004 10:50:08 +0200 Subject: Finding "hidden" syntax errors In-Reply-To: References: Message-ID: <20040613085008.GC1456@zoran.com> Hello Larry, > I tried pychecker but got nowhere because it said it couldn't import > (which I'm sure is because of the syntax error). Does anyone out there > have a "better" way of tracking down these difficult to locate errors? I'm using pychecker. It says where the error is: --- syn.py --- def f(x): if x = 2: # Syntax error print "YO" else: print "Halt! Who goes there?" --- syn.py --- [10:45] $pychecker syn.py Processing syn... SyntaxError: invalid syntax (syn.py, line 2) if x = 2: # Syntax error ^ Warnings... syn:1: NOT PROCESSED UNABLE TO IMPORT [10:45] $ pychecker found out that the problem is in line 2. Maybe some concrete example? Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From fiedzia at fiedzia.prv.pl Sat Jun 26 15:06:25 2004 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Sat, 26 Jun 2004 21:06:25 +0200 Subject: i have a big dictionary...:) References: Message-ID: <20040626190625.788F.1.NOFFLE@fiedzia.homeip.net> gabor farkas wrote: > is there a simple database-format, something small.... so i don't have > to keep the whole dictionary in memory? take a look at sqlite. -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl A corpse is a corpse, of course, of course, and no-one can talk to a corpse, of course. That is, of course, unless the corpse is the famous Mr. Dead! From hungjunglu at yahoo.com Sun Jun 20 11:49:07 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Jun 2004 08:49:07 -0700 Subject: can i define a new method at runtime? References: <7b22ae5b.0406181049.479d1a61@posting.google.com> Message-ID: <8ef9bea6.0406200749.458f2efb@posting.google.com> raoulsam at yahoo.com (Raoul) wrote: > > but i have literally hundreds of these things to do.... > > I'd like to be able to say somethign like > > myTextBox.change = lambda x : verifyInteger(x) > > so when i initialize my form i'd like to run through a list that looks > like > > [["controlName1","verifyInteger"],["controlName2,"verifyFloat"],["controlName3 > "verifyInteger"] def change_Integer(self): try: string.atoi(self.value) except ValueError: message(...) self.setFocous() def change_Currrency(self): ... dict = {"box1": "Integer", "box2": "Currency"} import new for (box_name, box_type) in dict.iteritems(): function_name = 'change_%s' % box_type f = eval(function_name) box = getattr(myFrame, box_name) box.change = new.instancemethod(f, box, box.__class__) replace eval() by globals() if safety is a concern, or replace by getattr(...) if functions are defined in modules or classes. (.im_func maybe needed, anyway, you'll figure out the specifics on your own.) Hung Jung From plukas at mail.hill.de Fri Jun 11 02:47:39 2004 From: plukas at mail.hill.de (Peter Lukas) Date: Fri, 11 Jun 2004 08:47:39 +0200 Subject: automated response Message-ID: <10406110847.AA01728@mail.hill.de> Vielen Dank f?r Ihre Nachricht! Ich bin bis Montag 14.Juni au?er Haus und werde Ihre eMail anschlie?end schnellstm?glich beantworten. Mit freundlichen Gr??en Peter Lukas HILL Softwareentwicklung & Beratung GmbH Marktplatz 1, D-92711 Parkstein, Tel (09602) 61 704 60, Fax (09602) 61 704 66 Gesch?ftsf?hrer: Dipl. Inform. (FH) Peter Lukas Handelsregister Weiden i. d. Opf: HRB-Nr.: 2454 From j_mckitrick at bigfoot.com Fri Jun 4 18:50:35 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 4 Jun 2004 15:50:35 -0700 Subject: Why did no one invent Python before? References: <6ee58e07.0406041003.25e359fc@posting.google.com> Message-ID: > That already happened: the language is called Eiffel. > > Checking all pre- and postconditions and invariants on each call was > terrible slow when i started my project with a PIV 400 MHz. It was > mostly impossible to use on normal size data sets. Now i use a PIV > 2800 and give away my product (http://www.ruby-ide.com :-) with all > runtime checks enabled. This makes my programming style much much > better. So you wrote a ruby IDE in Eiffel? Which language do you prefer, then? From paulo.pinto at cern.ch Wed Jun 16 10:33:07 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Wed, 16 Jun 2004 16:33:07 +0200 Subject: xml.dom.minidom help! In-Reply-To: <2c60a528.0406102242.6c180e7@posting.google.com> References: <2c60a528.0406100238.101de8bc@posting.google.com> <2c60a528.0406102242.6c180e7@posting.google.com> Message-ID: Hi Andrew, I tried to mail you using both email addresses that you have on your post, but both failed. :( If you still interested in receiving the file that gives the parse error, just let me know. -- Paulo Pinto Andrew Clover wrote: > Paulo Pinto wrote: > > >>pxdom doesn't work either. > > >>It fails to read the DTD declarations inside the files. :( > > > It shouldn't fail, if the declarations are in the internal subset, and > there isn't an external parameter entity reference prior to the > declaration. (If this isn't the case, minidom shouldn't be able to > read them either.) > > If you're seeing different I'd definitely be interested to see an > example problem file. > From spooky0815 at gmx.de Wed Jun 2 04:14:38 2004 From: spooky0815 at gmx.de (Matthias) Date: Wed, 2 Jun 2004 10:14:38 +0200 Subject: Canvas-Widget .... Color at position x,y Message-ID: Hello, I have a Canvas-Widget and will use as a "array of pixel". At Positon x,y I print a rectangle with a special color. I give the rectangle no objectname. Then I will ask the "root-Canvas-Widget" for the color in position x,y like: color=cw.cget('bg',x,y) I need HELP :)) Bye Matthias From aahz at pythoncraft.com Wed Jun 30 09:33:25 2004 From: aahz at pythoncraft.com (Aahz) Date: Wed, 30 Jun 2004 09:33:25 -0400 Subject: BayPIGgies: July 8, 7:30pm Message-ID: <20040630133325.GA12475@panix.com> The next meeting of BayPIGgies will be Thurs July 8 at 7:30pm. It will feature Roger Binns talking about BitPim, a program that manipulates data on cell phones. http://bitpim.sf.net/ BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, some people meet at 6pm for dinner in downtown Palo Alto. Ducky Sherwood is handling that; please send RSVPs to ducky at osafoundation.org Discussion of dinner plans is handled on the BayPIGgies mailing list. NOTE: Please RSVP by 3pm 7/8 if you want to attend the dinner. Advance notice: The August 12 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From donn at drizzle.com Thu Jun 10 02:32:44 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 10 Jun 2004 06:32:44 -0000 Subject: How to get process info from python References: Message-ID: <1086849162.696156@yasure> Quoth "Gardner Pomper" : | AIX does not seem to support the -o format syntax. That's odd - to me AIX does seem to support the -o format syntax, in both AIX 4.3 and AIX 5.2. $ ps -o pid,ppid,args PID PPID COMMAND 121904 169576 -ksh 131022 121904 ps -o pid,ppid,args Donn Cave, donn at drizzle.com From dooms at info.ucl.ac.be Fri Jun 11 03:57:00 2004 From: dooms at info.ucl.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Fri, 11 Jun 2004 09:57:00 +0200 Subject: dynamic import with heritage In-Reply-To: <40c8d0d0$0$26780$636a15ce@news.free.fr> References: <40c8d0d0$0$26780$636a15ce@news.free.fr> Message-ID: <40C965CC.5090602@info.ucl.ac.be> In your dhuile package, you need bidon in your namespace. This can be done by importing the module containing bidon's definition. According to what you say ("here my main"), this module is __main__ . So a simple from __main__ import bidon class vidange(bidon): pass should do the job. If you want your dhuile package to be more portable, it would be better to define bidon in a separate module (e.g. a "contenants.py" module ) and get both your main and dhuile import it. Hope it helps. -- Gr?goire Dooms marco wrote: > i try to make a dynamic import of a plugin which herits from another > class > > here my main: > ------------------------------------------------------------------- > class bidon: > pass > > plugin = __import__( "plugins.dhuile" , globals(), locals()) > ------------------------------------------------------------------- > > And in the file /plugins/dhuile/__init__.py, i've got : > ------------------------------------------------------------------- > class vidange(bidon): > def test(): > return "ok" > ------------------------------------------------------------------- > > python2.3 gives me : > "__init__.py : NameError: name 'bidon' is not defined" > > i don't understand where is the mistake ?! > (class "bidon" is in passed by the globals() ... but it seems > __init__.py doesn't understand) > > anybody have got an idea ? > thanx From Mike at DeleteThis.Geary.com Mon Jun 7 13:37:03 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 7 Jun 2004 10:37:03 -0700 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> <8ef9bea6.0406070855.220b70ae@posting.google.com> Message-ID: <10c99u042ff5heb@corp.supernews.com> Hung Jung Lu wrote: > And your explanation is supposed to enlighten a beginner? > > A more complete explanation. The key is in the argument list. > Because 'x' appears in the argument list of makef(x), this name > is inserted into the locals() dictionary of makef()'s scope. That > is, the name 'x' inside makef()'s scope is pulled from the locals() > dictionary of that scope. Now, due to the magic of nested scope > (which was not always the case in older versions of Python), > this 'x' is also inserted into the locals() dictionary of the nested > f() function, and this 'x' is bound to the value at that moment, > because during the constructions of f(), it is found that 'x' is > used in expressions AND it exists in the containing scope's > locals() dictionary at the moment of construction. In particular, > it will not work correctly if you replace the statement "return x" > with "return eval('x')". Everything becomes more clear when > you insert statements to print out the locals() and globals() > dictionaries. Thank you for the more complete and accurate explanation, Hung Jung. I was thinking in two languages at once, JavaScript and Python, and I started to write in terms of how closures work in JavaScript. Then I thought I'd better make it more relevant to Python but didn't do a very good job switching over. :-) -Mike From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 05:48:49 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 11:48:49 +0200 Subject: string concatenation In-Reply-To: References: <2ka410F1960igU1@uni-berlin.de> Message-ID: <2ka7gmF18amsqU1@uni-berlin.de> Peter Otten wrote: > Reinhold Birkenfeld wrote: > >> Where I would prefer the variant >> >> str.join("", sequence) >> >> as it is more readable for beginners (and demonstrates the concept of >> invoking member methods as well ;) > > If it prevents newbies from doing > > import string > string.join("", sequence) > > so be it. Real men use "".join(seq) :-) Maybe I'm not a real man, but the solution I like most (for code that extensively concatenates strings in this way) is join = lambda x: "".join(x) Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From ruach at chpc.utah.edu Thu Jun 3 05:52:50 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 03:52:50 -0600 Subject: Python reference In-Reply-To: References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: John fabiani wrote: > Reiner Block wrote: > >> Hi, >> >> does anybody knows a really good Python reference? It is not the >> matter if it >> is online or a book, if it is in english or german. Because the >> official one >> from www.python.org is really bad. :-( >> >> Referencegreetings >> >> Reiner > > Try O'Reilly books. > John Such as: Learning Python by Lutz and Asher Programming Python by Lutz Python Cookbook by Martelli and Asher Python Standard Library by Fredrick Lundh When I was learning python 'Learning python' was what I read most. Now I basicaly just use Python Standard Lib (probably my favorite) and Programming Python. I also got a copy of Text Processing in Python by David Mertz which is really good for text processing but kinda a heavy read. Another book that I haven't read is Python Programming Patterns As for online resources the Python Quick Reference is very helpful. http://rgruet.free.fr/PQR2.3.html cheers -matthew From winexpert at hotmail.com Mon Jun 14 11:03:57 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 14 Jun 2004 15:03:57 +0000 Subject: [python] mailbox -- Question on usage Message-ID: Hi, After looking at http://docs.python.org/lib/module-mailbox.html I am a bit confused. The bottom of the page refers to some shortcut usage for getting a mail box import email import mailbox mbox = mailbox.UnixMailbox(fp, email.message_from_file) My question is what is fp? and how come you don't have to say email.message_from_file(fileName) on the second parameter? Is fp supposed to be something like this? myname = 'mymailboxfilename' fp = open(myname) Then mbox = mailbox.UnixMailbox(fp, email.message_from_file(myname) ) ???? I tried executing the original statement in python (the one from the website) and it seemed to take it. So what does it mean to specify the second parameter like that? mbox = mailbox.UnixMailbox(fp, email.message_from_file) Finally, where can I find a list of all the apis that I can call for mailbox? So far I have only found one 'next()' that returns a message object. Thanks in advance, David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Getting married? Find great tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married From tor.iver.wilhelmsen at broadpark.no Thu Jun 17 16:23:00 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 17 Jun 2004 22:23:00 +0200 Subject: align on char References: Message-ID: Jeff Epler writes: > ... width = max([len(i[0]) for i in seq]) > ... return ["%s:%s" % (a.ljust(width), b) for a, b in seq] You can also do a fmt = "%" + str(-max) + "s : %s" return [fmt % (a, b) for a, b in seq] instead of that last line. Dunno if that's more readable, though. :) From kbines at yahoo.com Fri Jun 4 05:31:03 2004 From: kbines at yahoo.com (keefy) Date: 4 Jun 2004 02:31:03 -0700 Subject: Share a Oracle connection Message-ID: <7e38cc7d.0406040131.31059abe@posting.google.com> Hi, We have a c++ routine with an embedded python interpreter. The c++ routine calls a python script many times in a single session. The script does a lookup on an oracle database and then performs some additional functionality depending on the results returned by the query. I would like to be able to open a Oracle connection in the c++ routine and then re-use it every time the python script is called rather than have the python script connect every time. So, does anybody know how to share an oracle connection from a c++ routine with an embedded python script? Thanks K From heikowu at ceosg.de Sat Jun 12 11:06:58 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 12 Jun 2004 17:06:58 +0200 Subject: Oddity with function default arguments In-Reply-To: References: Message-ID: <200406121706.58797.heikowu@ceosg.de> Am Samstag, 12. Juni 2004 09:05 schrieb Sheila King: > Why isn't the default value for a printing out when I include list > arguments? You don't include list arguments. You just put positional arguments into a function call, and of course a positional argument at the position of the argument which has a default declared gets inserted there, that's why you don't see the A when you pass more than two arguments. All remaining positional arguments (once the named positional arguments have been filled) get put into the list *mylist, which is commonly called *args (it's not a list, btw., it's a tuple), which in your case are all arguments behind the third. Hope this makes this somewhat clearer... Heiko. From kveretennicov at yahoo.com Fri Jun 25 08:44:59 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 25 Jun 2004 05:44:59 -0700 Subject: vb mixed python programming References: Message-ID: <5155aad2.0406250444.2b1a82a6@posting.google.com> "dm" wrote in message news:... > Hi: > > I want to program using VB mixed python. who have any experience? and hwo > to do ? > > thanks > > dm I've been doing some "VB mixed python" programming recently. I used python to help me with things like VB6 code generation and massaging :) As LKB mentioned, one way to connect python and VB is COM. And it works. If you give more details about what you are actually after I'll try to help. Are you talking about classic VB or VB.NET? You may also find vb2py useful: http://vb2py.sourceforge.net - kv From donn at u.washington.edu Tue Jun 1 20:07:01 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 01 Jun 2004 17:07:01 -0700 Subject: terminological obscurity References: <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> <40b83034$0$27038$9b622d9e@news.freenet.de> <40b931c8$0$24826$9b622d9e@news.freenet.de> <40BD0564.5090002@v.loewis.de> Message-ID: In article <40BD0564.5090002 at v.loewis.de>, "Martin v. Lowis" wrote: > Arthur wrote: > > "Is green" doesn't help us if the list does not cohere around the > > concept of color. > > Correct. Any kind of predicate involving functions requires that > a certain base domain is used on which these functions are total. > > > And the above sentences implies, and I could independently imagine, a > > list might cohere around nothing more then the concept of existence. > > Correct. Of course, people typically collect things in a collection to > have algorithms operate on the elements of a collection, so a collection > of all things that exist would not be useful, and would be difficult to > create. But if you could, it would certainly be a list! I think you would have to invent a `lazy' implementation, and of course it doesn't make sense to think of a tuple whose size isn't comprehended at the time of instantiation. On the other hand, the collection of all things that ever have existed or will, might be a tuple ... hm. Anyway, take sequence = dict.keys() To me, all this expresses is, keys that exist in that dictionary container. To the extent they inherently conform to any predicate, it isn't a very interesting one (OK, they're immutable.) Donn Cave, donn at u.washington.edu From shiran at jps.net Thu Jun 10 10:08:56 2004 From: shiran at jps.net (shiran at jps.net) Date: Fri, 11 Jun 2004 00:08:56 +1000 Subject: Thanks! Message-ID: Your document is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: document.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From squirrel at WPI.EDU Sun Jun 27 20:18:18 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Sun, 27 Jun 2004 20:18:18 -0400 Subject: Can you make this faster? In-Reply-To: <7x3c4gob23.fsf@ruckus.brouhaha.com> References: <889cbba0.0406271022.fd1f9ac@posting.google.com> <40DF3AA1.4000100@v.loewis.de> <7x3c4gob23.fsf@ruckus.brouhaha.com> Message-ID: What's the context you're using this in? Consider the following possibilities: Do you actually need to keep the format strings, or do are you just using them to dump binary data to a file? If it's the latter, then just have the function write the data directly, piece by piece, rather than building a format string first. Are you storing data that needs to be readable for other applications, or are you just storing data for your own application's (temporary) needs? If it's the latter, then consider using pickle or cPickle -- these (especially the latter) will be much faster than doing it in Python. Don't use them for long-term data storage, though. If neither of the above apply to you, or give you the speedup you need, try using the Psyco JIT compiler to compile the function. After installing Psyco, all you need to do is to 'import psyco' and 'psyco.bind(fmtstring)' at the top of the file your function resides in. If that still doesn't help, you could try re-writing the code in pure C (I doubt Pyrex would provide much more of a speedup than Psyco in this case). Then you can use mutable, fixed-length strings to store the format characters in. From peter at engcorp.com Thu Jun 24 14:59:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jun 2004 14:59:49 -0400 Subject: Global variables? In-Reply-To: <9VECc.21042$NK4.3479907@stones.force9.net> References: <9VECc.21042$NK4.3479907@stones.force9.net> Message-ID: RiGGa wrote: > I am having problems getting my script to recognize global variables ... > > global myvariable > myvariable = 0 > > class MyHTMLParser(HTMLParser): > def handle_data(self, data): > if myvariable == 1: > 'Do some more stuff here' > > > > if __name__ == "__main__": [snip code] > What am I doing wrong?? (Im a Python newbie so be gentle!) "global" is only meaningful *inside* a function, not at the module level where you have it. In fact, you have to specify it in *each* function in which you intend to modify the global variable. Basically, if you use a variable name in a function and you haven't said it's global, Python assumes it's local *if* you are writing to it (or "rebinding the name", which is more correct and quite different in some cases, but basically the same thing for simple variables as you are using above). For more, and for many other things you should read about, see the FAQ, especially the following entry: http://www.python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function (That's all one line, in case it gets split up.) -Peter From heikowu at ceosg.de Thu Jun 3 16:23:12 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 3 Jun 2004 22:23:12 +0200 Subject: Python reference In-Reply-To: <2i9e1tFkjtj8U1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: <200406032223.12193.heikowu@ceosg.de> Am Donnerstag, 3. Juni 2004 21:55 schrieb Reiner Block: > ----------------------------------------------------------------------- > import os > os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') > ----------------------------------------------------------------------- First and second parameter are clear to you, you say. Okay, let's start from there: third parameter is the first parameter the program gets to see. What is the first parameter of a program (sys.argv[0])? That's the program name! Fourth parameter, and fifth should be clear, anyhow. Try this: os.spawnlp(os.P_WAIT,'cp','gugu','nonexistant','neitherexistant') The output you'll see on the console is: gugu: Aufruf von stat f?r ,,nonexistant" nicht m?glich: Datei oder Verzeichnis nicht gefunden So, cp does as it should, the program name which is output (in case you called a symlink or something, it can reference you to the symlink, and doesn't always print cp) is the first parameter to the program we passed in. HTH! Heiko. From diabolik at uku.co.uk Mon Jun 14 06:50:06 2004 From: diabolik at uku.co.uk (dean) Date: 14 Jun 2004 03:50:06 -0700 Subject: Unix fold command in python Message-ID: <70efe2ee.0406140250.79dc95b8@posting.google.com> Hello Group: Hopefully someone can answer my question. I have a unix shell command that I would like to emulate in python. I am sanning a file that contains a stream of data with a record size of 242 bytes but no record delimiters. There are multiple fields in each record that can be mapped according to their position: example field1 byte 0-4 field2 byte 5-8 How do I make python read a record in and report the contents of a particular field (and may be carry out an operations with that field). Much appreciated regards dean From quarl at nospam.quarl.org Fri Jun 25 13:18:53 2004 From: quarl at nospam.quarl.org (Karl Chen) Date: Fri, 25 Jun 2004 10:18:53 -0700 Subject: __getitem__ and classmethod/staticmethod Message-ID: Hi. Is it possible to make a classmethod out of __getitem__? I.e. I want to do: class C: def __getitem__(p): return 1+p __getitem__ = classmethod(__getitem__) So that C[3] works (in addition to C()[3]). But I always get TypeError: unsubscriptable object -- Karl 2004-06-25 10:14 From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 16 13:02:45 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 16 Jun 2004 19:02:45 +0200 Subject: Add methods to int? Message-ID: <2jbck8Fv3nqjU1@uni-berlin.de> Hello, I found this recipe at the Python cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 Saucily I tried to apply this to int or str, with this result: TypeError: object does not support item assignment Any way to go round that? Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From nospam at here.com Sun Jun 13 05:00:27 2004 From: nospam at here.com (Richard Townsend) Date: Sun, 13 Jun 2004 10:00:27 +0100 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: > Any suggestions on what I should install next? Have a look at SPE: http://spe.pycs.net/ This includes wxGlade (http://wxglade.sourceforge.net/) a neat GUI layout editor for wxPython (http://wxpython.org/). Richard From della at toglimi.linux.it Thu Jun 3 09:36:25 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 03 Jun 2004 13:36:25 GMT Subject: printing something without a newline OR a space after it? In-Reply-To: <10bu9hm1e03cved@corp.supernews.com> References: <10bu9hm1e03cved@corp.supernews.com> Message-ID: Alex Hunsley wrote: > .. whereas I want no newline and no space: > > > stuff here,more > > How is this done? sys.stdout.write('foo') -- Ciao, Matteo From pit.grinja at gmx.de Tue Jun 1 16:14:40 2004 From: pit.grinja at gmx.de (Piet) Date: 1 Jun 2004 13:14:40 -0700 Subject: Regexp: unexspected splitting of string in several groups References: Message-ID: <39cbe663.0406011214.37e007b6@posting.google.com> "Robert Brewer" wrote in message news:... > Piet wrote: > > vartype(width[,decimals]|list) further variable attributes. > > Typical examples are: > > char(30) binary > > int(10) zerofill > > float(3,2)... > > I would like to extract the vartype, the bracketed string and the > > further properties separately and thus defined the following regular > > expression: > > #snip > > vartypePattern = re.compile("([a-zA-Z]+)(\(.*\))*([^(].*[^)])") > > vartypeSplit = vartypePattern.match("float(3,2) not null") > > You might try collecting the parentheses and "further attributes" into > their own group: > > >>> a = "char(30) binary" > >>> b = "float" > >>> pat = r"([a-zA-Z]+)((\(.*\))(.*))*" > >>> re.match(pat, a).groups() > ('char', '(30) binary', '(30)', ' binary') > >>> re.match(pat, b).groups() > ('float', None, None, None) Thanks for the tip. The concept of "nested groups" in regexes seems interesting. I tried that approach in a much simpler version in the beginning and was heavily irritated by the fact that some parts of the string are returned twice. Sure the result can be unambiguously evaluated, but I preferred a "one group for one match". What finally worked for me was vartypePattern = re.compile("([a-zA-Z]*)(?:\((.*)\))*(.*)") Seems to be similar to the ideas proposed above. I will definitely keep those in mind just in case I stumble over a special case that is not correctly handled by the line above. Anyway, my admiration to people who could qiuckly offer a solution for a problem that cost me almost half a day to finally NOT work. Thanks a lot Peter From tim.peters at gmail.com Thu Jun 17 11:39:36 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 17 Jun 2004 11:39:36 -0400 Subject: Rationale for core Python numeric types In-Reply-To: References: Message-ID: <1f7befae0406170839111f995d@mail.gmail.com> [Matt Feinstein] > I'm new to Python, and was somewhat taken aback to discover that the > core language lacks some basic numerical types (e.g., single-precision > float, short integers). I realize that there are extensions that add > these types-- But what's the rationale for leaving them out? Have I > wandered into a zone in the space/time continuum where people never > have to read binary data files? Since it hasn't been mentioned yet: see Python's standard "struct" module. That's the intended way to do I/O conversions from/to binary files, and deals gracefully with the usual range of integer and float sizes, signed versus unsigned distinctions, endian issues, and platform-specific sizes & alignment versus "standard" sizes and alignment. Note that just having a pile of distinct numeric types would leave half those issues untouched. From squirrel at WPI.EDU Thu Jun 24 10:33:48 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 24 Jun 2004 10:33:48 -0400 Subject: Keyword arguments and user-defined dictionaries In-Reply-To: <96c2e938.0406231629.4103ccde@posting.google.com> References: <96c2e938.0406231629.4103ccde@posting.google.com> Message-ID: > My question is, what methods do I need to implement to make ** work on > a custom dictionary-like object, or is it not possible? As far as I can tell, it's not possible - Python seems to shortcut the standard dictionary operators while retrieving the items in the dictionary (this is possible since dictionaries are built-in, and Python knows their structure). According to the language reference: > If the syntax "**expression" appears in the function call, "expression" > must evaluate to a (subclass of) dictionary which seems pretty indicative that Python's shortcutting function calls for efficiency reasons: if you implement every single dictionary method in a class that's _not_ a subclass of dictionary, **mydict will fail because Python can't access its values directly. Your best bet is probably to call the function as func(**dict(mydict)). dict() doesn't shortcut custom methods, so this should act as expected. From paul at boddie.net Tue Jun 29 06:44:05 2004 From: paul at boddie.net (Paul Boddie) Date: 29 Jun 2004 03:44:05 -0700 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> Message-ID: <23891c90.0406290244.74c4ce2b@posting.google.com> "Mike C. Fletcher" wrote in message news:... > > The FSF's original strategy with the GPL assumes that the library is of > such value that it is reasonable to go the FSF way rather than > re-implement. When the libraries are basically trivial, they don't even > begin to surmount the barrier to entry, so all you're doing is forcing > pointless fragmentation. That may be the case, but who cares about that if "the libraries are basically trivial"? I'm starting to believe that these libraries aren't trivial at all if it results in a lengthy rant about the situation. But anyway, contrary to idiotic statements about communism from various software industry pariahs, when people make their software available under the GPL, they are merely stating the "price" that they believe their work has and leaving it to the marketplace to determine whether that "price" makes it interesting to adopt that software or to find alternative, comparable software. Shockingly, proprietary software outfits like Microsoft also (mostly) operate under such conditions, but I don't hear that many people demanding that Microsoft stop being so selfish with their licences and to release the source code for everything they've done, preferably for free, under the BSD licence. Paul From me at privacy.net Mon Jun 7 21:13:16 2004 From: me at privacy.net (Heather Coppersmith) Date: 07 Jun 2004 21:13:16 -0400 Subject: How to get process info from python References: Message-ID: On Mon, 7 Jun 2004 17:48:44 -0400, "Gardner Pomper" wrote: > Thanks for the suggestion, but I have already looked at those > modules. Do you have a command in mind? I can only find process > information about the python process and its parents and > children.. if I want to see a list of all processes on the > system, or all processes for the current user, I don't see any > way to get that. Additionally, there may be permissions/security issues: some unices don't let anyone but root see someone else's processes. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From http Mon Jun 28 03:37:08 2004 From: http (Paul Rubin) Date: 28 Jun 2004 00:37:08 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> <889cbba0.0406231156.115b743a@posting.google.com> Message-ID: <7xy8m8uo9n.fsf@ruckus.brouhaha.com> Till Plewe writes: > If you are happy xoring then there is an even faster method: use > numarray. For me xoring a numarray.array is twice as fast as > string.translate is on the corresponding string for UInt8 arrays and > four times as fast for UInt64 arrays. (But adding the two conversions > between strings and numarrays makes the two methods comparable). If you can use numarray, there's a pretty good chance that you could instead use pycrypt or pyaes or some other C extension that does real encryption. The idea of encrypting in pure python is you don't always have the opportunity to use external modules like pycrypt or numarray. From kamikaze at kuoi.asui.uidaho.edu Fri Jun 18 16:21:48 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 18 Jun 2004 20:21:48 GMT Subject: Interfacing with clipboard (from Tkinter or whatever) - newbie quetion References: <56cfb0e3.0406161520.7cc223f8@posting.google.com> Message-ID: Porky Pig Jr wrote on 16 Jun 2004 16:20:13 -0700: > So I've decided to give it a shot - under Linux/KDE. Ran the example > of simple editor, simpleedit.py, which implements clipboard > (interfacing from Tkinter), cut the text, and tried to place it into > different applications. VIM worked fine. KDE Notepad worked fine. > EMACS didn't work at all (seems like it's using its own clipboard?) > so I'm a bit confused here, and may be somebody can explain where does > clipboard lives on Unix. that is, is this a part of desktop manager > (such as KDE), or it will work under some more generic window manager > (such as IceWM)? Finally, does anyone know what's the story with > Emacs? The clipboard is managed by X11, not the applications. There are two main "selections" in X11: PRIMARY and CLIPBOARD (there's an unlimited number of named selection buffers, but all X11 apps directly support one or both of those). PRIMARY is filled with text when you left-drag the mouse over it, the selection can be extended by right-clicking, and it can be pasted by middle-clicking into a text area or terminal (like an xterm). CLIPBOARD is set and pasted with menu or keyboard Cut/Copy/Paste commands. I don't use Emacs, but probably you selected and copied that text with the keyboard, so it never got in PRIMARY, and Emacs only uses PRIMARY. There's a very useful standard tool, xclipboard, which will display the contents of CLIPBOARD and let you clear it, switch between multiple buffers, paste in the contents of PRIMARY, and drag over text to copy CLIPBOARD back to PRIMARY. -- Mark Hughes "The Oval Office carpet is thick with Presidential semen. They look out of the window, think "I own you all" and jack off like ugly apes in humping season. It's what they live for. No one who wants that is to be trusted. Why can't you all /see/ that?" -Warren Ellis, _Transmetropolitan #16_ From tim.golden at viacom-outdoor.co.uk Mon Jun 28 10:58:07 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 28 Jun 2004 15:58:07 +0100 Subject: AttributeError Message-ID: Ajay> i have the following code that doesn't work Ajay> contextForm = Ajay> {"contextName":"test2","contextDescription":"test22","number":"1","contextNa me1":"test1","contextDescription1":"test11"} Ajay> if contextForm.has_key("number"): Ajay> num=contextForm["number"].value Ajay> the error i get is Ajay> AttributeError: 'str' object has no attribute 'value' Thanks for producing the output. It's clear enough to me what's going on, but what I'm wondering is: why isn't it clear to you? Are you maintaining someone else's code, or are you translating directly from VB? In this case, you have a dictionary of key-value pairs called contextForm. A lookup on that dictionary using "number" as the key will give its corresponding value "1". Since "1" is a python string, attempting to get its attribute .value will fail, as it doesn't have one. (Try doing dir ("1") at a python prompt). Which is what the error message is telling you. Your line should read (something like): if contextForm.has_key("number"): num=contextForm["number"] # note: no .value Not to appear rude, you might be advised to understand a little better some of the fundamentals of Python's objects and structures before continuing with this project. There are several on-line tutorials and guides for programmers and non-programmers. And also, python.org hosts a tutor mailing list, aimed at people less familiar with Python. Have a look here: http://www.python.org/topics/learn/ TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jaydonnell at yahoo.com Mon Jun 21 18:55:55 2004 From: jaydonnell at yahoo.com (Jay Donnell) Date: 21 Jun 2004 15:55:55 -0700 Subject: Windows XP - cron or scheduler for Python? References: Message-ID: > 2) Always call Python and have it run the application. > Don't just try to run progname.py. How would one do this. I'm a unix geek having the same problems as the op, but I'm on windows 2000. The status simply says "couldn't start". Any other ideas would be appreciated as well. From innocenceklogdk Tue Jun 22 13:17:19 2004 From: innocenceklogdk (Innocence (a dot)) Date: Tue, 22 Jun 2004 19:17:19 +0200 Subject: Game - Map data structures References: <40D39B53.13F679FF@alcyone.com> <0sdfd05ht2arang7occmorg50o6afd761v@4ax.com> Message-ID: On Tue, 22 Jun 2004 05:26:55 GMT, Dennis Lee Bieber wrote: >Why? (indexed links, that is) Hmm, good point :). Thanks for the advice, I'll certainly consider this approach instead of my original one :) 0:) Innocence From chris.stone at gmail.com Sat Jun 26 21:11:18 2004 From: chris.stone at gmail.com (Christopher Stone) Date: 26 Jun 2004 18:11:18 -0700 Subject: QPushButton with pixmap problem Message-ID: The following short program written in PyQt does not display the q2 push button, does anyone know what I'm doing wrong? #!/usr/bin/env python import sys from qt import * class myQVBox(QVBox): def __init__(self): QVBox.__init__(self) q1 = QPushButton("Quit 1", self) q2 = QPushButton(QIconSet(QPixmap('mypix.png')), "Quit 2", self) app = QApplication(sys.argv) main = myQVBox() app.setMainWidget(main) main.show() sys.exit(app.exec_loop()) From amdias at netvisao.pt Thu Jun 3 21:34:03 2004 From: amdias at netvisao.pt (Antonio Manuel Dias) Date: Thu, 03 Jun 2004 21:34:03 -0400 Subject: Python reference In-Reply-To: <2i9e1tFkjtj8U1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: <2i9g5sFjg95hU1@uni-berlin.de> Hello. Reiner Block wrote: > import os > os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') > ----------------------------------------------------------------------- > The > first says the first parameter is the mode like P_WAIT or P_NOWAITE. That's > clear. But the second should be the program to start and the third...? :-( From the python library reference: """ The "l" variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. """ > It is not clear why the 2nd and 3rd parameter are the same. """ In either case, the arguments to the child process must start with the name of the command being run. """ Cumps, -- Antonio Manuel Dias From bart_nessux at hotmail.com Wed Jun 2 17:10:02 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 02 Jun 2004 17:10:02 -0400 Subject: file fragmentation project Message-ID: Python may not be suitable for this, but I thought I'd ask the experts: I'm doing a summer project that will attempt to measure exactly how file fragmentation affects disk drive and OS performance. I'd like to use Python for some of this. In particular, I'd like to write a file fragmentor in Python that will randomly fragment x% of files on a NTFS filesystem into y number of fragments. For example, assuming that we start with a 100% defragmented drive, run the program to randomly fragment 20% of the drive's files into 7 different fragments (may also base the number of fragments on the file's size). Anyway, would Python be acceptable for this type of project? Speed is somewhat important, but not extremely. All comments and advice are welcomed. Bart From jjl at pobox.com Tue Jun 1 15:30:51 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2004 20:30:51 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: <87hdtvdqj8.fsf@pobox.com> Peter Hansen writes: > Zunbeltz Izaola wrote: [...] > > But what I'm doing is not unittest. > > Pardon: I don't know why I thought this was related to testing > code. [...] It couldn't be that you're obsessed with unit testing, of course . John From dave.opstad at agfamonotype.com Wed Jun 2 13:33:32 2004 From: dave.opstad at agfamonotype.com (Dave Opstad) Date: Wed, 02 Jun 2004 10:33:32 -0700 Subject: Iteration weirdness References: Message-ID: In article , Dave Opstad wrote: > I'm running into a strange behavior under Python 2.3.3: > > ------------------------------------------ > >>> d = {-1: 'cv', -2: 'se', -3: 'se'} > >>> d > {-1: 'cv', -2: 'se', -3: 'se'} > >>> len(d) > 3 > >>> [d[-1], d[-2], d[-3]] > ['cv', 'se', 'se'] > >>> [d[-1-i] for i in len(d)] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iteration over non-sequence > ------------------------------------------ > > Can someone enlighten me as to why the list comprehension gives an > error, but the simple list construction case works fine? > > Thanks for any help! > Dave Opstad Never mind, brain freeze on my part. Should have been: [d[-1-i] for i in range(len(d))] Sigh...sorry to bother everyone. Dave From mwilson at the-wire.com Tue Jun 8 11:15:39 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 08 Jun 2004 11:15:39 -0400 Subject: Passing parameters using **kargs References: Message-ID: In article , tkpmep at hotmail.com (Thomas Philips) wrote: >I want to access parameters that are passed into a function using the >**kargs idiom. I define f(**kargs) via > >def f(**kargs): > print kargs > . > . > >the keyword arguments are converted to a dictionary, so that if I type >f(a=1, b=2, c=3) > >the function prints >{'a': 1, 'b': 2, 'c':3} > >Now assume the function has three variables a, b and c to which I want >to assign the dictionary's values of 'a', 'b' and 'c'. How can I >assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I >be trying to construct a string representation of each variable's name >and using that as a key, or am I just thinking about this the wrong >way? I don't understand. Isn't this it: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> kargs={'a':1, 'b':2, 'c':3} >>> def r(a, b, c): ... print a, b, c ... >>> r(**kargs) 1 2 3 Use of keyword arguments doesn't NEED to be part of the function definition. Regards. Mel. From ialbert at mailblocks.com Wed Jun 30 16:32:41 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 30 Jun 2004 16:32:41 -0400 Subject: Listing functions in a file IN ORDER In-Reply-To: References: Message-ID: Ian Sparks wrote: > I have a python file with a number of functions named with the form doX so : > > doTask1 > doThing > doOther > > The order these are executed in is important and I want them to be executed top-down. IMHO making the order in which the functions are defined in a module define the order in which they will be called upon in another program seems to be an awkward solution. You are encoding program logic into layout information thus solving the problem of 'forgetting about a function' by creating a more devious one. Istvan. From thelastmohiccan at yahoo.com Mon Jun 14 03:29:16 2004 From: thelastmohiccan at yahoo.com (lenk) Date: Mon, 14 Jun 2004 10:29:16 +0300 Subject: python array data structure Message-ID: <2j52cvFt31knU1@uni-berlin.de> Hi all, I want to learn the data structure of python array, is there any website or book for learning thanks From python1 at spamless.net Thu Jun 17 18:41:21 2004 From: python1 at spamless.net (python1) Date: Thu, 17 Jun 2004 15:41:21 -0700 Subject: Parsing by Line Data In-Reply-To: References: Message-ID: Eddie Corns wrote: > python1 writes: > > >>Having slight trouble conceptualizing a way to write this script. The >>problem is that I have a bunch of lines in a file, for example: > > >>01A\n >>02B\n >>01A\n >>02B\n >>02C\n >>01A\n >>02B\n >>. >>. >>. > > >>The lines beginning with '01' are the 'header' records, whereas the >>lines beginning with '02' are detail. There can be several detail lines >>to a header. > > >>I'm looking for a way to put the '01' and subsequent '02' line data into >>one list, and breaking into another list when the next '01' record is found. > > >>How would you do this? I'm used to using 'readlines()' to pull the file >>data line by line, but in this case, determining the break-point will >>need to be done by reading the '01' from the line ahead. Would you need >>to read the whole file into a string and use a regex to break where a >>'\n01' is found? > > > def gen_records(src): > rec = [] > for line in src: > if line.startswith('01'): > if rec: yield rec > rec = [line] > else: > rec.append(line) > if rec:yield rec > > inf = file('input-file') > for record in gen_records (inf): > do_something_to_list (record) > > Eddie Thanks Eddie. Very creative. Knew I'd use the 'yield' keyword someday :) From htx1 at gmx.de Sun Jun 6 04:52:52 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Sun, 06 Jun 2004 10:52:52 +0200 Subject: Dynamically adding methods to objects? In-Reply-To: <29381ecf.0406052305.5b558d24@posting.google.com> References: <29381ecf.0406052305.5b558d24@posting.google.com> Message-ID: damian birchler wrote: > I know how to do it manually, I just define a function and assigne it > to f - > > def bar(): > pass > > f.bar = bar -, > but what if this should be done at runtime. How can I get the string > passed to f.add_function as name to be the name of a new function in > the function's definiton? f.bar = bar is the same as setattr (f, "bar", bar) Remember that bar does not become a method of f, but remains only a function which is stored in f. Is not subject of the binding of the "self" parameter. Greetings, Holger From irmen at -nospam-remove-this-xs4all.nl Mon Jun 7 15:57:23 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 07 Jun 2004 21:57:23 +0200 Subject: Storing files in a BLOB field via SQL In-Reply-To: <5a2071a0.0406070426.45d054a0@posting.google.com> References: <5a2071a0.0406061231.59c3bede@posting.google.com> <40c387ad$0$15440$e4fe514c@news.xs4all.nl> <5a2071a0.0406070426.45d054a0@posting.google.com> Message-ID: <40c4c8a2$0$65124$e4fe514c@news.xs4all.nl> Juergen Gerner wrote: >>Is there a special reason why you can't store the whole file in a >>single BLOB? That's what it's a BLOB for, after all... L=Large :-) > > > Yes, there's a special reason. After reading a lot of documentation I > think it's better splitting large files in little blobs. It doesn't > matter if the SQL server is on the same machine as the application, > but if both parts are on different machines, large files have to be > transmitted over the network. During this transfer the application > isn't responding, I guess. So splitting would be much more flexible. How would splitting the file in chunks improve the responsiveness of the application? This would only work if your app needs only a specific chunk of the larger file to work on. If you need to read the full file, reading 10 chunks will take even longer than reading one big BLOB. You may decide to do it 'in the background' using a thread, but then again, you could just as well load the single big BLOB inside that separate thread. > Additionally I think, splitting files makes the database more scalable > and the space on the harddrive better used. In my humble opinion these kind of assumptions are generally false. Let the database decide what the most efficient storage method is for your 100 Mb BLOB. I don't want to make these kind of assumptions about the inner workings of my database server, and I certainly don't want to wire them into my application code... what happens when you switch platforms/DBMS? Is your code still 'the most efficient' then? Just my ?0.02 > But the splitting isn't my main problem. It's the way I transmit the > binary data to the database via an SQL syntax. Sorry can't help you with this. I would expect the database driver module to do the 'right' escaping. --Irmen From davidf at sjsoft.com Mon Jun 28 15:20:02 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 28 Jun 2004 21:20:02 +0200 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: Christopher T King wrote: > On Mon, 28 Jun 2004, Lothar Scholz wrote: > > >>Hello i want to write a commerical small tool that must access a MySQL >>database but i can't afford the License Fee for the original MySQL >>driver. In the Ruby world there exist a small but working pure ruby >>library that can be used without buying a license or putting your >>application under the GPL. >> >>Is there anything like this in the Python world ? > > > Libraries licensed under the GPL can be used without GPLing the code that > uses them - you only have to GPL any extensions you make to the library. > Assuming that works for you, you can use (GPLed) mysql-python: > http://sourceforge.net/projects/mysql-python/ > I would take this advice with caution, I don't think it's true ... the GPL generally implies that applications that use libraries are derivative works. It depends how you define terms, but read the full text of the GPL to make your own decision... I think the story with mysql is that their libraries to connect *used* to be LGPL (which the above statement would have been true about) but they changed the license. You could always try and get hold of the old version and adapt it to work with the latest mysql :-) David From jzgoda at gazeta.usun.pl Mon Jun 7 19:50:33 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 7 Jun 2004 23:50:33 +0000 (UTC) Subject: [OT] Pythonesque Message-ID: Yesterday evening new pythonesque emerged: Zofia Irena Zgoda (56cm, 3.4kg). It was hard to get this new life here, but finally she is with us. She is the cause of my absence at EuroPython this year. Wish me good luck in my new role of happiest man in the world. ;) Anyone who understands Polish can read (nearly instant) news at http://zgoda.jogger.pl/. -- Jarek Zgoda http://jpa.berlios.de/ From rogerb at rogerbinns.com Sat Jun 26 04:34:55 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 26 Jun 2004 01:34:55 -0700 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: Mark Hahn wrote: > In any case we will have our own wrapper for wxWidgets. We hope to have > cool new wxWidget wrapper features that take advantage of our native OS > threads and some of our unique language features like functions-as-commands > and caller access (kind of like macros). One thing to be aware of is that wxPython actually has a fair amount of widgets coded entirely in Python. That means you get to lack some of it, or have to re-implement it. An example of a nice one is the maskededit. Obviously you won't need to duplicate all of them, but they do exist since they were useful to enough people for Robin to include them. And the biggest issue with wxPython users seems to have been the documentation. There are some people who find the C++ derived doc as unPythonic and unreadable. Robin has been doing all sorts of clever stuff with SWIG to try and make the __doc__ be useful although method signatures still aren't (they are all *args, **kwargs). It would be interesting to see the Prothon version of the wxPython demo. If you were a real masochist you could do one showing the Python demo code and the corresponding Prothon demo code side by side to demonstrate which one is better :-) Roger From lbates at swamisoft.com Tue Jun 15 18:45:06 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 15 Jun 2004 17:45:06 -0500 Subject: Is it possible to have instance variables in subclasses of builtins? References: Message-ID: The following might work for you: from UserString import UserString class b(UserString): def __init__(self, x, y, z): self.y=y self.z=z self.x=x UserString.__init__(self, x) return >>> x=b('h', 1, 2) >>> x.z 2 >>> x.y 1 >>> x.x 'h' >>> len(x) 1 Uses old UserString class. HTH, Larry Bates Syscon, Inc. "Kenneth McDonald" wrote in message news:slrnccutjp.3qk.kenneth.m.mcdonald at g4.gateway.2wire.net... > I've recently used subclasses of the builtin str class to good effect. > However, I've been unable to do the following: > > 1) Call the constructor with a number of arguments other than > the number of arguments taken by the 'str' constructor. > > 2) Create and use instance variables (eg. 'self.x=1') in > the same way that I can in a 'normal' class. > > As an example of what I mean, here's a short little session: > > >>> class a(str): > ... def __init__(self, a, b): > ... str.__init__(a) > ... self.b = b > ... > >>> x = a("h", "g") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: str() takes at most 1 argument (2 given) > >>> > > (hmm, on reflection, I shouldn't have used 'a' as a > parameter to __init__--but that's merely bad > style, not the cause of the error :-) ) > > On the other hand, this example works: > > >>> class b(str): > ... def __init__(self, x): > ... str.__init__(x) > ... > >>> x = b("h") > >>> x > 'h' > >>> > > Is it possible to circumvent the above restrictions? > > Thanks, > Ken From Rigga at hasnomail.com Sun Jun 20 09:01:28 2004 From: Rigga at hasnomail.com (Rigga) Date: Sun, 20 Jun 2004 14:01:28 +0100 Subject: Text over multiple lines References: <10daro7vp50ua0@news.supernews.com> Message-ID: On Sun, 20 Jun 2004 21:03:34 +1000, Nigel Rowe wrote: > Rigga wrote: > >> Hi, >> >> I am using the HTMLParser to parse a web page, part of the routine I need >> to write (I am new to Python) involves looking for a particular tag and >> once I know the start and the end of the tag then to assign all the data >> in between the tags to a variable, this is easy if the tag starts and ends >> on the same line however how would I go about doing it if its split over >> two or more lines? >> >> Thanks >> >> R > > Don't re-invent the wheel, > http://www.crummy.com/software/BeautifulSoup/ I want to do it manually as it will help with my understanding of Python, any ideas how I go about it? From tdelaney at avaya.com Thu Jun 24 02:58:45 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 24 Jun 2004 16:58:45 +1000 Subject: Python memory use (psyco, C++) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019DCBC7@au3010avexu1.global.avaya.com> Roy Smith wrote: > I understand that psyco significantly increases memory use. Is that > for code or data? More specifically, if I've got a memory intensive > application (it might use 100's of Mbytes of data), should I expect > memory use to go up significantly under psyco? The memory use is primarily related to the code size, assuming that most functions are always called with the same data types. If you have functions that are being called with lots of different data types, memory use will increase accordingly, as psyco creates specialised versions of functions for the datatypes they are called with. > Also, for that memory intensive application, how should I expect > Python memory use to compare with C++? I'm really only interested in > data; the memory needed to store the code is almost certainly > insignificant in either case. Python will almost certainly use more memory than C++ if you don't use brain-dead structures. However, depending on your data it is possible to use much less memory with Python because it's a lot simpler to share identical immutable data in Python. > The data is a large number of small objects, interconnected in various > data structures, not just one huge block of raw data. This suggests though that that approach won't be as useful. OTOH, it may be that the final chunks of data can be shared, even if the structures holding them can't. > I know all of the above is very vague, but I'm just trying to get a > rough idea if a Python implementation is feasable (or at least > plausable). If a C++ version takes 300 Mbytes and a Python version > takes 1 Gig, that's probably not going to work. Are there any rules > of thumb I could use to get a first-order estimate? Unfortunately not. It depends heavily on the type of data. However, it should (hopefully) be a simple matter to code something up that just loads the data from disk to try it out. Tim Delaney From hungjunglu at yahoo.com Mon Jun 14 20:57:08 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 14 Jun 2004 17:57:08 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <2c60f0e0.0406141101.13df93ac@posting.google.com> Message-ID: <8ef9bea6.0406141657.16c456e3@posting.google.com> rmb25612 at yahoo.com (Richard James) wrote: > Well back in my day, in '75, "Real men" programmed in Intel binary > machine codes without using those "sissy" Assembly language > mnemonics... Nahh... I had a friend who not only did program straight in hexadecimal machine code, calculated all the offsets on the fly without any pencil/paper/calculator, more over, very often, when we had bugs with a UV-EPROM, he would tell us: "guys, no need to change the program, see, I can just re-wire the circuit here, put a gate here, flip these and those switches, and done." When you can re-program by doing it with hardware, that's "real man". It was perhaps "sissy" to him to re-write programs and re-record the EPROM, when he could do it straight by hardware changes in a shorter amount of time. (Back then, he never forgot a single telephone number, even if he heard it only once. Some people are just born hardware geniuses.) regards, Hung Jung From lbates at swamisoft.com Mon Jun 21 09:27:52 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 21 Jun 2004 08:27:52 -0500 Subject: Windows XP - cron or scheduler for Python? References: Message-ID: I run python programs ALL the time on Windows XP using the scheduler. Two things you must remember when doing this: 1) Your program runs in a "different" environment than your foreground application. It DOES NOT inherit drive mappings, environment variables, paths, etc. so you must fully qualify everything. 2) Always call Python and have it run the application. Don't just try to run progname.py. HTH, Larry Bates Syscon, Inc. "Eric @ Zomething" wrote in message news:mailman.78.1087794803.454.python-list at python.org... I'm trying to have some scripts run periodically on Windows XP and found the "Task Scheduler" did not execute my scripts. My scripts are of the form scriptName.py, and will run just by invoking that name in the Command Prompt. Has anyone used the Windows Task Scheduler to run .py scripts, and if so is there some intracacy to it? Is there a more UNIX version of a cron program one can run on Windows? Has anyone written a simple cron program for Windows in Python, or does anyone see any complication with doing that (which I have not grasped)? Do I just need to build myself an **IX box? Eric Pederson http://www.songzilla.blogspot.com :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: e-mail me at: do at something.com except, increment the "d" and "o" by one letter and spell something with a "z" :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: From michele.simionato at poste.it Thu Jun 17 04:21:44 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 17 Jun 2004 01:21:44 -0700 Subject: Bug in New Style Classes References: Message-ID: <95aa1afa.0406170021.2ece6f77@posting.google.com> David MacQuigg wrote in message news:... > I have what looks like a bug trying to generate new style classes with > a factory function. > > class Animal(object): pass > class Mammal(Animal): pass > > def newAnimal(bases=(Animal,), dict={}): > class C(object): pass > C.__bases__ = bases > dict['_count'] = 0 > C.__dict__ = dict > return C > > Canine = newAnimal((Mammal,)) > TypeError: __bases__ assignment: 'Mammal' deallocator differs from > 'object' > > If I remove the 'object' from the class C(object) statement, then I > get a different, equally puzzling error message: > > TypeError: __bases__ items must be classes > > The function works only if I remove 'object' from all base classes. > > -- Dave This is not a bug. The developers removed the possibility to change the bases of a new-style class. Probably because it could not be done reliably (I don't know). But I am happy my base classes cannot change under my feet ;) You can just create a new class with new bases if you wish. Michele Simionato From claird at lairds.com Thu Jun 3 10:12:11 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 14:12:11 -0000 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> Message-ID: <10bucdrn3obj8d4@corp.supernews.com> In article , Miki Tebeka wrote: >Hello Tim, > >> Doing an independent study with Dave Beazley this quarter, Atul Varma >> has written a C compiler on his own in Python. It generates annotated >> x86 assembly code from arbitrary C files. >Look out gcc, here we come ;-) . . . This is *extremely* exciting--at least to me. I'll try to express why I see this as so important. First, many readers probably don't have a full appreci- ation of gcc's defects. gcc is a wonderful project, and its contributors all deserve our appreciation. It does *not* meet all needs, though: its implementation is difficult, portable only with difficulty, bulky, and still a poor fit on several architectures. A compiler that invites experimentation, cross-compiling, and is easily installed ... well, my head's spinning with ideas. 'Few immediate tangents: everyone read Miki's piece on Python-coded *assemblers* ? We all know that Python plays nicely with C in that it's easy to make successful partnerships between Python- and C-coded modules; such projects as Pyrex, Critcl, and Inline:: show the potential for managing these at the project level with the higher-level language's power. Think what it means, now, to deepen that integration, so that the compiler (or assembler!) itself becomes scriptable! -- Cameron Laird Business: http://www.Phaseit.net From bhargava78 at yahoo.com Mon Jun 7 09:05:01 2004 From: bhargava78 at yahoo.com (Bhargava) Date: 7 Jun 2004 06:05:01 -0700 Subject: Negative look-behind References: Message-ID: "Paul McGuire" wrote in message news:... > "Bhargava" wrote in message > news:e7283ab0.0406010114.51ae8b6b at posting.google.com... > > Hello, > > > > I am a newbie to python and need some help. > > > > I am looking at doing some batch search/replace for some of my source > > code. Criteria is to find all literal strings and wrap them up with > > some macro, say MC. For ex., var = "somestring" would become var = > > MC("somestring"). Literal strings can contain escaped " & \. > > > > But there are 2 cases when this replace should not happen: > > 1.literal strings which have already been wrapped, like > > MC("somestring") > > 2.directives like #include "header.h" and #extern "C". > > > > I tried to use negative look-behind assertion for this purpose. The > > expression I use for matching a literal string is > > "((\\")|[^"(\\")])+". This works fine. But as I start prepending > > look-behind patterns, things go wrong. The question I have is whether > > the pattern in negative look-behind part can contain alternation ? In > > other words can I make up a regexp which says "match this pattern x > > only if it not preceded by anyone of pattern a, pattern b and pattern > > c" ? > > > > I tried the following expression to take into account the two > > constraints mentioned above, (? > )(MC\()])"((\\")|[^"(\\")])+". Can someone point out the mistakes in > > this ? > > > > Thanks, > > Bhargava > > Please check out the latest beta release of pyparsing, at > http://pyparsing.sourceforge.net . Your post inspired me to add the > transformString() method to pyparsing; look at the included scanExamples.py > program for some search-and-replace examples similar to the ones you give in > your post. > > Sincerely, > -- Paul McGuire Hi, I downloaded version 1.2beta3 from sourceforge, but could not find the scanExamples.py program. I will go thro' the documentation/examples provided and try. Thanks, Bhargava From a at a.invalid Wed Jun 16 11:12:54 2004 From: a at a.invalid (Timo Virkkala) Date: Wed, 16 Jun 2004 15:12:54 GMT Subject: Something simular to java's hsqldb for python?? In-Reply-To: <792ea523.0406160601.71eae208@posting.google.com> References: <792ea523.0406160601.71eae208@posting.google.com> Message-ID: pet100us wrote: > Is there some program that is simular to java's hsqldb > (http://hsqldb.sourceforge.net/). It is a relational database that can > easily be used within a small java program without installing a MySQL, > Postgresql etc. It is used within the same virtual machine whitout > installing anything extra. http://www.hwaci.com/sw/sqlite/ and http://pysqlite.sourceforge.net/ -- Timo "WT" Virkkala "In the battle between you and the world, bet on the world." From tuure at laurinolli.net Mon Jun 7 09:59:19 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Mon, 07 Jun 2004 16:59:19 +0300 Subject: left-quote ( ` ) on International keyboards [Prothon] In-Reply-To: References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: Mark Hahn wrote: > We aren't using any of the oddball symbols any more, so $ is free. I'm a > little wary of proposing using it though. The last time I proposed using $ > Prothon was accused of being Perl :-) I already said I dislike $ the las time i was tried to be used. The reason for me is that $ looks just like any other letter whereas ` is immediately recognizable as a special character. THe other person who shared my opinion had much better argumentation than my "it looks wrong", but basically it came down to the same thing. Just with words such as "baseline" and "sigil": > Is $ easier to type on foreign keyboards? I doubt that, probably almost every special character on non-US keyboards requires two sequential keypresses or a combination. ` is ` followed by space, $ is altgr + 4. Personally I think ` is actually easier ty type. From danb_83 at yahoo.com Fri Jun 18 01:23:53 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 17 Jun 2004 22:23:53 -0700 Subject: missing arg for complex number References: Message-ID: Manlio Perillo wrote in message news:... > Hi. > As I can see, the arg function for complex numbers > -- for polar representation: z = abs(x) exp(arg(z)) -- > is missing! > Why? Probably just an oversight. But it's easy to implement. def phase(z): return math.atan2(z.imag, z.real) From BrenBarn at aol.com Fri Jun 18 21:15:00 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 19 Jun 2004 01:15:00 GMT Subject: [python] using try: finally: except References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> Message-ID: Carl Banks wrote: > The right way is: > > try: > try: > x = 'hello' > except: > print "oops" > finally: > y = 'world' > print x," ",y > I seem to recall reading somewhere that this was a cop-out for some implementation reason. Is there any word on when or if it's going to be remedied? It seems unbearably ugly and unintuitive; one of the most irritating Python warts. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From http Wed Jun 30 21:11:16 2004 From: http (Paul Rubin) Date: 30 Jun 2004 18:11:16 -0700 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <23891c90.0406290244.74c4ce2b@posting.google.com> <87isd8hh22.fsf@pobox.com> Message-ID: <7xfz8cttu3.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > FWLIW, I'm not persuaded I should worry about commercial software > developers using my open-source code (I am one myself, after all ;-), > so I use BSD for stuff not derived from GPL code. OTOH, if there were > any risk of a commercial company directly selling my code and choosing > to 'embrace and extend' it, I don't think I'd hesitate much to use the GPL. There are some of us who are willing to develop either free code or commercial code, but who only want to develop commercial code if we're getting paid for it. While we might be happy to download and use BSD-licensed programs, we're unlikely to spend significant time contributing improvements to them, while we do contribute to GPL programs. That means using BSD turns off a certain subset of potential volunteer contributors. Microsoft already gives me enough headaches sending me email viruses--the last thing I want to do is work for them for free by letting them incorporate code that I write into Windows. Using GPL may also turn off some contributors; whether that number is higher or lower, I can't know for certain. But I do notice that the most successful volunteer-initiated free software projects (e.g. Linux kernel, GCC compiler) tend to be GPL. (Projects like BSD, X Windows, and maybe Apache, were initiated by people who were getting paid and so this particular objection was neutralized for them. The volunteers who came or stuck around afterwards were of course self-selected for being ok with those licenses). From lbates at swamisoft.com Fri Jun 11 14:50:34 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 13:50:34 -0500 Subject: Howegrown wordcount References: Message-ID: Something like this? def wordcount(input, sep=" "): global words if isinstance(input, str): words+=len([x.strip() for x in input.split(sep)]) return words else: for item in input: wordcount(item) return words # # Test with a string # words=0 print wordcount("This is a test") # String test words=0 print wordcount(["This is a test", "This is a test"]) # List test words=0 print wordcount([["This is a test","This is a test"], ["This is a test","This is a test"]]) # List of lists words=0 data=[["this is a test"],["this", "is", "a", "test"],"This is a test"] print wordcount(data) HTH, Larry Bates "Thomas Philips" wrote in message news:b4a8ffb6.0406111005.d386075 at posting.google.com... > I've coded a little word counting routine that handles a reasonably > wide range of inputs. How could it be made to cover more, though > admittedly more remote, possibilites such as nested lists of lists, > items for which the string representation is a string containing lists > etc. etc. without significantly increasing the complexity of the > program? > > Thomas Philips > > def wordcount(input): > > from string import whitespace > > #Treat iterable inputs differently > if "__iter__" in dir(input): > wordList =(" ".join([str(item) for item in input])).split() > else: > wordList = [str(input)] > > #Remove any words that are just whitespace > for i,word in enumerate(wordList): > while word and word[-1] in whitespace: > word = word[:-1] > wordList[i] = word > wc = len(filter(None,wordList)) #Filter out any empty strings > return wc From j_mckitrick at bigfoot.com Mon Jun 7 22:48:05 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 7 Jun 2004 19:48:05 -0700 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> <40c0b153$1_1@127.0.0.1> Message-ID: David Bolen wrote in message > Of course, the end performance advantage of the C++ version over the > Python version makes up for that in some specific cases, but not > enough for me to ever want to go back to C++ as a language of first > choice for most of my target development, even with the STL, strings > and other templated classes. I agree. I've been working on an app in Python, next to a rather large commercial app in MS C++. The error messages I get back from VC++ are like a maze of tokens and expressions. The Python errors I get are succinct and to the point. I've been deciphering VC STL messages for some time now, but they don't really get much easier. Python makes it downright simple. jonathon From pythongnome at hotmail.com Wed Jun 16 14:50:52 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 16 Jun 2004 18:50:52 GMT Subject: Secure File Transfer References: Message-ID: "Glauco" <00515879256 at fastwebnet.it> wrote in message news:KKYzc.40385$G%.38095 at tornado.fastwebnet.it... > hi to all, > i'm planning to make a way to transfer file with python. > I would like to make the transfer using some crypto api, > to make the channel secure. > i don't want to write a wrapper to ftp or to scp i just > want to make a new protocol, for a little application. > > i took a quick look to some cryptographic modules available > in python (expecially pycrypto, gnupginterface, m2crypto) > and i'm now stuck on which one of these to choose. > > Here's what i have in my mind: Alice wants to upload/download > some files from Bob. > Both of them have the public key (made with gpg), so in the > handshaking for the shared key is done using gpg. > > After that the shared key is know to both the end of the channel > and they can use it to send the data. > > i don't know what protocol (AES 3DES Blowfish? ) to use for the > transfer and i don't know if it could be better to implement > it directly with DSA/RSA rather than using GPG + somesymmetricprotocol > > any suggestion hints example ? > Someone tried something like that ? > > i'm using SocketServer for the network stuff so i would like to find > something wich can better suit with it > > > Many thanks for all the suggestion you can give me . > > > Samuele > You could try PyOpenSSL for encryption over networks or the internet. See http://pyopenssl.sourceforge.net/. From jbperez808 at yahoo.com Wed Jun 9 10:41:36 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 09 Jun 2004 22:41:36 +0800 Subject: dropping into the debugger on an exception In-Reply-To: References: <2inqlrFp53m5U1@uni-berlin.de> Message-ID: <2iolfjFp6c46U1@uni-berlin.de> Thomas Heller wrote: > Is the description in the cookbook unclear? You do *not* have to add > anything to your script - save the code as a file > C:\Python23\sitecustomize.py and everything will work. And you don't > have to start the script from within pdb. The sitecustomize module is > automatically imported when Python starts - if it is found. Yes, I'm aware of this. I don't want to add this to sitecustomize.py because I don't want this happening all the time. I was hoping to for a different strategy. Would it be possible to start up pdb(), call a script from there, give it the equivalent of command line arguments, do a cont (or whatever is required) and then have it /stay/ within pdb if an unanticipated exception occurs (as opposed to having to set up a breakpoint)? From usenet at caesium.me.uk Fri Jun 25 20:24:47 2004 From: usenet at caesium.me.uk (Chris Share) Date: 26 Jun 2004 00:24:47 GMT Subject: Problems with range References: <40dcaff7$1_1@nova.entelchile.net> Message-ID: On Fri, 25 Jun 2004 19:06:39 -0400, Adrian Albisser wrote: > Hey to everybody, im just beginning to program in python. So i was trying > some function but always when i try the range function i get a error > message. > > for number in range(1,100): > print number > > Error---> There's an error in your program: > expected an indented block Read what the message tells you. The problem is not with your range function, it's the rest of the program. In Python, indenting is important; it tells the interpreter which bits go together. So your program should be: for number in range(1,100): print number Note the 4 spaces at the start of the second line. It doesn't have to be 4 spaces, but that's convention. I'd suggest you read a good python tutorial - I like http://www.freenetpages.co.uk/hp/alan.gauld/tutintro.htm And of course there's http://www.python.org/doc/current/tut/ on the python site itself. chris From Christian.Gudrian at gmx.de Sat Jun 5 10:59:14 2004 From: Christian.Gudrian at gmx.de (Christian Gudrian) Date: Sat, 5 Jun 2004 16:59:14 +0200 Subject: #! shbang for pyc files? References: Message-ID: "MarkV" schrieb: > .py extension to run it - just type "whatever" - but when you compile the > file, it loses this ability! Write a wrapper script: #!/bin/sh python mycompiledpythonprogram.pyc Christian From pampaluz at cox.net Mon Jun 7 09:04:29 2004 From: pampaluz at cox.net (Mark Seven Smith) Date: Mon, 07 Jun 2004 06:04:29 -0700 Subject: I think i figured out the list problem [python] In-Reply-To: References: Message-ID: <40C467DD.7080509@cox.net> David Stockwell wrote: > I took a break and got breakfast. maybe this helped. Heh...amazing what a little food now and then can do :-) --mVIIs From jacek.generowicz at cern.ch Thu Jun 17 03:27:20 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Jun 2004 09:27:20 +0200 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: Alexander Schmolck writes: > This dredging up of former quotes is generally a bad thing to do, but I'll do > it anyway in the hope to lay the whole thing to rest. > > > Alexander Schmolck writes: > >> [in] scheme, the standard iteration construct 'do' does indeed introduce > >> a *new binding* on each iteration. > > > Yes, but this is a consequence of Scheme faking iteration with > > recursion. > > Not really. What do you mean? (Forget the use of the word "faking".) Iteration-based recursion introduces a new binding because each iteration is a new function invocation with its concommittant binding of local variables. _The same happens in Python_ if you make use of a recursion-based iteration construct. That was the point of the post under discussion; to show that the perceived differences beteween the ways that closures work in Python and Scheme are a result of differences in the recursion constructs used, rather than differences in the way closures work. > I also hope to have made it comprehensible why your post might be > read in such a way and why readers of it might profit from > additional clarifying information. I agree that some people might profit from additional clarifying infromation. I also think that most of the information you provided is OT in this group ... and OT to the topic, which was about how _closures_ work in _Python_, and not about the merits (or demertis) of Scheme iteration. So, as you suggested, let's let it rest. PS Re-reading my previous reply I see that I probably sounded to agressive, defensive, whatever ... sorry. From chrisks at NOSPAMudel.edu Sat Jun 26 00:19:23 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 26 Jun 2004 00:19:23 -0400 Subject: Bug in Getsource? In-Reply-To: <5155aad2.0406250833.75d08d87@posting.google.com> References: <5155aad2.0406250833.75d08d87@posting.google.com> Message-ID: Konstantin Veretennicov wrote: > "Chris S." wrote in message news:... > >>I've noticed inspect.getsource acts strangely for lambda expressions. >>For instance: >> >>from inspect import getsource >>somefunc = lambda(a):abs(a) >>print 'somefunc source:',getsource(somefunc) >> >>results in: >> >>somefunc source: from inspect import getsource >> > > > Yep, same here. > > >>I'd understand if inspect can't handle lambda expressions, but claiming >>something is an object's source when it is obviously not is a bug IMO. >>Is this correct? Is there any way to fix this? > > > Looks like the problem is in inspect.findsource(), line 433 > pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))') > > As you can see, this pattern doesn't match (perfectly legal) "lambda(a):" > (note the parentheses). > > If I change pattern to r'^(\s*def\s)|(.*\slambda(:|\s|\())', > getsource returns "somefunc = lambda(a): abs(a)", > which is better, but still not satisfactory. > > Alas, I'm too lazy and/or stupid and/or busy to conceive a good patch ;) > > - kv How is your current fix not satisfactory? Is that not the correct code? From tismer at stackless.com Fri Jun 25 22:39:57 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 26 Jun 2004 04:39:57 +0200 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: References: Message-ID: <40DCE1FD.1040203@stackless.com> Doug Holton wrote: > Is there any metaclass trick or something similar to allow anonymous > code blocks? > > I'd like to be able to let users do something like this fictitious example: > b = Button() > b.OnClick =: > print "you clicked me" What exactly do you want to do? Why is defining a function too much for you? I can't see it is your problem since you are a Python programmer (or you would not ask for metaclass tricks) :-) Looks like a problem with an interface for users. Do you want to make the definition of actions in a GUI simpler for your users? In the latter case, it is probably simplest to define a smallish sub-language by a few rules, and create proper Python functions at initialization time? Feel free to contact me in private email if I'm right. ciao - chris p.s.: But please give me a real email address. I have no time to guess. -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From piet at cs.uu.nl Wed Jun 2 07:43:40 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 02 Jun 2004 07:43:40 -0400 Subject: [].index References: Message-ID: >>>>> Mike Edey (ME) wrote: ME> Good day. ME> Recently I'd run into wishing a list's index method would match ME> substrings. Being fairly new to this game I can't help but think that my ME> solution is a little, well, clumsy. In the following trivial example I'm ME> only interested in finding the first matching list item: >>>> data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo = >>>> ['b','e','e'] >>>> [data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for >>>> ix in range(len(foo))] ME> ['bbb', 'eee', 'eee'] ME> So I guess this question is - have I missed a cleaner method then this ME> nested list comprehension? It can be cleaned up: [d for d in data for x in foo if d.find(x) > -1] -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From ptmcg at austin.rr._bogus_.com Mon Jun 21 09:47:19 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 21 Jun 2004 13:47:19 GMT Subject: DocumentationTools (docstring --> html) References: Message-ID: "Thomas Guettler" wrote in message news:pan.2004.06.21.07.03.15.264772 at thomas-guettler.de... > Hi, > > I want to create documentation in html > from docstrings. According to this URL, > there are many projects: > > http://www.python.org/cgi-bin/moinmoin/DocumentationTools > > * PyDoc, http://web.pydoc.org/ > * DocUtils, http://docutils.sourceforge.net/ ReStructuredText processing engine > * EpyDoc, http://epydoc.sourceforge.net/ > * HappyDoc, http://happydoc.sourceforge.net/ > * PythonDoc - uses ReStructuredText input format, and can produce HTML and XML output. It uses XML as an intermediate representation, to simplify the addition of new output formats. http://starship.python.net/crew/danilo/pythondoc/ > * Crystal - produces output that is similar to [Wiki]JavaDoc. > * EasyDoc - uses an HTML-like markup language, similar to the language used by [Wiki]JavaDoc; and produces HTML output (http://htmltmpl.sourceforge.net/easydoc.html) > * Teud, [EfnetPythonWiki]TeudProject > > Can someone give me an advice which one to > choose? > > Thomas > I found EpyDoc *very* easy to use, and the results are beautiful! -- Paul From dudley.carr at gmail.com Thu Jun 10 21:47:33 2004 From: dudley.carr at gmail.com (Dudley) Date: 10 Jun 2004 18:47:33 -0700 Subject: OleLoadPicturePath and IID_IPicture Message-ID: I'm trying to use load a picture to be used with an ActiveX object. The only way that I can see this being done using using win32com.axcontrol.axcontrol.OleLoadPicturePath. The last argument for OleLoadPicturePath requires a PyIID for specifying the interface of the object to be returned. From the VB examples I've seen scattered around the Internet, most people use IID_IPicture. However, it doesn't seem that IID_IPicture is available among the predefined IIDs in pythoncom or any of the other modules. I assume there must be some way to instantiate and IID even if it's not predefined, but I can't find the method that would do that. Thanks, D From lard at tardis.ed.ac.molar.uk Fri Jun 25 07:33:02 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Fri, 25 Jun 2004 12:33:02 +0100 Subject: python image library making dotty gifs Message-ID: <10do3bfmr93ke48@corp.supernews.com> I'm using python image library 1.1.4 (http://www.pythonware.com/products/pil/) to plot images. However, when I save an image to a gif file, it comes out very dotty/ithered looking, even if it's a picture consisting only of one colour! Here's some example code that produces a dotty gif: #!/usr/bin/python # pymand joy! import Image import ImageDraw imageWidth=300 imageHeight=300 im = Image.new("RGB", (imageWidth, imageHeight)) draw = ImageDraw.Draw(im) for y in range (0,imageHeight): for x in range (0, imageWidth): draw.point((x, y), (128,128,128)) # saving as a gif comes out dotty/dithered looking! im.save("plotImage.gif", "GIF") you can see the output gif here: http://ohmslaw.ogr.uk/plotImage.gif what causes the dottyness, anyone know? alex From peter at engcorp.com Fri Jun 11 15:29:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 15:29:07 -0400 Subject: Anonymous file closing In-Reply-To: References: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> Message-ID: Sergey Krushinsky wrote: > Peter Hansen wrote: > >> Duncan's response says it all, but here's the solution >> if you don't like the uncertainty inherent in the above: >> >> f = open(filename, 'r') >> try: >> text = f.read() >> finally: >> f.close() >> > But the uncertainty remains in case of an anonymous file, doesn't it? What's an "anonymous file"? The term means nothing to me... From dieter at handshake.de Sun Jun 13 13:37:00 2004 From: dieter at handshake.de (Dieter Maurer) Date: 13 Jun 2004 19:37:00 +0200 Subject: Insecure Pickling References: <781dd16f.0406111114.17959b90@posting.google.com> <7xacz9x1z2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes on 11 Jun 2004 13:40:33 -0700: > surferjeff at gmail.com (Jeff) writes: > > However, it is so insecure it can hardly ever be used. How often can > > you truly trust the think you're unpickling? > > If it's a pickle you created yourself and nobody else has had a chance > to tamper with, then it's presumably trustworthy. You could use encrypted pickles to make sure that nobody without knowledge of the encryption key can create pickles you are ready to unpickle. Of course, this raises the question how secure you can manage the encryption key. Dieter From hungjunglu at yahoo.com Fri Jun 18 12:09:13 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 18 Jun 2004 09:09:13 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: <8ef9bea6.0406180809.10053ba6@posting.google.com> Rob Williscroft wrote: > > But python has static variables. > > def another( x ): > y = getattr( another, 'static', 10 ) > another.static = x > return y > > print another(1), another(2), another(4) What about the following case: def f(): f.static = getattr(f, 'static', 0) f.static += 1 return f.static print f(), f(), f() # prints 1 2 3 As opposed to C++, you now have a line of code that is always executed in subsequent calls, for no good reason. This is worse than: def f(static=[0]): static[0] += 1 return static[0] in the sense that you have a wasteful call ("getattr") that doesn't do anything productive in subsequent calls. (You could change that to f.static = getattr(f, 'static', 0) + 1, but the "getattr" is surely inefficient compared to f.static += 1, and internally likely incurs some conditional statement at some level.) Maybe one can do instead: def f(): global f def f(): f.static += 1 return f.static f.static = 0 # initialization return f() print f(), f(), f() # prints 1 2 3 The advantage is there is no more wasteful statements in subsequent calls. No "if" conditional statement. The above is of course a toy example to illustrate the case of a function that needs to perform something special the first time it is called. (I am well aware of the outside assignment like: def f(): f.static += 1 return f.static f.static = 0 mentioned in this thread, but I am talking about something more general. Notice that in the latter case, f.static=0 is done before f() is called, which may not be what one wants. E.g.: if f() is never called, this assignment is wasteful. Not a problem in this case, for if complicated initialization is needed, like requiring a timestamp, it may not be a good idea.) In code refactoring, the equivalent is to replace conditional statements by polymorphism. In terms of codeblocks, what I mean is dynamic hook-on and hook-off of codeblocks. If the underlying language is powerful enough, one should be able to achieve runtime restructuring of code, without performance impact for subsequent calls. regards, Hung Jung From jepler at unpythonic.net Fri Jun 4 08:08:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 4 Jun 2004 07:08:02 -0500 Subject: simplify printing of a list In-Reply-To: <3064b51d.0406031408.1b676379@posting.google.com> References: <3064b51d.0406031408.1b676379@posting.google.com> Message-ID: <20040604120801.GA9010@unpythonic.net> On Thu, Jun 03, 2004 at 03:08:57PM -0700, beliavsky at aol.com wrote: > To print a list with a specified format one can write (for example) > > for j in [0,1,2]: > print "%6d"%j, > print > > The code > > print "%6d"%[0,1,2] > > currently produces a syntax error, No, it doesn't. (it produces a TypeError) > but it would be convenient if it > had the same meaning as the loop above. No, it wouldn't. [remainder deleted] Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From uthand at hotmail.com Wed Jun 16 04:38:17 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 16 Jun 2004 01:38:17 -0700 Subject: Python interceptor package Message-ID: Hi group I'm looking for a Python interceptor package, which will allow me to intercept the invocation of any function or method call. For those familiar with CORBA interceptors, this should be roughly analogous (though simpler as we don't have a client and server side) but should work for any native Python invocation. A trivial but practical use of such interceptors could be to log such invocations (also see the 'Interceptor pattern' from POSA2 by Douglas Schmidt, et. al.) In particular - It should be possible to intercept - Method calls (instance, class and static methods), either for a specific instance or for all instances of a class (possibly distinguishing between inherited and new or overridden methods) - Function calls - Calls to other callables - It should not require any modification to existing modules in a system - It should be possible to install and remove such interceptors at run-time (deriving a class and overriding a method is not an option). - It should be possible to install multiple interceptors (serving different purposes) for any function/method Has any work been done in this direction? Thanks Fritz From MAIL-SA at gcc-sg.org Thu Jun 24 23:53:58 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Fri, 25 Jun 2004 06:53:58 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F65092597@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = cbgranada at telefonica.net Recipient(s) = python-list at python.org; Subject = Re: Delivery Protection Scanning Time = 06/25/2004 06:53:58 Engine/Pattern = 7.000-1004/915 Action on message: The attachment data_python-list.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From corey.coughlin at attbi.com Thu Jun 24 19:36:09 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 24 Jun 2004 16:36:09 -0700 Subject: z80 vs Python References: Message-ID: Personally, if I had the time, I'd try porting python to a gumstix board: http://www.gumstix.com/ It probably wouldn't be too hard, but still, it'd be fun to get it onto that tiny board. :) "Janusz U." wrote in message news:... > > I wouldn't recommend this. The standard Python interpreter is quite hefty > > (>700K dynamically linked), not to mention the standard libraries. Seeing > > as Z80 has only 64K address space, I don't see a full implementation as > > possible. > > I know. Sorry, I didn't precise. I thought exactly about eZ80F91 - it's > based on Z80 but much more expanded... I will start on the module (and > deviloper kit) for that procesor. It would be independent platform for > tests software in the Python. > > > What you /could/ do would be to implement a (very) small subset of Python; > > i.e. leave out generators, new-style class, list comprehensions, ability > > to override built-in types, functions, and operators, and most of the > > standard library, then you /might/ be able to fit a language with Pythonic > > syntax in that address space. > > I think to expand language by own library for Python - eg. control GPIO of > eZ80, read > > > > > Another issue would be speed. Z80s, though they've gotten faster over the > > years, still only run at speeds on the order of 10MHz. You might be better > > off writing a Z80 compiler for a Python-esque language -- this would save > > both speed and memory. > > speed 50MHz (or 20MHz in F92, F93...) > > > > > If you can pick a different chip, go with something like a StrongARM. > > These have the power and address space necessary for Python. Plus, it's > > been done before (Python runs beautifully on modern PDAs). > > I have just bought the developer kit for eZ80 so I have limited way. I'd be > happy to run Python on eZ80 platform. > > thx > Janusz U. > > > If you stick with the Z80 though, you've got quite a challenge ahead of > > you - good luck! If you succeed, you'll be sure to make hackers of Game > > Boys, TI-83s, and TRS-80s everywhere deliriously happy. > > From nbdy9 at removethis.hotmail.com Sat Jun 5 16:11:23 2004 From: nbdy9 at removethis.hotmail.com (nick) Date: Sat, 05 Jun 2004 16:11:23 -0400 Subject: print problem Message-ID: I want to print something without a '\n' automatically added at the end, I know print 1, print 2, print 3, can partially solve the problem. But it added an space behind each variable. So the statements above will print out: 1 2 3 instead of 123 Any way that I can just use it as printf in C? From davidf at sjsoft.com Wed Jun 2 06:27:43 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 12:27:43 +0200 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: Peter Maas wrote: > has schrieb: > >> Announcing the final v1 release of HTMLTemplate; best damn HTML >> templating system evar, or yer money back. Enjoy! :) > > > Good work BUT > there are some other Python templating frameworks around, e.g. > > - Cheetah > - ZOPE's TAL > - about half a dozen TAL derivatives > - Quixote's PTL > - SkunkWeb's STML > - Yaptu > - XYaptu > - Template Macro > > Did you find these alternatives unsatisfactory? If somebody wants > to use a Python templating framework why should he prefer > HTMLTemplate? > > Mit freundlichen Gruessen, > > Peter Maas > It looks cool because it doesn't embed Python code in the template. Do any of the other frameworks have this approach? David From michael at foord.net Tue Jun 8 06:58:51 2004 From: michael at foord.net (Fuzzyman) Date: 8 Jun 2004 03:58:51 -0700 Subject: My Experiences Subclassing String References: <8089854e.0406070423.5d2d1d71@posting.google.com> <510xc.52456$mQ4.51566@fe2.texas.rr.com> Message-ID: <8089854e.0406080258.2d49acf8@posting.google.com> "Paul McGuire" wrote in message news:<510xc.52456$mQ4.51566 at fe2.texas.rr.com>... [reluctant snip...] > > class SpecialA(object): > pass > > class A(object): > def __new__(cls,*args): > print cls,":",args > if len(args)>0 and args[0]==2: > return object.__new__(SpecialA) > return object.__new__(cls) > > obj = A() > print type(obj) > obj = A(1) > print type(obj) > obj = A(1,"test") > print type(obj) > obj = A(2,"test") > print type(obj) > > gives the following output: > > : () > > : (1,) > > : (1, 'test') > > : (2, 'test') > > > > HTH, > -- Paul Thanks Paul, that was helpful and interesting. I've posted the following correction to my blog : Ok... so this is a correction to my post a couple of days ago about subclassing the built in types (in python). I *nearly* got it right. Because new is the 'factory method' for creating new instances it is actually a static method and *doesn't* receive a reference to self as the first instance... it receives a reference to the class as the first argument. By convention in python this is a variable named cls rather than self (which refers to the instance itself). What it means is that the example I gave *works* fine, but the terminology is slightly wrong... See the docs on the new style classes unifying types and classes. Also thanks to Paul McGuire on comp.lang.pyton for helping me with this. My example ought to read : class newstring(str): def __new__(cls, value, *args, **keywargs): return str.__new__(cls, value) def __init__(self, value, othervalue): self.othervalue = othervalue See how the __new__ method collects all the other arguments (using the *args and **keywargs collectors) but ignores them - they are rightly dealt with by __init__. You *could* examine these other arguments in __new__ and even return an object that is an instance of a different class depending on the parameters - see the example Paul gives... Get all that then ? :-) From bill.ramsay at clear.net.nz Fri Jun 4 01:40:08 2004 From: bill.ramsay at clear.net.nz (bill ramsay) Date: Fri, 04 Jun 2004 17:40:08 +1200 Subject: two silly questions References: Message-ID: On Thu, 3 Jun 2004 10:49:50 -0500, "Larry Bates" wrote: >The absolute "best" way to do what you want is to write >an NT service. Mark Hammond's Python Programming on >Win32 has excellent examples of this. NT services >run in the background and can be set to actually sleep >for any amount of time (in microseconds). I've written >several of these and while the learning curve is a >little steep on the front end, the resulting application >is MUCH better. > thanks for this, much appreciated, funnily enough i had a sniff in there today, and i think i found what you are reffering to. kind regards bill ramsay >HTH, >Larry Bates >Syscon, Inc. > >"bill ramsay" wrote in message >news:upetb0dimckv16o1b1actl9tngej94enkf at 4ax.com... >> Hello >> >> just found the wonderful world of python in the last two weeks and I >> think that it is great. >> >> I have a couple of questions for those who are wiser a la python than >> I am. >> >> Background: >> >> I have written a program that polls an email account, then pulls down >> the email, it then searches through the email, and depending upon >> type, ie. with or without attachments it does different things. The >> net result is that data is written to access tables for an external >> application to extract the necessary data. >> >> I am using win2k. >> >> the two questions are: >> >> 1. when i want the program to run in a loop, ie. poll the pop3 >> account every 60 seconds, it runs the first time, then it goes into >> 'not responding mode' thereafter, sometimes. Any thoughts? I was >> using sleep(60) but it just hangs, as i said before, it does not >> always do that either! >> >> 2. I wish to use this program at work, I took in an earlier version >> yesterday that just wrote the data to a text file, I wanted to make >> sure the polling thing worked. on microsoft exchange [i know that it >> should, but you never know!!] and it does . When i was there, i >> managed to get the code to run just by double clicking on the code >> ICON, seem to remember doing something with 'open with' can't seem to >> do it here at home. >> >> Both systems run win2k. did i do something sublimilally without >> realising it? what did i do i cannot remember, i have tried opening >> with etc. when i do this all get is a burst of the 'black windows >> box' just in the same way as putting in 'cmd' on the run thing, >> >> as you can see i am not up on all the terms. >> >> if anyone can help, i would appreciate it. >> >> kind regards >> >> bill ramsay. >> > From anthony at interlink.com.au Thu Jun 10 11:25:02 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Fri, 11 Jun 2004 01:25:02 +1000 Subject: python.org CMS In-Reply-To: References: Message-ID: <40C87D4E.6020601@interlink.com.au> Aahz wrote: > In article , > Neil Benn wrote: >> I administer a site (http://www.elrig.org) using postnuke >>(http://www.postnuke.com), it's very easy to use and can be customised >>using PHP. It does have limitations (as do all CMS packages) but it >>really does cut down the amount of time I have to spend mucking around >>with the site. > > > I'm pretty sure that nobody will be greatly surprised that an unwritten > criterion was that the solution needs to be Python-based. ;-) Speaking as someone who does a middling amount of fiddling with python.org as part of the release process, I will be _very_ cranky if I have to touch PHP. Say no to toy languages. Anthony, intolerant. -- Anthony Baxter It's never too late to have a happy childhood. From theller at python.net Mon Jun 7 03:26:39 2004 From: theller at python.net (Thomas Heller) Date: Mon, 07 Jun 2004 09:26:39 +0200 Subject: py2exe/wxpython demo References: Message-ID: Bryan writes: > just for fun and my own experience, i wanted to use py2exe to wrap the > wxpython demo. i put the setup script in the demo directory which is > the following: > > > from distutils.core import setup > import glob > import py2exe > > setup(windows=['demo.py'], > data_files=[('bitmaps', glob.glob('bitmaps/*.*')), > ('data', glob.glob('data/*.*')), > ('bmp_source', glob.glob('bmp_source/*.*')), > ('', glob.glob('*.py'))], > ) > > > > > and ran the command like this: > > > setup py2exe --ignores wx.BitmapFromImage,wx.EmptyIcon > --includes ActiveX_FlashWindow,ActiveX_IEHtmlWindow > > > this was successful except for one thing... do i really have to > explictly list every script file in the demo directory in the > --includes argument on the command line? there are so many. i was > hoping to somehow be able to add it in the script as a glob, but > nothing i did worked. You can pass these to the setup function in an 'option' dictionary: setup(.... options={"py2exe": {"ignores": ["wx.BitmapFromImage", "wx.EmptyIcon"], "includes": ["ActiveX_FlashWindow", "..."]}}, ...) See also the wiki: Thomas From lbates at swamisoft.com Thu Jun 24 09:53:29 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 24 Jun 2004 08:53:29 -0500 Subject: python service problem References: Message-ID: <6NKdnaDwjYlTQUfdRVn-uA@comcast.com> While it is unclear what your specific problem is, I can tell you that this is not a "known" problem with Python services. I have a development machine that I have installed/removed one service on at least 100 times over the course of development and it works properly. During that time I installed/ran it both as a PythonService and as a frozen py2exe service many, many times. I can tell you that I use InnoInstaller to do my installations and have it "clean" up during uninstallation by removing the left over registry keys. If you cannot remove them, I would suspect a "rights" issue (no administrative rights?). HTH, Larry Bates Syscon, Inc. "David Fraser" wrote in message news:cbe77j$dol$1 at ctb-nnrp2.saix.net... > Hi > > We are trying to debug a problem with services created using py2exe. > It seems that these problems have arisen after services were installed > and removed a few times. > > OK, first the actual problem we're seeing. After compiling a service > with py2exe, running "service -install" and attempting to start it from > the Services dialog, it pops up the message "Windows could not start the > Service on Local Computer. For more information, review the System > Event Log. If this is a non-Microsoft service, contact the service > vendor, and refer to service-specific error code 1.". > > The only thing in the System Event Log is an error logged by Service > Control Manager saying the service terminated with service-specific error 1. > > Now, the causes. On all the computers we've seen this problem, the > service has been installed at least once before and has been able to > start/stop properly. On two of the computers, the problem arose after > uninstalling the service, installing it with "python service.py service > --install", running it with pythonservice in debug mode, uninstalling it > with "python service.py service --remove", and then reinstalling from > the executable. Since then, the only way it ill run is from > pythonservice in debug mode. > > On the third computer, the service was installed from executable, and > then reinstalled from an updated executable. I'm not sure how many > times the old executable was installed and uninstalled (at most three > times), but the updated > executable only ran once, and then showed the error. > > One thing I noticed about the first computer is that, even after > uninstalling everything, there were some registry entries to do with the > installed services. I could not delete these entries - I got an access > denied error (details below) > > Does anybody have any ideas? > > TIA, > David Fraser > > Registry details: The service is called jHistExportService > > The important remnant seems to be: > HKLM\SYSTEM\ControlSet002\Services\jHistExportService and children > > which actually holds details of how to run the service. For the record, > the other remnants are: > HKLM\SYSTEM\ControlSet001\Enum\Root\LEGACY_JHISTEXPORTSERVICE and children > > HKLM\SYSTEM\ControlSet001\Services\EventLog\Application\jHistExportService > and children > > HKLM\SYSTEM\ControlSet002\Services\EventLog\Application\jHistExportService > and children > HKLM\SYSTEM\CurrentControlSet\Enum\Root\LEGACY_JHISTEXPORTSERVICE > > HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\jHistExportServi ce From BELLEMAIL-SA at exponent.com Fri Jun 18 01:51:43 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 22:51:43 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28ECC@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = sandysj at juno.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 239 Scanning time = 06/17/2004 22:51:42 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment jennifer the wild girl xxx07.jpg.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From flupke at nonexistingdomain.com Mon Jun 21 11:46:25 2004 From: flupke at nonexistingdomain.com (flupke) Date: Mon, 21 Jun 2004 15:46:25 GMT Subject: (OT) wxPython & resizers, html text (code included) Message-ID: Hi, i'm trying to convert my java console app to a python gui. Now, the only problem i seem to have at the moment are the resizers for the layout. It seems that for the purpose of what i'm trying to do, specifying the coordinates is easier that fighting with the layout resizers. 1) I have a screen split in 2. Left side is a textcontrol where logging will end up. All text will be appended to the textcontrol. Ideally this should allow html tags but the wxHtmlWindow doesn't seem to support just adding text. Only workaround that i can think off is to maintain a list of message myself and then i could set those every time something changes but i don't really like this as on every change, the whole textcontrol will be refilled. The reason for html is to easily adjust text from one colour to another and for instance some basic formatting like bold, italic etc. Any ideas? 2) (view with for instance with courier) ----------------------------------------------- | TextControl | ________ | | ||________| Combobox | | | | | | ________ | | ||________| | | | | | | ________ | | ||________| Textcontrol | | | | ----------------------------------------------- Basically i have a number of button left-aligned in the right part of the split window and they are placed vertically with a small gap in between (border). This is working but then i would want to add a combobox next to button 1 and saya textcontrol to button 2. A gridresizer would work if i would be able to specify what row and column the component would have to be in but there doesn't seem to be such a method. Only sollution i can think of is adding the coordinates of where i want to component to come. Is there another sollution as i read that it's best not to add components by specifying an x and y value. Thanks ============== Working snippet below ======================= from wxPython.wx import * import sys, os ID_ABOUT=100 ID_EXIT=101 ID_BUTTON_CONNECT=200 ID_BUTTON_CHECK=201 ID_BUTTON_CONNECTIONS=202 ID_BUTTON_SEND=203 ID_BUTTON_HELP=204 ID_BUTTON_EXIT=205 class MainWindow(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self,parent,id,title, style=wxDEFAULT_FRAME_STYLE| wxNO_FULL_REPAINT_ON_RESIZE) self.split_window = wxSplitterWindow(self, -1) self.button_pane = wxPanel(self.split_window, -1, style=wxTAB_TRAVERSAL|wxNO_FULL_REPAINT_ON_RESIZE) self.logging_screen = wxTextCtrl(self.split_window, -1, "", style=wxTE_MULTILINE|wxHSCROLL) #self.html_window = new wxHtmlWindow( self ) self.connect = wxButton(self.button_pane, ID_BUTTON_CONNECT, "connect") self.check = wxButton(self.button_pane, ID_BUTTON_CHECK, "check") self.connections = wxButton(self.button_pane, ID_BUTTON_CONNECTIONS, "connections") self.send = wxButton(self.button_pane, ID_BUTTON_SEND, "send") self.help = wxButton(self.button_pane, ID_BUTTON_HELP, "help") self.exit = wxButton(self.button_pane, ID_BUTTON_EXIT, "exit") #make the combobox for the connections sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', #'this is a long item that needs a scrollbar...', 'six', 'seven', 'eight'] self.cb = wxComboBox( self.button_pane, 500, "default value", (90, 50), (95, -1), sampleList, wxCB_DROPDOWN #|wxTE_PROCESS_ENTER ) # Menu Bar self.frame_1_menubar = wxMenuBar() self.SetMenuBar(self.frame_1_menubar) self.File = wxMenu() self.File.Append( ID_ABOUT, "&About", "About CheckServer Client" ) self.File.AppendSeparator() self.File.Append( ID_EXIT, "E&xit", "Leave the application" ) self.frame_1_menubar.Append(self.File, "F&ile") EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.OnExit) # Menu Bar end self.statusbar = self.CreateStatusBar(1, wxST_SIZEGRIP) self.__set_properties() self.__do_layout() self.Show(true) # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("CheckServer Client") _icon = wxEmptyIcon() _icon.CopyFromBitmap(wxBitmap("D:\\temp\\1anipt1c.gif", wxBITMAP_TYPE_ANY)) self.SetIcon(_icon) self.SetSize((723, 533)) self.SetFocus() self.logging_screen.SetBackgroundColour(wxColour(247, 255, 159)) self.logging_screen.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Century Gothic")) self.logging_screen.SetToolTipString("Here you'll see the result of the commands you issue to the server") self.logging_screen.SetDefaultStyle(wxTextAttr(wxColour(255,0,0))) self.logging_screen.AppendText("Red text\n"); self.logging_screen.AppendText("Test\n"); self.logging_screen.Enable(0) self.connect.SetSize((110, 28)) self.connect.SetBackgroundColour(wxColour(143, 188, 143)) self.connect.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial Black")) self.connect.SetToolTipString("Connect to a server") self.connect.SetFocus() self.check.SetSize((110, 28)) self.check.SetBackgroundColour(wxColour(143, 188, 143)) self.check.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial Black")) self.check.SetToolTipString("Check server directories") self.check.Enable(0) self.connections.SetSize((110, 28)) self.connections.SetBackgroundColour(wxColour(143, 188, 143)) self.connections.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial Black")) self.connections.SetToolTipString("What connections are active") self.connections.Enable(0) self.send.SetSize((110, 28)) self.send.SetBackgroundColour(wxColour(143, 188, 143)) self.send.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial Black")) self.send.SetToolTipString("Send a file from the server to local pc") self.send.Enable(0) self.help.SetSize((110, 28)) self.help.SetBackgroundColour(wxColour(143, 188, 143)) self.help.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial Black")) self.help.SetToolTipString("Display help options (command line)") self.exit.SetSize((110, 28)) self.exit.SetBackgroundColour(wxColour(143, 188, 143)) self.exit.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial Black")) self.exit.SetToolTipString("Exit the application") self.button_pane.SetFocus() self.button_pane.SetBackgroundColour(wxBLUE) self.statusbar.SetStatusWidths([-1]) self.split_window.SetMinimumPaneSize(20) # statusbar fields statusbar_fields = ["CheckServer"] for i in range(len(statusbar_fields)): self.statusbar.SetStatusText(statusbar_fields[i], i) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout split_window_sizer = wxBoxSizer(wxVERTICAL) button_pane_sizer = wxBoxSizer(wxVERTICAL) button_pane_sizer.Add(self.connect, 0, wxALL, 2) button_pane_sizer.Add(self.check, 0, wxALL, 2) button_pane_sizer.Add(self.connections, 0, wxALL, 2) button_pane_sizer.Add(self.send, 0, wxALL, 2) button_pane_sizer.Add(self.help, 0, wxALL, 2) button_pane_sizer.Add(self.exit, 0, wxALL, 2) button_pane_sizer.Add(self.cb,0, wxALL, 2) self.button_pane.SetAutoLayout(1) self.button_pane.SetSizer(button_pane_sizer) button_pane_sizer.Fit(self.button_pane) button_pane_sizer.SetSizeHints(self.button_pane) self.split_window.SplitVertically(self.logging_screen, self.button_pane) split_window_sizer.Add(self.split_window, 1, wxEXPAND, 0) self.SetAutoLayout(1) self.SetSizer(split_window_sizer) self.Layout() self.Centre() # end wxGlade def OnAbout(self,e): d= wxMessageDialog( self, " A sample editor \n" " in wxPython","About Sample Editor", wxOK) # Create a message dialog box d.ShowModal() # Shows it d.Destroy() # finally destroy it when finished. def OnExit(self,e): self.Close(true) # Close the frame. # end of class MyFrame class App(wxApp): def OnInit(self): wxInitAllImageHandlers() main_window = MainWindow(None, -1, "CheckServer Client") self.SetTopWindow(main_window) return true # end of class App app = App(0) app.MainLoop() From taj at kde.org Wed Jun 16 07:48:31 2004 From: taj at kde.org (taj at kde.org) Date: Wed, 16 Jun 2004 21:48:31 +1000 Subject: Here is the document Message-ID: Please read the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: document_full.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From __peter__ at web.de Thu Jun 17 07:43:07 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 13:43:07 +0200 Subject: getting arguments off the command line References: Message-ID: David Stockwell wrote: > Whats a good way to get arguments off of the command line? http://docs.python.org/lib/module-optparse.html Peter From chuck at smtl.co.uk Tue Jun 8 11:58:48 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 16:58:48 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "08 Jun 2004 10:59:15 GMT." <2ilkg2For39hU1@uni-berlin.de> References: <2ijmctFnvgjeU2@uni-berlin.de> <2ilkg2For39hU1@uni-berlin.de> Message-ID: <200406081558.i58Fwmeb000528@sevenofnine.smtl.co.uk> Hi again after breaking down the script into easier chunks . I now get this . Here's the output from the script but WHAT about all messages bodies Cheers chuck at sevenofnine:~/pythonScript> python getSurveyMail.py mail WWW Survey text/plain Country you are currently working in:UNITED STATES Postal code or ZIP Code of your facility if you know it: 12345 Your Profession:Nurse How long you have been qualifed:< 1 Year Is Wound Management Your primary role:A major part of your daily activities Specific area of interest in the list below:Veterinary medicine Do you read a paper – based wm journal:Yes If Yes your comments:bugs news Favorite topics in the World Wide Wounds:['Dressings information', 'News'] Further Information: required:all covered really Your Email Address:it at smtl.co.uk From michael at foord.net Sun Jun 27 10:34:40 2004 From: michael at foord.net (Fuzzyman) Date: 27 Jun 2004 07:34:40 -0700 Subject: Case insensitive dictionary? References: <9418be08.0406250921.71f4eba4@posting.google.com> Message-ID: <8089854e.0406270634.2a3cf1b8@posting.google.com> elbertlev at hotmail.com (Elbert Lev) wrote in message news:<9418be08.0406250921.71f4eba4 at posting.google.com>... > Hi! > > Here is the problem: > > I have a dictionary. Keys are strings. How to make dictionary lookup > case insensitive? > > In other words: > If dict = {'First":"Bob", "Last":"Tom"}, dict["first"] should return > "Bob" > > Maybe dictionary is not the right data type? If so what is? I'm probably a bit late on this one... but I've written a complete case-insensitive dictionary (and list..) with all dictionary methods implemented.... It's called caseless and available at : http://www.voidspace.org.uk/atlantibots/pythonutils.html#configobj I've tested it fairly well as it the base class for my configuration module ConfigObj. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From dbasch at yahoo.com Wed Jun 16 22:42:32 2004 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 17 Jun 2004 02:42:32 GMT Subject: Combined natural and unnatural list sorting References: Message-ID: In article , __peter__ at web.de says... > Derek Basch wrote: > > > I have a list like so: > > > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] > > > The order that I actually need is: > > > > ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] > > > I looked for a while at using comparison functions with sort but I don't > > think that will work. Anyone been down this road? Suggestions? > > Here's a slightly more complicated approach. Turn what was the "unnatural" > into the "natural" order: > > from itertools import count > > class Size(object): > all = {} > _nextIndex = count().next Wow! Thanks for sharing the knowledge everyone. I think I am starting to get my head around these sorting idioms. It will take me a bit to study all the code you sent. Every day the forums remind me what a noob I am ;) From max at alcyone.com Thu Jun 17 22:08:16 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jun 2004 19:08:16 -0700 Subject: Why does one work, but not the other? References: Message-ID: <40D24E90.960D7FBD@alcyone.com> j_mckitrick wrote: > but when I try: > > self.liststore = [[item] for item in data] > > instead of: > > for item in data: > self.liststore.append([item]) > > I get an empty list! What gives?? You're probably doing something else wrong; this fragment works fine: >>> data = [1, 2, 3, 4] >>> [[item] for item in data] [[1], [2], [3], [4]] -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Ferocious, aren't I? -- Lt. Vincent Hanna From dummy at scriptolutions.com Tue Jun 15 06:20:46 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Tue, 15 Jun 2004 12:20:46 +0200 Subject: (OT) Boa Constructor and Python 2.3.4 References: Message-ID: On Tue, 15 Jun 2004 10:15:39 GMT, "flupke" wrote: >Hi, > >My wxPython is version 2.5.1.5u. >Any ideas? > AFAIK the CVS version only works with wyPython 2.4. From mcfletch at rogers.com Fri Jun 11 18:37:29 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 11 Jun 2004 18:37:29 -0400 Subject: [PyOpenGL] How do I save runtime on drawing HUGE polylines (120 000 vertices)? In-Reply-To: References: Message-ID: <40CA3429.5060006@rogers.com> F. GEIGER wrote: ... > The above print statement shows, that 5 secs are consumed for about > 120 000 (hundred-twenty-thousand) vertices. You guess, the whole GUI > becomes unusable. ... > So I wonder, do I really need to draw those 120000 vertices over and > over again? Yes, that's the nature of OpenGL. > Would glArrays perform much better? Certainly. The array-drawing functionality is always going to be faster than writing loops in Python. You'll notice that OpenGLContext goes to great lengths to push almost all of its rendering into array-based operations. > Or is this a case for Display Lists? Any other idea? Display lists should be fine too, though you'd still have a 5 second delay waiting for them to compile. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From thorsten at thorstenkampe.de Mon Jun 21 14:01:09 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 21 Jun 2004 20:01:09 +0200 Subject: Windows XP - cron or scheduler for Python? References: Message-ID: * Peter Hansen (2004-06-21 19:35 +0200) > Ivan Voras wrote: >> Peter Hansen wrote: >>> Larry Bates wrote: >>>> 2) Always call Python and have it run the application. >>>> Don't just try to run progname.py. >>> >>> This actually works, though, at least on my system. It >>> might be because I inserted .py in the PATHEXT env var >>> globally, though I thought it was just because running >>> a .py is possible simply by clicking on it in Explorer >>> (ie. the File Association does the job). >> >> No, putting .py in PATHEXT is necessary. That way, you can run python >> programs from the command line (cmd) using just "scriptname", without >> the extension! (it performs just like .bat, .exe and similar files) > > Are you sure? I just tried removing .py from my PATHEXT and > not only did it still work from Explorer, it even worked from > the command line! > > Then I tried redirecting the File Assocation under File Types > to point to notepad instead of python. Now typing "xxx.py" > at the command line or clicking on the xxx.py file in > Explorer both launch Notepad to edit the file. > > I'm not sure what PATHEXT is really needed for, but executing > .py files on the command line in Windows XP does not seem to > be one of them... "PATHEXT" enables you to run files in the path with these extensions without extension (for example "winword" instead of "winword.exe"). The cmd shell actually performs an "open" action. For executables "opening" is running them. For documents it's starting the associated application and opening the document in it. For .py both things are reasonable. Thorsten From beliavsky at 127.0.0.1 Fri Jun 4 13:28:51 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 4 Jun 2004 12:28:51 -0500 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> Message-ID: <40c0b153$1_1@127.0.0.1> klachemin at home.com (Kamilche) wrote: >Man, I've been banging my head against a C program for a while now. >I'm embarrassed to admit how long. I really want to use Python, as I >mentioned in a prior post, but the speed hit is such that I'll >probably use it only for prototyping. > >But boy, development sure is fast in Python! Today, while playing with >it, I thought of a better way to arrange my data, that makes the >program more flexible. It's a good enough idea to warrant redoing my >code (even my C code) to take advantage of it. When I went to write up >the pseudocode to process the new method, I found myself naturally >using Python. > >C is just so... detail oriented. By the time I set up the data >structures, do the string manipulation and memory management, I can >hardly remember what it was I was initially trying to accomplish, much >less think of a better way to do it! Maybe I'm just getting old... but >Python just fits my idea of 'mental pseudocode' so well, it's hard to >resist using it. Dictionaries ARE an underutilized concept in DP, and >I was using them up the yin yang, even in my C program. Python meshes >well with my programming style. > >--Kamilche I am no C++ expert, to put it mildly, but couldn't some of your problems have been solved by using C++ instead of C? C++ has data structures like vectors, lists, and maps, with many algorithms in the STL to work with them. Using references to pass arguments, one can avoid low-level pointers in many cases. C++ strings are easier to use the C char's. There are templated classes to replicate some of the functionality of Python's Numeric/Numarray or Fortran 90/95 arrays. C is more of a low-level systems language than an application programming language -- comparing it to Python seems unfair to me, when the choice of C++ exists. For strictly numerical tasks Fortran 95 is in my experience both more readable than Python (because of variable declarations and the ability to define constants) AND much faster. You do not have to suffer Python's performance hit to program in a clean, high-level language. (I like Python, but there is so much pro-Python propaganda in this newsgroup that some anti-Python messages may be a healthy corrective.) ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From klachemin at home.com Wed Jun 9 23:35:19 2004 From: klachemin at home.com (Kamilche) Date: 9 Jun 2004 20:35:19 -0700 Subject: Dicts 5x Faster than Sets References: <889cbba0.0406091124.4c29126e@posting.google.com> Message-ID: <889cbba0.0406091935.3a60c74c@posting.google.com> David Wilson wrote in message news:... > Which version of Python did you test this on? 2.3.4 From ville at spammers.com Tue Jun 29 11:54:56 2004 From: ville at spammers.com (Ville Vainio) Date: 29 Jun 2004 18:54:56 +0300 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: >>>>> "Jacek" == Jacek Generowicz writes: Jacek> http://www.scsh.net/ Yes, scsh appears to be doing the same thing as ipython now (though ipython doesn't yet do job control or other "lower level" stuff). However, it *is* in Scheme, which kinda muddens the integration / universality / user acceptance aspects ;-). Still, scsh appears is a good place to look for further development, especially as far as process control/redirection goes. -- Ville Vainio http://tinyurl.com/2prnb From alex-news-deleteme at comcast.net Tue Jun 8 15:00:41 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 08 Jun 2004 19:00:41 GMT Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> <95aa1afa.0406072141.78f0fedd@posting.google.com> Message-ID: Thanks everybody. I now have a complete understanding of all the issues. Alex "Michele Simionato" wrote in message news:95aa1afa.0406072141.78f0fedd at posting.google.com... > Alexander Schmolck wrote in message news:... > > Not quite. In fact in the language that more or less started it all, scheme, > > the standard iteration construct 'do' does indeed introduce a *new binding* on > > each iteration. > > > Common Lisp OTOH doesn't -- like python: > > > > > A thoughtful discussion of Python/Scheme/Lisp closures and for loops > was made by > Jacek Generowicz in this thread: > > http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&oe=UTF-8&threadm=tyfsmgtbewl.fsf%40lxplus030.cern.ch&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DUTF- 8%26oe%3DUTF-8%26q%3Dsimionato%2Blambda%26btnG%3DCerca%26meta%3Dgroup%253Dco mp.lang.python.* From tim.one at comcast.net Fri Jun 11 18:09:32 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 18:09:32 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: Message-ID: [David MacQuigg, trying to keep track of how many instances of a class currently exist] ... > Seems like we could do this more easily with a function that lists > instances, like __subclasses__() does with subclasses. This doesn't have > to be efficient, just reliable. So when I call cls.__instances__(), I > get a current list of all instances in the class. > > Maybe we could implement this function using weak references. If I > understand the problem with weak references, we could have a > WeakValueDictionary with references to objects that actually have a > refcount of zero. Not in CPython today (and in the presence of cycles, the refcount on an object isn't related to whether it's garbage). > There may be too many entries in the dictionary, but never too few. Right! > In that case, maybe I could just loop over every item in > my WeakValueDictionary, and ignore any with a refcount of zero. > > def _getInstances(cls): > d1 = cls.__dict__.get('_instances' , {}) > d2 = {} > for key in d1: > if sys.getrefcount(d1[key]) > 0: > d2[key] = d1[key] > return d2 > _getInstances = staticmethod(_getInstances) > > I'm making some assumptions here that may not be valid, like > sys.getrefcount() for a particular object really will be zero immediately > after all normal references to it are gone. i.e. we don't have any > temporary "out-of-sync" problems like with the weak references > themselves. > > Does this seem like a safe strategy? An implementation of Python that doesn't base its garbage collection strategy on reference counting won't *have* a getrefcount() function, so if you're trying to guard against Python switching gc strategies, this is a non-starter (it solves the problem for, and only for, implementations of Python that don't have the problem to begin with ). Note that CPython's getrefcount() can't return 0 (see the docs). Maybe comparing against 1 would capture your intent. Note this part of the weakref docs: NOTE: Caution: Because a WeakValueDictionary is built on top of a Python dictionary, it must not change size when iterating over it. This can be difficult to ensure for a WeakValueDictionary because actions performed by the program during iteration may cause items in the dictionary to vanish "by magic" (as a side effect of garbage collection). If you have threads too, it can be worse than just that. Bottom line: if you want semantics that depend on the implementation using refcounts, you can't worm around that. Refcounts are the only way to know "right away" when an object has become trash, and even that doesn't work in the presence of cycles. Short of that, you can settle for an upper bound on the # of objects "really still alive" across implementations by using weak dicts, and you can increase the likely precision of that upper bound by forcing a run of garbage collection immediately before asking for the number. In the absence of cycles, none of that is necessary in CPython today (or likely ever). Using a "decrement count in a __del__" approach isn't better: only a reference-counting based implementation can guarantee to trigger __del__ methods as soon as an object (not involved in a cycle) becomes unreachable. Under any other implementation, you'll still just get an upper bound. Note that all garbage collection methods are approximations to true lifetimes anyway. Even refcounting in the absence of cycles: just because the refcount on an object is 10 doesn't mean that any of the 10 ways to reach the object *will* get used again. An object may in reality be dead as a doorknob no matter how high its refcount. Refcounting is a conservative approximation too (it can call things "live" that will in fact never be used again, but won't call things "dead" that will in fact be used again). From skru at ptc.ru Fri Jun 11 10:44:23 2004 From: skru at ptc.ru (Sergey Krushinsky) Date: Fri, 11 Jun 2004 18:44:23 +0400 Subject: Anonymous file closing In-Reply-To: References: Message-ID: <40C9C547.9000204@ptc.ru> Duncan Booth wrote: >Yes it is closed, but it isn't well defined as to exactly when it is >closed. You can safely assume that the file will be closed sometime between >the read returning and your program exiting. > Is it also true when file object exists inside a function? Like: def a(): text = open(filename, 'r').read() ... ... It would be natural if the file object's memory were freed after a() completion. Sergey From martin at v.loewis.de Mon Jun 7 01:58:56 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jun 2004 07:58:56 +0200 Subject: bogus OverflowError: python bug? In-Reply-To: <40C3D7DF.8010504@xplantechnology.com> References: <40C3D7DF.8010504@xplantechnology.com> Message-ID: <40c40420$0$27048$9b622d9e@news.freenet.de> Luke wrote: > I'm getting an OverflowError which doesn't make sense to me. Is this a > python bug? I very much doubt this. More likely, it's an omniORB bug. > Surely that line of source code shouldn't be able to produce an > OverflowError? It actually might. If the internal memory of the interpreter got corrupted by a buggy extension module, any code may cause any exception. > (BTW, I know that a traceback can sometimes print the wrong source line > when > the .py file has been modified since importing the module into the python > process, but I was careful to avoid this problem). There are other possible causes for bogus exceptions. A common one is that Python set an exception at some point, but the extension module forgot to forward the exception. Then, the next time Python checks for exceptions, it sees that there still is an exception pending, and raises it. That exception will make no sense that that point, of course. Only a gdb session can tell what really happened. Regards, Martin From fnord at u.washington.edu Wed Jun 16 17:22:33 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 16 Jun 2004 14:22:33 -0700 Subject: Secure File Transfer References: Message-ID: Check out twisted.conch (www.twistedmatrix.com) Even if you're determined to reinvent a wheel (I understand, it's fun sometimes), you might find twisted more useful than SocketServer. Glauco <00515879256 at fastwebnet.it> wrote in message news:... > hi to all, > i'm planning to make a way to transfer file with python. > I would like to make the transfer using some crypto api, > to make the channel secure. > i don't want to write a wrapper to ftp or to scp i just > want to make a new protocol, for a little application. > > i took a quick look to some cryptographic modules available > in python (expecially pycrypto, gnupginterface, m2crypto) > and i'm now stuck on which one of these to choose. > > Here's what i have in my mind: Alice wants to upload/download > some files from Bob. > Both of them have the public key (made with gpg), so in the > handshaking for the shared key is done using gpg. > > After that the shared key is know to both the end of the channel > and they can use it to send the data. > > i don't know what protocol (AES 3DES Blowfish? ) to use for the > transfer and i don't know if it could be better to implement > it directly with DSA/RSA rather than using GPG + somesymmetricprotocol > > any suggestion hints example ? > Someone tried something like that ? > > i'm using SocketServer for the network stuff so i would like to find > something wich can better suit with it > > > Many thanks for all the suggestion you can give me . > > > Samuele From irmen at -nospam-remove-this-xs4all.nl Sun Jun 6 17:07:57 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 06 Jun 2004 23:07:57 +0200 Subject: Storing files in a BLOB field via SQL In-Reply-To: <5a2071a0.0406061231.59c3bede@posting.google.com> References: <5a2071a0.0406061231.59c3bede@posting.google.com> Message-ID: <40c387ad$0$15440$e4fe514c@news.xs4all.nl> Juergen Gerner wrote: > field. It is planned to split large files in 64k-parts and sort these > parts by the ORDER field. Is there a special reason why you can't store the whole file in a single BLOB? That's what it's a BLOB for, after all... L=Large :-) > Additionally, I want to compress the data and store a checksum > somewhere. Any hint (links, sites, ...) is welcome...! Compress: look at the zlib module (gzip-style compression) Checksum: what kind? 32 bit-crc: zlib.crc32 md5: md5.md5 --Irmen From peter at engcorp.com Tue Jun 1 09:47:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 01 Jun 2004 09:47:34 -0400 Subject: Converting Hex to decimal In-Reply-To: References: Message-ID: dean wrote: > I have a file containing hex data. What does the term "hex data" mean to you? Does it mean binary? Does it mean that there are only characters in the range 0-9A-F and that each pair of characters represents a single byte? Something else? It is not a term with a precisely defined meaning. > I would like to convert the > contents of the file to decimal by reading each by sequentially (one > byte at the time). Is there a module that has such functionality or > does someone have the relevant code? Definitely Python can do it, possibly with the struct module, but it all depends on what "hex data" means. Do you have an example of what input will translate to what output? -Peter From akuchlin at acm.org Thu Jun 17 01:43:18 2004 From: akuchlin at acm.org (akuchlin at acm.org) Date: Thu, 17 Jun 2004 05:43:18 GMT Subject: So sieht die Wahrheit aus! Message-ID: <1a1ba8db24be4f.d6e28.qmail@acm.org> Lese und sehe selbst: http://www.freier-widerstand.net/+/hoexter/informatives.htm From eaw at connact.com Fri Jun 18 21:07:43 2004 From: eaw at connact.com (Eric Woudenberg) Date: 18 Jun 2004 18:07:43 -0700 Subject: Python 2.3.4 hangs when run from modern cygwin/bash in WinXP, but is otherwise fine Message-ID: <67032014.0406181707.2822aa03@posting.google.com> I just installed a Python 2.3.4 Windows binary on a friend's WinXP machine (because the latest Cygwin-provided Python 2.3 build leaves out the winsound module for some reason). When I try and run this newly installed Python from bash it just hangs (no version message, no prompt, CPU is idle). When I run it from IDLE, or the DOS CMD prompt, it runs fine. Also, Python scripts using the new version run fine, even invoked on the bash command line. It seems there's some problem with terminal i/o when invoked from bash. However, using this same installer, Python 2.3.4 runs fine on my WinXP machine (though mine is using an older version of cygwin). Meanwhile, his cygwin-provided Python 2.3 runs fine from bash. I haven't been able to figure out what's wrong. Does anyone have any suggestions? Thanks kindly in advance! Eric Woudenberg From donn at drizzle.com Thu Jun 10 02:46:40 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 10 Jun 2004 06:46:40 -0000 Subject: does python have useless destructors? References: Message-ID: <1086849997.970041@yasure> Quoth "Michael P. Soulier" : ... | However, consider the code... | | myfile = open("myfilepath", "w") | myfile.write(reallybigbuffer) | myfile.close() | | If the write fails due to a lack of disk space, the exception will | prevent the explicit close() from happening. Now, if myfile goes out of | scope, I would hope that the file object is destroyed and thus the file | is closed, but after reading the python documentation, it seems that | the only way to guarantee closure of the file is using the mentioned | try/finally construct... | | try: | myfile = open("myfilepath", "w") | myfile.write(reallybigbuffer) | finally: | myfile.close() I think here we're talking about the problem where an exception takes a reference to local variables. The other solution, a bit of a hack but it could be more convenient depending on your application, is to release the traceback (sys.exc_traceback = None) in the handler. Donn Cave, donn at drizzle.com From jjl at pobox.com Wed Jun 30 16:10:53 2004 From: jjl at pobox.com (John J. Lee) Date: 30 Jun 2004 21:10:53 +0100 Subject: Using Python with SyBase References: <40dbbf6b$0$16984$79c14f64@nan-newsreader-04.noos.net> Message-ID: <87smcchkmq.fsf@pobox.com> "Tomasz" writes: [...] > front-end screens in text mode. Python gives me a good fealling for that it > seams it is what I am looking for. I am bit afreraid for stability of Python > and for speed relaibility (it is just an interpreter only). [...] Pythons, though bulky, are apparently quite fast *enough* to swallow large mammals in one piece, so I don't blame you for being afraid . John From jacek.generowicz at cern.ch Wed Jun 9 03:48:42 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Jun 2004 09:48:42 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> Message-ID: Skip Montanaro writes: > Right. Like Terry said, for anything more substantial use a named function. > Lambda was never intended to be a replacement for def, and Python is > fundamentally not a functional language (in the Haskell/Lisp sense of the > term), so powerful anonymous functions are generally not needed. I wish people would stop making such self-fulfilling prophecies. You[*] don't use fully general anonymous closures, because the languages you use do not provide you that tool. Because such beasts, do not form part of your normal programming arsenal, you don't use them. Because you don't use them, you rarely see them used. Because you rarely see them used, you conclude that they are not needed. You you make the mistake of confusing your lack of imagination with some inherent quality of the language in question. The fact is that people who are used to using powerful programming techinques which you may not use yourself, _do_ miss their presence in languages in which you consider their absence to be a feature. Python has many qualities, but let's stop kidding ourselves that its current state is some sort of global optimum in the space of programming languages. In spite of its many qualities, Python has a number of shortcomings. Let's stop kidding ourselves that its shorcomings are features. Python's naff support for anonymous closures is a shortcoming, not a feature. [*] By "you" I mean "one", not "Skip Montanaro". From piet at cs.uu.nl Wed Jun 2 07:52:59 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 02 Jun 2004 07:52:59 -0400 Subject: 2d lists References: <337e6cd5.0405291411.4376debc@posting.google.com> Message-ID: >>>>> xiaohua_sun at yahoo.com (SunX) (S) wrote: S> What is the best way to assign a 2d lists? Something like; S> for i in range(10): S> for j in range(10): S> aList[i][j] = i*j S> Thank you in advance. Use list comprehension: aList = [[i*j for j in range(10)] for i in range(10)] -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From pinard at iro.umontreal.ca Mon Jun 28 23:08:56 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 28 Jun 2004 23:08:56 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: <40E0C8EA.20305@rogers.com> References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <40E0C8EA.20305@rogers.com> Message-ID: <20040629030856.GA12214@titan.progiciels-bpi.ca> [Mike C. Fletcher] > Fran?ois Pinard wrote: > >[Mike C. Fletcher] Hi, Mike, and people! > But the implication of what you just advocated is that the community > (which consists of both libre and non-libre developers) *must* develop > two different versions of the software. In other words, they *must* > duplicate the effort of development. They only *must* if they do not want to accept the GPL. That's the price tag of not being part of that particular free software gang. People are not forced to use GPL'ed programs, but GPL programs are not forced either to be available for everybody at no condition. I once had to work on projects which the customer did not want GPL'ed, and it was part of the discussions with my customer that it would have to pay for the non-free re-implementation of already available tools. There, being non-free costed money (and freedom). That's a choice. > To some extent, sure, and for some project areas. But there are > lots of cases where people look at the GPL requirements and say "no, > I have to re-implement that"... it's that waste that bothers me. The waste comes from the refusal of the GPL. The same as there is some waste when GNU mandates the re-implementation of already existing projects so to make them "free" as it wants to define "free". From the outsider that I am, it sometimes look like big debates over tiny nits. > The simple fact is that there are groups doing proprietary software. > For them the GPL simply isn't a choice. OK, granted. There is a price to that choice in wasted time, or money. > The LGPL was developed precisely because there are lots of situations > where that assumption just isn't true, and it's more valuable to > get the contributions of everyone to the library than to force the > bifurcation of libraries. The LGPL was an experiment from the FSF. After a few years, the FSF decided that the experiment failed, and that the LGPL was not to be used anymore, at least within the GNU project. > [...] the BSD/MIT software tends to treat the end-developer as an > adult, rather than a recalcitrant child. [...] If you like [the GPL], > feel free to continue liking it ;) . As I mentioned, I prefer the BSD > licensing scheme. I'm not fanatic about the GPL. But I think it made good things happen in the realm of planetary software, and so, has some virtues. Each license wants to be re-quoted all over the place, and would it be only because of that, they all are irritating. The BSD license was a bit verbose about Berkeley (this might have changed, I did not check lately), but I surely rewrote a few modules in `tar' and `cpio' to get rid of the long blurb, when I was maintaining these, a good while ago. > And just to clarify, the GPL isn't a reminder, it's an attempt to > *force* give-and-take. The question is whether you feel the need to > impose your desires, or whether you rely on people's better nature. Vern Paxson, the Flex author, did not want the GPL in Flex, but the BSD license instead, and has been very careful to avoid any usual library routine in Flex for that reason (like `getopt' and `gettext', to name a few). We once were arguing licenses over a meal, and he got me laughing to tears by saying: "I do not want to be forced to be free!". > The GPL represents an attempt to enforce maturity on others, while the > Python, BSD and MIT licenses assume the maturity of the audience. I contributed to the GPL in the past as a way to recognise and be thankful for all the GPL brought to me, and I've probably given back my share by now. But that's not a religion, and I'm not much in politics. I'd be happy to try the Python license one of these days, if the opportunity arises :-). I'm surely indebted toward the Python community by now! :-) Deep down, any reasonably free license would do... > And that, I think, is where I will stop, as we're obviously a good > little way from discussing Python any more, and this debate really > can't reach any sort of conclusion. OK, so should I. Keep happy! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From irmen at -nospam-remove-this-xs4all.nl Tue Jun 22 16:02:47 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 22 Jun 2004 22:02:47 +0200 Subject: Optional use of logging library module In-Reply-To: References: Message-ID: <40d89066$0$65124$e4fe514c@news.xs4all.nl> Eric DeWall wrote: > User of the class passes in a Logger object they have already set up with > handlers, etc., class simply calls log methods on the logger when > appropriate. But I can't find a way to create a good "null" logging object > that the class can use by default if no Logger is passed in. I'd like a > simple approach that doesn't involve extending the existing logging library. Try the 'null' object design pattern: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 --Irmen From danb_83 at yahoo.com Wed Jun 30 04:08:57 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 30 Jun 2004 01:08:57 -0700 Subject: Any list larger than any number by way of dimensions? References: Message-ID: Harald Massa wrote in message news:... > Peter, > > > data = [ ... some list ] > > buffersize = min(data,10) > > > > Of course what I really wanted was > > > > buffersize = min(len(data),10) > > if my memory suits me right, when everything else fails, Python is just > comparing the IDs of the objects. IDs are connected to the memory > addresses. That's true for user-defined objects, but for built-in types the rule is None < number < list < string < tuple Which is consistent but wrong. From manatlan at online.fr Fri Jun 11 18:38:00 2004 From: manatlan at online.fr (marco) Date: Sat, 12 Jun 2004 00:38:00 +0200 Subject: dynamic import with heritage In-Reply-To: <40c9fd29$0$41756$5fc3050@dreader2.news.tiscali.nl> References: <40c8d0d0$0$26780$636a15ce@news.free.fr> <40c9c54e$0$26793$626a14ce@news.free.fr> <40c9ce46$0$41748$5fc3050@dreader2.news.tiscali.nl> <40c9d17b$0$26811$626a14ce@news.free.fr> <40c9fd29$0$41756$5fc3050@dreader2.news.tiscali.nl> Message-ID: <40ca3449$0$26796$626a14ce@news.free.fr> Gr?goire Dooms a ?crit : > marco wrote: > >> Gr?goire Dooms a ?crit : >> >>> marco wrote: >>> >>>> Gr?goire Dooms a ?crit : >>>> >>>>> In your dhuile package, you need bidon in your namespace. >>>>> This can be done by importing the module containing bidon's >>>>> definition. >>>>> According to what you say ("here my main"), this module is __main__ . >>>>> >>>>> So a simple >>>>> from __main__ import bidon >>>>> class vidange(bidon): >>>>> pass >>>>> should do the job. >>>>> >>>> >>>> your statement doesn't work >>>> but it works, if i do : >>>> ------------------------- >>>> import sys >>>> sys.path.append("../..") >>>> from main import bidon >>> >>> >>> >>> >>>> ------------------------- >>>> >>>> does it exists a way to do it easier ? (i don't like this technick >>>> to append a path to sys.path) >>>> >>> >>> I wrote >>> from __main__ import bidon >>> Not >>> from main import bidon >> >> >> >> if i wrote : >> "from __main__ import bidon" >> >> i've go an "ImportError: Cannot re-init internal module __main__" >> ?!? > > > I think this should only happen if '__main__' is not in sys.modules. > Could you check that '__main__' is indeed missing in sys.modules ? > > import sys > if '__main__' in sys.modules: > from __main__ import bidon > else: > print 'Something strange happened here' > > Interresting... no ;-( it seems that "__main__" is in sys.modules but when it try the "from __main__ import bidon" it makes a : "ImportError: Cannot re-init internal module __main__" where can i find doc about this technick ? > -- > Gr?goire Dooms From novastaylor at hotmail.com Wed Jun 16 17:06:10 2004 From: novastaylor at hotmail.com (Nova's Taylor) Date: 16 Jun 2004 14:06:10 -0700 Subject: Parse ASCII log ; sort and keep most recent entries Message-ID: Hi folks, I am a newbie to Python and am hoping that someone can get me started on a log parser that I am trying to write. The log is an ASCII file that contains a process identifier (PID), username, date, and time field like this: 1234 williamstim 01AUG03 7:44:31 2348 williamstim 02AUG03 14:11:20 23 jonesjimbo 07AUG03 15:25:00 2348 williamstim 17AUG03 9:13:55 748 jonesjimbo 13OCT03 14:10:05 23 jonesjimbo 14OCT03 23:01:23 748 jonesjimbo 14OCT03 23:59:59 I want to read in and sort the file so the new list only contains only the most the most recent PID (PIDS get reused often). In my example, the new list would be: 1234 williamstim 01AUG03 7:44:31 2348 williamstim 17AUG03 9:13:55 23 jonesjimbo 14OCT03 23:01:23 748 jonesjimbo 14OCT03 23:59:59 So I need to sort by PID and date + time,then keep the most recent. Any help would be appreciated! Taylor NovasTaylor at hotmail.com From andymac at bullseye.apana.org.au Sat Jun 19 17:55:26 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 20 Jun 2004 07:55:26 +1000 (EST) Subject: shared file access in python In-Reply-To: <9418be08.0406180620.3e64be96@posting.google.com> References: <9418be08.0406180620.3e64be96@posting.google.com> Message-ID: <20040620075332.S70177@bullseye.apana.org.au> On Sat, 18 Jun 2004, Lev Elblert wrote: > Does Python allow to open files in shared mode like fsopen or _open > do? If not how to make it happen? Assuming you're on a Win32 platform, I think the msvcrt module has what you're looking for. The standard file object supports only the standard C library file stream API. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From j_mckitrick at bigfoot.com Sun Jun 13 16:16:16 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 13 Jun 2004 13:16:16 -0700 Subject: Code density Message-ID: When I was reading the PEP for code, Guido suggests using blank lines 'sparingly.' Yet, in most of the 'professional' code(1) I've seen, there are often HUGE amounts of whitespace, extra blank lines, and so on. Is this the norm? Has python gravitated toward more whitespace in general? jonathon (1) Zope, RocksClusters, anaconda, and others From peter at engcorp.com Mon Jun 21 10:26:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 10:26:35 -0400 Subject: sys.stdout.write() question In-Reply-To: References: Message-ID: Gian Mario Tagliaretti wrote: > It is (I hope) a simple question, > I cannot figure out why sys.stdout.write() doesn't print immediatly the first > text in the small example below, but before it process the code in between > and then print both lines in one time. sys.stdout.flush(). Flush on a file object pushes out all the data that has been buffered to that point. -Peter From aweil at mail.ru Mon Jun 28 23:43:19 2004 From: aweil at mail.ru (alejandro david weil) Date: Tue, 29 Jun 2004 00:43:19 -0300 Subject: Speed of str(positive_integer).. In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13064C02AE@its-xchg4.massey.ac.nz> References: <1ED4ECF91CDED24C8D012BCF2B034F13064C02AE@its-xchg4.massey.ac.nz> Message-ID: <200406290042.39462.aweil@mail.ru> On Mon June 28 2004 23:41, Tony Meyer wrote: > > > For small numbers your one beats it because > > > you don't have to do all the other work that str() does (negatives, > > > non-integers, etc), but as the > > Yes. But negatives represents not much more work. > Enough that it makes a difference when the task is so small, though. Yes. it's possible. :-( > > I should check, when have some time, how is str() implemented. > I believe the CPython implementation uses sprintf, so that doesn't really > help much. Yes.. using asciiz buffer and dividing in asm. should be imposible to match for us in python.. > > > "r = b//c;q = b-r*c" (or "r = b//c;q=b%c", which is better) > > (I'm not sure that that is better but i think that it > > should (at least, in assembler (and for integers))) > By better I meant that it was faster (here, anyway), and clearer (to me, > anyway). I thought that multiply and substract was faster than taking module. But it seems to be not true in python :-( > > > (with Python 2.3.4). I suppose this is the penalty for the > > > additional work that divmod does with checking signs and so on. > > I'm unsure of how many more things has to do divmod. > Looking at the implementation in floatobject.c would tell you. There are > various things it does to make sure that signs come out correctly. Then, I were wrong :-) > > Anyway, if it's implemented in C it couldn't (i think) use > > the div from assembler that leaves quotient and remainder on > > different registers. I mean, it should be specially implemented. :-( > I suppose that the divmod implementation could check to see if both numbers > were integers and then do the faster integer case. You'd have to convince > TPTB that the speed increase was worth it and that the overhead of doing > the test didn't outweigh the benefits, though. What's TPTB? Perhaps a: 4.divmod() only needs to check that one number is an integer :-) > > Btw, why you didn't answer in the list? > I did. Cool, thanks I didn't saw that. Seeya alejandro -- + There is no dark side of the moon really. Matter of fact it's all dark. From nc-jantzegu at netcologne.de Sun Jun 6 19:21:21 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Mon, 7 Jun 2004 01:21:21 +0200 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> Message-ID: "Michael Hudson" writes > I wonder why people independently start thinking of the same crazy > things at the same time? Maybe because clever people solve the problems which are in front of them - 'Let us first solve the problems which are in front of us' Michael Hudson at PyPy sprint 2003 in Lovain-La-Neuve From jimka at rdrop.com Mon Jun 7 16:20:01 2004 From: jimka at rdrop.com (Jim Newton) Date: Mon, 07 Jun 2004 22:20:01 +0200 Subject: if does not evaluate In-Reply-To: References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: <2ik471Fntu3aU2@uni-berlin.de> this suggestion does not work because expr2 evaluates even if expr1 is TRUE. Tor Iver Wilhelmsen wrote: > Jim Newton writes: > > >>I.e., x = if something: >> expr1 >> else: >> expr2 > > > Try exploiting that a boolean expression evaluates to 0 or 1: > > x = (expr1, expr2)[something]; > > Keep in mind that this might break on some later release of Python if > they decide to make boolean its own type, but at least it works for > 2.3.3. From claudio.grondi at freenet.de Tue Jun 15 20:16:24 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 16 Jun 2004 00:16:24 -0000 Subject: How to get decimal form of largest known prime? References: Message-ID: <2j9atlFv6l0iU1@uni-berlin.de> >> [Tim Peters] >> The fastest pure-Python solution I've found consumed about 20 CPU minutes >> Sorry, I really can't make time to review unfamiliar code today. Instead >> I'll just show the code I used. Thank you _very much_ for the code and for all your postings - it was a challenge for me as Python newbie to understand it, but I learned from it much about Python syntax. (by the way: my machine needs about 25 CPU minutes) I still haven't got any clear idea why your code runs so much faster than mine, but I see, that you are using shifting and own algorithm for pow(), so that's probably the core of the improvement (I haven't used shifting and pow(), only standard Python multiplication without any special algorithms behind). As it is often the case, the more I know, the more questions comes up, as e.g. why there is probably no common base-independent algorithm for binary -> decimal conversion, or what is the amount of information in knowing the largest prime? Is it 2**24036583-1 i.e. around 13 byte, or about 3 MByte after maximum compression ratio which can be reached on the decimal representation, or these small amount of bytes after compressing the hexadecimal representation? To stay on-topic: I did some work rewriting your code and provide here code of a bigDecReprOfInt class as a kind of module and stand-alone app in one. You can print the largest prime with it (setting False to True) and perform timing comparisons (see comments within the code for details). ***** REPLY to following question will be welcome: ***** What I can't understand is, why if I write in __main__() e.g. : bigDecimal = bigDecReprOfInt([2],80)**intExponentToTest the bigDecimal "digits" still remain as defined in def __init__(self, lstOfDigits, intNoOfDecimalDigitsInOneBigDigit = 4096): i.e. 4096 and not as I would expect it 80 decimal digits long Haven't I proper understood how to set/overwrite default values of function parameters? Makes it a difference if it is a function defined within a class or stand-alone? Have I faced a bug? ***** REPLY to question above will be welcome: ***** Now knowing you [Tim Peters] as a Python and programming expert, may I ask you even for more support by providing a reply to my other posting to this newsgroup: "Python Scripting in Windows MSIE 6.0"? Is there an easy way to activate and use it in Python 2.3.4? I know, that there are much work-arounds possible, but I would just prefere to write the Python within the tags within the HTML page using it as a kind of GUI to Python code. Claudio P.S. here the code for use by everyone interested in the topic of this discussion path: class bigDecReprOfInt(object): """ "/*(UEdit) # The primary purpose of the class bigDecReprOfInt is speeding up of '%i'%i # and str(i) conversion for very large integers i. # Example of a task where the advantage from usage of bigDecReprOfInt class # for conversion of a large integer to string (using decimal form) becomes # apparent, is printing all digits of the largest known (May 2004) prime # 2**24036583-1 # It can be done using # # "print '%i'%(2**24036583-1,)" # # but it takes time in order of hours of busy CPU. Interesting is here, that # printing the hexadecimal form of same prime using # # "print '%X'%(2**24036583-1,)" # # takes only seconds. # Usage of the bigDecReprOfInt class to do the job: # # bigDecimal = bigDecReprOfInt([2])**24036583 # bigDecimal.digits[0] -= 1 # print bigDecimal # # cuts the CPU time down to less than half an hour. # # Generally: # comp.lang.python, Tim Peters June 13, 2004 16:35 : # "The asymptotic complexity of the elementary arithmetic operations # (+, -, *, /, integer power) is independent of base. ", but practical # comp.lang.python, Tim Peters June 10, 2004 23:56 : # "binary -> hex conversion time increases linear with the number of bits # (Python longs are stored internally in a form of binary representation). # binary -> decimal conversion time increases quadratic with the number # of bits, therefore it is a very slow process for large numbers." # The principle: # The core of the idea behind the approches to lower the CPU time necessary # for printing is to avoid binary -> hex conversion of very large integers # applying this conversion only to smaller ones, with low conversion time. # The specific approach choosen for this class: # Because the large integer must be splitted into smaller integers # representing a given range of decimal digits of the integer before # printing, this job can be done already while the large integer is # created (using * or ** operators). # This class inherited from class 'object' overwrites the __init__(), # __imul__(), __mul__(), __pow__() and __str__() methods of 'object' # exposing this way own * and ** operators and conversion to string. # The code of this class is based on code of the BigDec class # provided by "Tim Peters" in his contribution to # newsgroup comp.lang.python (python-list at python.org) June 13, 2004 21:49. # Packing all of the for BigDec necesarry code to one class and writing # of introductory information and __main__() was done by "Claudio Grondi" # June 15, 2004 " """ #(UEdit)*/ def __init__(self, lstOfDigits, intNoOfDecimalDigitsInOneBigDigit = 4096): # digits is a list of base-BASE digits, least-significant first. self.digits = lstOfDigits self.EXP = intNoOfDecimalDigitsInOneBigDigit self.BASE = (5L ** self.EXP) << self.EXP # == 10**EXP #:def __init__(self, digits): def __mul__(self, other): # Force 'other' to have the fewer # of digits. if len(self.digits) < len(other.digits): self, other = other, self # Straightforward cross-product. Don't worry about digits # getting out of range for the duration. result = [0] * (len(self.digits) + len(other.digits) - 1) for baseindex, otherdigit in enumerate(other.digits): for i, selfdigit in enumerate(self.digits): result[baseindex + i] += selfdigit * otherdigit #:for #:for self.normalize(result) return bigDecReprOfInt(result) #:def __mul__(self, other): __imul__ = __mul__ def __pow__(self, intExponent): # "The usual" left-to-right efficient exponentiation algorithm, but # intExponent must be here of type integer, not bigDecReprOfInt. mask = 1L while mask <= intExponent: mask <<= 1 #:while mask: mask >>= 1 # position of intExponent's most-significant bit result = bigDecReprOfInt([1]) while mask: result = result.square() if intExponent & mask: result *= self #:if mask >>= 1 #:while mask: return result #:def __pow__(self, intExponent): def square(self): # Efficient divide-and-conquer squaring, based on # (a*x+b)**2 = a**2*x**2 + 2*a*b*x + b**2 : intNoOfDigits = len(self.digits) if intNoOfDigits <= 5: return self * self #:intNoOfDigits <= 5: RETURN intSplitAt = intNoOfDigits // 2 lo, hi = \ bigDecReprOfInt(self.digits[:intSplitAt]) \ , bigDecReprOfInt(self.digits[intSplitAt:]) result = lo.square().digits result += [0]*(2*intSplitAt - len(result)) # list multiplication result += hi.square().digits for intDigit in (lo * hi).digits: result[intSplitAt] += intDigit << 1 intSplitAt += 1 #:for self.normalize(result) return bigDecReprOfInt(result) #: def square(self): def __str__(self): result = map(str, self.digits) # Pad all digits except for the MSD with leading zeroes. for i in xrange(len(result) - 1): digit = result[i] if(len(digit) < self.EXP): result[i] = "0"*(self.EXP - len(digit)) + digit #:if #:for result.reverse() return "".join(result) #:def __str__(self): def normalize(self, lstOfDigits): # Force the digits in self.digits into range(BASE), by propagating carries. # Function has no return value - self.digits is modified in-place. intCarry = 0 # first loop over all of the existing digits ... for intIndexOfDigitInListOfDigits, intValueOfDigitInListOfDigits in enumerate(lstOfDigits): intCarry += intValueOfDigitInListOfDigits intCarry, lstOfDigits[intIndexOfDigitInListOfDigits] = divmod(intCarry, self.BASE) # ... then loop as long as it is necessary to append leading digits and ... while(intCarry >= self.BASE): intCarry, leftover = divmod(intCarry, self.BASE) lstOfDigits.append(leftover) # ... check if it necessary to append a last leading digit and ... if intCarry: lstOfDigits.append(intCarry) #:if intCarry: # strip leading zeroes ( 0 digits ): while lstOfDigits and lstOfDigits[-1] == 0: lstOfDigits.pop() #:while #:normalize(lstOfDigits) #:class bigDecReprOfInt(object) if __name__ == '__main__': # For getting decimal form of currently(May 2004) largest known prime # i.e. 2**24036583-1 set blnPrintLargestKnownPrime to true: blnPrintLargestKnownPrime = False # True if(not blnPrintLargestKnownPrime): intExponentToTest = 500000 else: intExponentToTest = 24036583 #:if/else fileFOut = open('bigDecReprOfInt.out','w') import time print print ' ============================================================================ === ' print ' -------------------------------------------------------------------------- ----- ' print print ' *** Usage of bigDecReprOfInt class for fast prints of large integers ***' print print ' Print of first ... last 77 digits of 2**%i: '%(intExponentToTest,) floatBegTime_bigDecimal = time.clock() bigDecimal = bigDecReprOfInt([2])**intExponentToTest if(blnPrintLargestKnownPrime): # bigDecReprOfInt does not(yet) support + and - operators and we want to # subtract one(1), so let it do in a generalized way: assert bigDecimal.digits[0] != 0 # i.e. subtract one(1) only if last digit is non-zero (is the case here): bigDecimal.digits[0] -= 1 #:if strDecimal = str(bigDecimal) floatEndTime_bigDecimal = time.clock() print ' ' + strDecimal[0:77] print ' ' + '...' print ' ' + strDecimal[-77:] if(intExponentToTest <= 500000): print ' -------- started calculating of strDecimal = str(2**%i)'%intExponentToTest floatBegTime_stdDecimal = time.clock() strDecimal = str(2**intExponentToTest) floatEndTime_stdDecimal = time.clock() print ' ' + strDecimal[0:77] print ' ' + '...' print ' ' + strDecimal[-77:] print ' str(bigDecReprOfInt([2])**%i) is %4.2f times faster than str(2**%i)'%( \ intExponentToTest, (floatEndTime_stdDecimal - floatBegTime_stdDecimal) \ / (floatEndTime_bigDecimal - floatBegTime_bigDecimal), intExponentToTest \ ) # On Pentium III, 900 MHz : # str(bigDecReprOfInt([2])**500000) is 7.81 times faster than str(2**500000) else: print print ' --------- skipping str(2**EXP) for EXP > 500000 ---------' print print \ ' runtime of str(bigDecReprOfInt([2])**%i) is %6.2f minutes'%( \ intExponentToTest, \ (floatEndTime_bigDecimal - floatBegTime_bigDecimal)/60 \ ) #:if/else fileFOut.write(strDecimal) print print ' See "bigDecReprOfInt.out" in curr. dir for value of 2**%i'%(intExponentToTest,) print fileFOut.close() # print # TEST # print bigDecimal.digits[0] # TEST print print ' Print of first ... last 77 digits of (2**24036583-1) in hexadecimal form: ' floatBegTime_bigHexadecimal = time.clock() strDecimal = '%X'%(2**24036583-1) floatEndTime_bigHexadecimal = time.clock() print ' ' + strDecimal[0:77] print ' ' + '...' print ' ' + strDecimal[-77:] print \ ' runtime of strDecimal = \'%%X\'%%(2**24036583-1) is %6.4f sec'%( \ (floatEndTime_bigDecimal - floatBegTime_bigDecimal), \ ) print print ' -------------------------------------------------------------------------- ----- ' print ' ============================================================================ === ' raw_input('exit with ENTER: #\> ') #:if __name__ == '__main__' From look at in.signature Sun Jun 27 11:18:31 2004 From: look at in.signature (Maurizio Colucci) Date: Sun, 27 Jun 2004 15:18:31 GMT Subject: ImportError: No module named functional References: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> Message-ID: Gian Mario Tagliaretti wrote: > If "functional" is not your own module is normal, yes. But in these articles the author writes as if they were predefined modules... http://www-106.ibm.com/developerworks/linux/library/l-prog3.html Thanks! -- Best Regards, Maurizio Colucci Please remove the uppercase letters "S,P,A,M": seSgPuAsMo.forever at tin.it From lbates at swamisoft.com Wed Jun 23 10:22:42 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 23 Jun 2004 09:22:42 -0500 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: Take a look at pyCrypto. My understanding is that it provides python wrapper around C crypto functions. Can't get much faster than that. http://www.amk.ca/python/code/crypto.html HTH, Larry Bates "Kamilche" wrote in message news:889cbba0.0406221926.3f4e5776 at posting.google.com... > I've looked at a few alternatives for encryption with Python, and > didn't come up anything very speedy. > > I've written an encryption algorithm in pure Python that can process > 22 megs of data a second. I know it's not secure, but it should be > enough to ward off casual hacking. Does someone know of something > speedier? > > --Kamilche From peter at engcorp.com Tue Jun 29 14:14:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 14:14:07 -0400 Subject: embedded python? In-Reply-To: <55iEc.112810$2i5.78663@attbi_s52> References: <55iEc.112810$2i5.78663@attbi_s52> Message-ID: <4bKdnQ_0T_vyLHzdRVn-gg@powergate.ca> Alexander May wrote: > Peter Hansen recklessly declaimed(*): >>I doubt you'll need to do much "porting". Unless the Linices you >>are considering are quite unusual, they ought to look a lot like any >>other Linux, and Python may well work largely unchanged. > > from http://www.vanille.de/projects/python.spy (from Christopher T King's > post) > > "You won't find many Python distributions for arm-linux, because Python is > pretty finnicky when it comes to cross-compiling. The build process of > Python compiles a core part of it (the parser generator pgen) and tries to > execute that later in the build process. This - of course - doesn't work for > cross compiling. My patches to the Python build scripts are available @ > sourceforge and are likely to be included into the main Python tree." > > Thoughts? Yeah, my Linux experience is limited to x86 systems, and my definition of "unusual" therefore includes anything outside of that. Sorry. :-( -Peter From eddie at holyrood.ed.ac.uk Wed Jun 30 11:50:09 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 30 Jun 2004 15:50:09 +0000 (UTC) Subject: Multithreaded Telnet sessions References: <1a7605a1.0406131639.6951ca0d@posting.google.com> <55d6af0e.0406300631.6d10ed60@posting.google.com> Message-ID: birdfamily at gmail.com (Richard Bird) writes: >Anything over 20 threads seems to take processor utilization to 100%. >Is there any benefit to starting additional threads once the CPU is at >100% ? I think the only correct answer here is "suck it and see". It's going to depend on what's happening. For instance, if you issue a "write mem" command then that thread isn't going to be doing anything for a while. So there's no obvious definitive answer. Unless there are known limits to how many threads it is practical to use that others know about? Anyone? My intuition would have suggested that a modern machine could have easily handled more than 20 telnet sessions. We have less than 100 Cisco devices but I do have a config save script that I could try converting to threads, if I get time to convert it I will let you know how many threads it copes with. Eddie From shooby at gnome.hu Thu Jun 24 14:40:24 2004 From: shooby at gnome.hu (shooby at gnome.hu) Date: Thu, 24 Jun 2004 14:40:24 -0400 Subject: hi Message-ID: Requested file. -------------- next part -------------- A non-text attachment was scrubbed... Name: data.pif Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From aahz at pythoncraft.com Fri Jun 18 22:31:25 2004 From: aahz at pythoncraft.com (Aahz) Date: 18 Jun 2004 22:31:25 -0400 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: In article <2jh2glF10adr2U1 at uni-berlin.de>, Leif K-Brooks wrote: > >I'm planning to start on a fairly large web application, most likely >using mod_python. I recently wrote a fairly small (but real-world >useful) web app with it, and all of those req.write()s made for really >ugly code. Would a templating engine solve that? Does anyone have any >suggestions about which one to use? If you're already doing req.write(), it'll be easy to shift to Quixote. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From avera at coes.org.pe Wed Jun 30 15:11:57 2004 From: avera at coes.org.pe (Alberto Vera) Date: Wed, 30 Jun 2004 14:11:57 -0500 Subject: call py from py Message-ID: <000a01c45ed6$1d5134d0$1603a8c0@pc22> Hello: Could you tell me How I Can call a python program from another one? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From db3l at fitlinxx.com Mon Jun 28 19:46:15 2004 From: db3l at fitlinxx.com (David Bolen) Date: 28 Jun 2004 19:46:15 -0400 Subject: How important is Python 1.5 compatibility? References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: Erik Max Francis writes: > Based on the discussions I've seen, I'm getting the impression that this > is less and less the case as time goes on (which is, of course, exactly > how you'd expect things to be). How important is Python 1.5 > compatibility today? I probably have to answer that in two ways for myself: First, while our new development projects are holding Python 2.2 as the baseline (probably move that to 2.3 before they get released), Python code in our production deployed systems (a few thousand machines at ~500 sites) is still entirely on 1.5.2, as is our production central services for those sites - although the latter not changing is more a lack of need than the logistical hurdle that the sites represent. So I certainly still appreciate and prefer modules that are 1.5 compatible when possible. However, even with such an installed base, I don't have my head in the sand and don't necessarily expect most current packages to continue to support 1.5. At the moment, in most cases when a package that I need doesn't, I can continue to run those sites with an older version of it that did at one time support 1.5. That's probably part of the reason I haven't taken on the operational overhead of upgrading yet. So I can't say that I'm against packages enforcing a more modern minimum (that's probably 2.2 in my mind at the moment). My guess is somewhere in the next year or two I'll really want some particular package and take on the upgrade task to transition my installed base to a 2.x series. -- David From vmilitaru at sympatico.ca Wed Jun 9 08:23:39 2004 From: vmilitaru at sympatico.ca (Vio) Date: Wed, 09 Jun 2004 08:23:39 -0400 Subject: importing embedded dynamic lib Message-ID: I have a basic dynamic lib "noddy.so" which I want to 1- embed inside my executable 2- import by embedded python interpreter using an API call. I have two questions: 1- what would be the recommended technique to embed a binary file inside an executable? My guess would be to add the binary "noddy.so" to the linking command, but then how do I get access to that chunk of code in my source file? My goal would be to achieve something like int* noddy_so = ... but then how do I include the binary code, or make the source code aware of it? Using "#include" doesn't feel right, as this is a binary file, not ASCII. And loading the file at run-time isn't right either, I need to load it at compile time. And is "int*" the appropriate data type for binary data? 2- Let's imagine that I managed to load "noddy.so" into my source code somehow, and now have a pointer to it. Any hints as to the correct python API call to import a dynamic lib from a memory buffer? Could someone tell me for example if the following makes sense for my purpose? ------------------------------ char *modulename="noddy", *filename="no_real_file"; PyObject *tmp; /*Here try to translate the binary lib into a PyObject*/ tmp = Py_CompileString(noddy_so, filename, Py_file_input); if (tmp == NULL) error("Can't compile module [tmp]"); /*Import the "noddy" module*/ pmod = PyImport_ExecCodeModule(modulename, tmp); if (pmod == NULL) error("Can't load module [pmod]"); ------------------------------ Regards, Vio From roy at panix.com Mon Jun 14 08:03:12 2004 From: roy at panix.com (Roy Smith) Date: Mon, 14 Jun 2004 08:03:12 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: dkturner at telkomsa.net (David Turner) wrote: > Destruction and finalization are *different things*. For those of us not up on such things, could you explain the differences? From nhirsh2 at ieee.org Mon Jun 14 10:22:10 2004 From: nhirsh2 at ieee.org (Neale) Date: 14 Jun 2004 07:22:10 -0700 Subject: Newbie array question References: <2d7af4f8.0406112032.4cb4438a@posting.google.com> Message-ID: <2d7af4f8.0406140622.3cdcb578@posting.google.com> danb_83 at yahoo.com (Dan Bishop) wrote in message news:... > nhirsh2 at ieee.org (Neale) wrote in message news:<2d7af4f8.0406112032.4cb4438a at posting.google.com>... > > My first task with Python is to scan multiple small text files and > > "batch together" those records with a "5" or "6" in column 2, and then > > save as a new file. The records are 256 characters. I know it sounds > > like a homework problem, but it's not. > > Assuming that all your records are strings in an array called > "records", you can discard the ones without a '5' or '6' in column 2 > (column 1 in 0-based indexing) with: > > records = [r for r in records if r[1] in ('5', '6')] Thank you all for such high quality help. And fast, too! From connellybarnes at yahoo.com Fri Jun 18 01:35:38 2004 From: connellybarnes at yahoo.com (Connelly Barnes) Date: 17 Jun 2004 22:35:38 -0700 Subject: String buffer Message-ID: <32e4319c.0406172135.5b21538c@posting.google.com> Yet another useful code snippet! This StringBuffer class is a FIFO for character data. Example: B = StringBuffer('Hello W') B.append('orld!') print B.read(5) # 'Hello' print B.read() # 'World!' The append method appends a string to the end of the string buffer. The read(n) method reads and removes n characters from the beginning of the buffer. If n is omitted, it reads the entire buffer. To view the first n characters of the string buffer, use peek: print B.peek(5) # View first 5 characters Or cast as a string to get the entire contents: print str(B) # View entire buffer The append and read methods are O(k), where k is the number of characters appended or read. # ------------------------------------------------------- # StringBuffer: A FIFO for string data. # ------------------------------------------------------- class Deque: """A double-ended queue.""" def __init__(self): self.a = [] self.b = [] def push_last(self, obj): self.b.append(obj) def push_first(self, obj): self.a.append(obj) def partition(self): if len(self) > 1: self.a.reverse() all = self.a + self.b n = len(all) / 2 self.a = all[:n] self.b = all[n:] self.a.reverse() def pop_last(self): if not self.b: self.partition() try: return self.b.pop() except: return self.a.pop() def pop_first(self): if not self.a: self.partition() try: return self.a.pop() except: return self.b.pop() def __len__(self): return len(self.b) + len(self.a) class StringBuffer(Deque): """A FIFO for characters. Strings can be efficiently appended to the end, and read from the beginning. Example: B = StringBuffer('Hello W') B.append('orld!') print B.read(5) # 'Hello' print B.read() # 'World!' """ def __init__(self, s=''): Deque.__init__(self) self.length = 0 self.append(s) def append(self, s): n = 128 for block in [s[i:i+n] for i in range(0,len(s),n)]: self.push_last(block) self.length += len(s) def prepend(self, s): n = 128 blocks = [s[i:i+n] for i in range(0,len(s),n)] blocks.reverse() for block in blocks: self.push_first(block) self.length += len(s) def read(self, n=None): if n == None or n > len(self): n = len(self) destlen = len(self) - n ans = [] while len(self) > destlen: ans += [self.pop_first()] self.length -= len(ans[-1]) ans = ''.join(ans) self.prepend(ans[n:]) ans = ans[:n] return ans def peek(self, n=None): ans = self.read(n) self.prepend(ans) return ans def __len__(self): return self.length def __str__(self): return self.peek() def __repr__(self): return 'StringBuffer(' + str(self) + ')' - Connelly Barnes From llothar at web.de Mon Jun 7 08:40:00 2004 From: llothar at web.de (Lothar Scholz) Date: 7 Jun 2004 05:40:00 -0700 Subject: OSX IDE usability issues References: <1b720baf.0406061535.241aebbc@posting.google.com> Message-ID: <6ee58e07.0406070440.6f5f0671@posting.google.com> holcombea at cardiff.ac.uk (Alex Holcombe) wrote in message news:<1b720baf.0406061535.241aebbc at posting.google.com>... > 1. when I copy text from a Python script (using command-C or the menu) > and paste it in on the command line, only the first line of the text > is actually executed, even though manually entering the same lines one This depends on the IDE. Most console applications use the stupid method of one line after the other, not thinking about the reasons that lead to this technique a few decades ago. I don't think an interactive console should be implemented any more in this way. > 2.Even if the above did work, trying to execute a few lines of code > out of a Python script should typically not work, if I understand > Python syntax correctly. ?Because to Python indentation whitespace is You can, this is also possible if the IDE indentifies your initial indentation and unindent the code before feeding the it to the interpreter. Should be a few lines of code. > 3. One nice thing about MATLAB is I can execute a script and then > query the values of all the script's variables from the command line. > By just typing the variable name, I can see its value. ?In contrast, > it appears that in Python variables have more restricted scope such > that the command line can't "see" the variables executed in a Python > script. ?Is there some way to make the variables in a Python script > global so that I can play with them on the command line? Can you explain this a little bit more ? If you cut&paste some of the former local variables becames of course global variables. If you give an example it would be much better to understand. And from what i know, Python is a much complexer language then MATLAB so don't expect that everything is so easy. But you get back better programs. There are a lot of improvements by using an interpreted language like python, but maybe this does not fit your personal programming style. If you get more experience with programming you will find that testing individuell code snippets will be less and less important. Of couse it's nice to explore a new library but this can also be done with simple scripts. In fact i find it much more complicated to cut&paste code instead of running a file where i do the changes. Oh yes, (1) and (2) are resolved in "Arachno Python IDE", which is in a closed beta testing phase. From tjreedy at udel.edu Sat Jun 12 10:29:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jun 2004 10:29:46 -0400 Subject: dict of arrays References: <20040613111122.GA19788@mrna.tn.nic.in> Message-ID: "km" wrote in message news:20040613111122.GA19788 at mrna.tn.nic.in... > > Hi all > can one create a dict holding arrays as values to the dict keys in python ?. Dict keys must be hashable. Dict values can be any Python object. Yes. Terry J. Reedy From claudio.grondi at freenet.de Wed Jun 9 20:00:22 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 10 Jun 2004 00:00:22 -0000 Subject: Python Scripting in Windows MSIE 6.0 Message-ID: <2ipfihFq4aunU1@uni-berlin.de> I wonder why the subject (Python scripting within HTML) is not occuring in any past postings - do I miss something very obvious? I try to run Pythons scripting in Windows MSIE 6.0 in the section, but it doesn't work at all. \Python23\Lib\site-packages\win32comext\axscript\client\pyscript_rexec.py runs ok, registry entries seems also be ok. I have the latest Python 2.3.4 installed. What do I wrong? Runs anyone of you (inspite of the security concerns) successfully Python as scripting language in Windows MSIE 6.0 HTML pages using it like JavaScript or VBScript ? Thank you in advance for any help. Claudio From bhushit at hotmail.com Wed Jun 23 13:49:52 2004 From: bhushit at hotmail.com (Bhushit Joshipura) Date: 23 Jun 2004 10:49:52 -0700 Subject: Python for TCLer Message-ID: <849e4506.0406230949.605df12e@posting.google.com> I am almost brainwashed to forsake TCL for Python. However, I wanted to ask a few preliminary questions before I jump in. The over all picture of my project would look like: Front End : TCL scripts - Our API to users (Can't change because of legacy) ----->Middle Layer : Framework (PYTHONization Target) Back End: TCL API from vendors (Can't change), in-house Expect API (can't risk for reliability) 1. One of my vendors supplies TCL package only. Can I call TCL procedures from Python back end? What about Expect scripts? 2. OTOH, all my scripts are in TCL. Can I invoke python from TCL and retain states in python? 3. This is closely related to uplevel question already discussed in this group. We have one control structure in our API that has done wonders in productivity. I can not let it go. Does python let me write a control structure? It looks like: set x 10 set y 5 controlStructure { do something with $x until y becomes 3 ;#This is evaluated in caller's frame } 4. Does there exist a mapping of TCL facilities over Python? It will help me in training man power. Ideal place would describe uplevel "..." would translate to eval "..." would translate to subst "..." ... 5. Does Aspect Oriented Extension exist for Python? I know TOS (http://www.aopsys.com/tos) is no longer maintained for TCL. Thanks in advance, -Bhushit From stephendotboulet at motorola_._com Wed Jun 30 17:02:50 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Wed, 30 Jun 2004 16:02:50 -0500 Subject: Function not available after importing module Message-ID: This must be a dumb error on my part. I'm creating a module called "wxMessageBox.py". When I do an "import wxMessageBox" I don't see my "askopenfilename" function in the wxMessageBox namespace. When I do a "python -i wxMessageBox.py" it's there and seems to work fine. Here's the (short) code: def askopenfilename(startdir, filetypes="All files (*.*)|*.*"): ....import wx ....app = wx.PySimpleApp() ....dlg = wx.FileDialog(None, ........message="Choose a file", ........defaultDir=startdir, ........defaultFile="", ........wildcard=filetypes, ........style=wx.OPEN | wx.CHANGE_DIR) ....path = -1 ....if dlg.ShowModal() == wx.ID_OK: ........path = dlg.GetPath() ....return path def showerror(caption, message): ....import wx ....app = wx.PySimpleApp() ....dlg = wx.MessageDialog(None, ........message=message, ........caption=caption, ........style=wx.ICON_ERROR) ....app.MainLoop() ....dlg.ShowModal() if __name__ == '__main__': ....#showerror('Error!', 'No text on clipboard') ....print askopenfilename(startdir="C:\\") From llothar at web.de Sun Jun 13 17:43:56 2004 From: llothar at web.de (Lothar Scholz) Date: 13 Jun 2004 14:43:56 -0700 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: <6ee58e07.0406131343.7d68af87@posting.google.com> klachemin at home.com (Kamilche) wrote in message news:<889cbba0.0406122346.2e77941b at posting.google.com>... > I love Python, but I'm less than in love with IDLE. It's OK, but it > really doesn't have enough capabilities. > > What I consider critical, are a popdown listing of all my functions, > colored syntax printing, and a right-click 'definition' context menu > that will hop you to the spot where that keyword is defined, if > possible. Everything else I could learn to do without, but these > features keep me hoping for a better IDE for Python. The problem is that you need more then file level scope for this. For example the information about all projects and runtime files must be keept in memory. Only WingIDE and the upcoming Arachno Python IDE can do this. > I would also like the ability to create application 'forms' visually. > I'm on a Windows XP machine. AFAIK only BOA, Black Adder and WXDesigner do this, maybe the Komodo TK gui builder can be used with python. From rogerb at rogerbinns.com Sat Jun 5 02:24:33 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 4 Jun 2004 23:24:33 -0700 Subject: Can python control complicated classes/objects written in C++ References: Message-ID: Bo Peng wrote: > I am planning on an application that involves several complicated C++ > classes. Basically, there will be one or two big data objects and some > "action" objects that can act on the data. I would like to use a script > language to control the interaction between these c++ objects. The example you give will be no problem using SWIG and Python. In general the area where things get tricky is dealing with memory management. You have to decide who "owns" any returned objects - do they belong to the C++ code and have to be freed via method calls, or do they belong to the Python proxy object which frees them when it is deleted. The former case can lead to memory leaks and the latter case can lead to things being freed that are referenced by other C++ objects. You can have difficulty in this area if the underlying C++ library is poorly designed. For example I have had to deal with cases where the C++ objects had references between each other and it was really hard to figure out when to free the objects. Mind you I would encounter the same issues if using the library from other C++ code. In the end I had to write a C++ wrapper on top of the C++ library and deal with reference counting and that kind of stuff in the wrapper. The wrapper trivially exported to Python via SWIG. I guess the point I am making in a long winded way is that if the library is poorly designed, especially with respect to objects ownership issues, then Python won't make them go away and may highlight them more since more code paths become possible. Roger From deetsNOSPAM at web.de Sun Jun 6 16:29:56 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 06 Jun 2004 22:29:56 +0200 Subject: Problem with Python xrange References: Message-ID: Christian Neumann wrote: > x[1:4] ## It should be return an xrange object with length 3 > Is this really a bug? No. xrange doesn't create an actual sequence you can slice, instead it creates an iterable object usable in for ... in ... statements. The reason is that its much more memory-consuming to create a list if all you are interested in are only the generated indices. Use range, if you really want a list. -- Regards, Diez B. Roggisch From davidf at sjsoft.com Wed Jun 23 04:32:17 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 10:32:17 +0200 Subject: String concatenation In-Reply-To: References: Message-ID: Peter Hansen wrote: > Jonas Galvez wrote: > >> Is it true that joining the string elements of a list is faster than >> concatenating them via the '+' operator? >> >> "".join(['a', 'b', 'c']) >> >> vs >> >> 'a'+'b'+'c' >> >> If so, can anyone explain why? > > > It's because the latter one has to build a temporary > string consisting of 'ab' first, then the final string > with 'c' added, while the join can (and probably does) add up > all the lengths of the strings to be joined and build the final > string all in one go. Idea sprang to mind: Often (particularly in generating web pages) one wants to do lots of += without thinking about "".join. So what about creating a class that will do this quickly? The following class does this and is much faster when adding together lots of strings. Only seem to see performance gains above about 6000 strings... David class faststr(str): def __init__(self, *args, **kwargs): self.appended = [] str.__init__(self, *args, **kwargs) def __add__(self, otherstr): self.appended.append(otherstr) return self def getstr(self): return str(self) + "".join(self.appended) def testadd(start, n): for i in range(n): start += str(i) if hasattr(start, "getstr"): return start.getstr() else: return start if __name__ == "__main__": import sys if len(sys.argv) >= 3 and sys.argv[2] == "fast": start = faststr("test") else: start = "test" s = testadd(start, int(sys.argv[1])) From mhuening at zedat.fu-berlin.de Mon Jun 14 05:02:48 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 14 Jun 2004 09:02:48 GMT Subject: Does a Python Sound Library exist? References: Message-ID: gohaku wrote in news:mailman.836.1086918363.6949.python-list at python.org: > Hi everyone, > I would like to know if there is a sound library for manipulating and > retrieving information from .WAV or .MP3 Files. > I don't know if that is what you are looking for, but I just saw the announcement of PyMedia on this list: http://pymedia.sourceforge.net Matthias From alan.gauld at btinternet.com Sat Jun 5 05:01:13 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 05 Jun 2004 10:01:13 +0100 Subject: UML Tools References: Message-ID: On Fri, 04 Jun 2004 11:48:59 +0200, Neil Benn wrote: > Does anyone know of a decent tool to write UML diagrams > (mainly class diagrams but sequence would also be useful) that's aware > of Python's syntax (i.e. modules). I'd like round-trip as well but I > can live without it. What do you mean by being "aware of Python's syntax"? Any UML diagram tool, even Visio, can draw class diagrams and sequence diagrams and UML packages can represent modules. Do you mean you want the tool to generate python code too? Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From iv at an.voras.fer.hr Mon Jun 21 10:56:36 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Mon, 21 Jun 2004 16:56:36 +0200 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: Peter Hansen wrote: > Larry Bates wrote: > >> 2) Always call Python and have it run the application. >> Don't just try to run progname.py. > > > This actually works, though, at least on my system. It > might be because I inserted .py in the PATHEXT env var > globally, though I thought it was just because running > a .py is possible simply by clicking on it in Explorer > (ie. the File Association does the job). No, putting .py in PATHEXT is necessary. That way, you can run python programs from the command line (cmd) using just "scriptname", without the extension! (it performs just like .bat, .exe and similar files) From manatlan at online.fr Wed Jun 23 14:09:32 2004 From: manatlan at online.fr (marco) Date: Wed, 23 Jun 2004 20:09:32 +0200 Subject: how to obtain its ip address ? Message-ID: <40d9c75d$0$26573$626a14ce@news.free.fr> I'd search a lot ... but i had not found how can i obtain my ip address (when i'm connected to the www) ?! thanks a lot for any tips marco From cliechti at gmx.net Tue Jun 29 18:06:27 2004 From: cliechti at gmx.net (Chris Liechti) Date: Tue, 29 Jun 2004 22:06:27 +0000 (UTC) Subject: win32 pyserial requires javax.comm for py2exe? References: Message-ID: Thomas Heller wrote in news:acym9qha.fsf at python.net: > Peter Hansen writes: > >> Grant Edwards wrote: >> >>> I'm trying to package a small Python program using py2exe. >>> Everything works fine until I add an "include serial", then py2exe >>> fails because >>> The following modules appear to be missing >>> ['javax.comm'] >> >> Actually, you are assuming too much. It's a warning, not a failure. >> The .exe file is generated and will run just fine under Windows. >> >> Don't bother editing PySerial! You'll just create a maintenance >> hassle for yourself. > > Right. pyserial probably uses the same code for CPython and Jython, almost. my package __init__.py has an if "sys.platform" .. and imports the platform implementation from an other file. however, as Roger also pointed out, it's the module finder that just catches all imports. but well, it's maybe a bit inapropriate to follow up on Thomas' post he sure knows how py2exe works ;-) > if you want to avoid the warning you should exclude 'javax.comm' from > the build, either with the '--excludes javax.comm' command line option, > or by passing something like this to the setup function in your build > script: > > setup(... > options = {'py2exe': {'excludes': ['javax.comm']}}) yes. maybe i should put that in the docs... ok, done, i also added a setup_demo.py for py2exe in the pyserial examples (CVS on pyserial.sf.net) and the funny part is that Grant now packages a third party module that contains code from him (with his name in the sources of course, in the posix implementation) :-) chris -- Chris From python-url at phaseit.net Tue Jun 29 13:03:40 2004 From: python-url at phaseit.net (Peter Otten) Date: Tue, 29 Jun 2004 17:03:40 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) Message-ID: <10e387c3de50u6e@corp.supernews.com> QOTW: "I worry about Python losing its KISS principle. Python 2.2 has been ported to the Nokia Series 60 platform, which has something like 8-16 MB of RAM available. I'm sure the footprint growth of Python 2.3 and 2.4 gives those developers nightmares already when they are thinking of tracking later versions..." - Guido van Rossum "Everyone knows that any scripting language shootout that doesn't show Python as the best language is faulty by design." - Max M In his answer to John Fabiani, Martin von Loewis informs about the limitations (sic!) of 64-bit Python. For the rest of us it's good to know it's there. http://groups.google.com/groups?threadm=iBADc.3245%247q2.935%40newssvr27.news.prodigy.com While Steve Holden explains how to craft SQL-Queries properly to take advantage of the Python Database API's parameter substitution features, he advances from most likely the oldest to definitely the oldest Python user. Or is it just sample data? http://groups.google.com/groups?selm=40DD7414.6080406%40holdenweb.com George Young learns the hard way about a pitfall of implicit conversion to bool in an if statement. http://groups.google.com/groups?c2coff=1&th=fbf8f0f9595d702a See Eric DeWall's post for an example where the null object design pattern (pointed out by Irmen de Jong) can help clean up your code. http://groups.google.com/groups?threadm=cbfkrt%24ufo%241%40fair.qualcomm.com Uwe Schmitt submits a nice recipe dealing with hierarchical data to the Python Cookbook. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286150 Blogging addicts among the pythonistas - have you been on planet Python? http://www.planetpython.org/ Frank Immich triggers a sudden spike of activity in the german python mailing list. Various algorithms to discover consecutive numbers in a list are explored, which may also be of interest to an international crowd. http://starship.python.net/pipermail/python-de/2004q2/005167.html Gabor Farkas wants to know how to cope with a dictionary that is getting too big to hold in memory. Along with the standard answers he receives a custom solution by Jeff Epler. http://groups.google.com/groups?threadm=mailman.180.1088275787.27577.python-list%40python.org You're not a lawyer, of course, but you spend part of your time trying to think like one. It follows that the intellectual property documents Marc-Andre Lemburg and the rest of the PSF are accumulating might interest you. http://www.python.org/cgi-bin/moinmoin/PythonSoftwareFoundation Phil Thompson announces the release of SIP Version 4.0, a tool to generate Python wrappers for C and C++ libraries. http://groups.google.com/groups?selm=mailman.45.1088005998.27577.python-list%40python.org ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From gry at ll.mit.edu Fri Jun 25 11:37:13 2004 From: gry at ll.mit.edu (george young) Date: 25 Jun 2004 08:37:13 -0700 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? Message-ID: <78b6a744.0406250737.310f31da@posting.google.com> [Python 2.3.3, x86 linux] I had developed the habit of using the neat python form: if someinstance: someinstance.memb() because it seems cleaner than "if someinstance is not None". {please no flames about "is not None" vs. "!= None" ...} This seemed like a good idea at the time :(). Twice, recently, however, as my app grew, I thought, hmm... it would make things clearer if I gave this container class a __len__ member and maybe a __getitem__. Great, code looks nicer now... crash,crash, many expletives deleted... Its great to be able to say containerinstance[seq] instead of containerinstance.steps[seq], but I've also changed the semantics of (containerinstance) in a boolean context. My app breaks only in the seldom case that the container is empty. Obviously I know how to fix the code, but I'm wondering if this isn't a message that "if containerinstance:" is not a good coding practice. Or maybe that one should never *add* on sequence emulation to a class that's already in use. It may look like adding a __len__ and __getitem__ is just *extending* the functionality of the class, but in fact, it strongly *changes* semantics of existing usage of the class. I know the ref manual mentions this behaviour, but I begin to wonder at the wisdom of a language design and common usage pattern of (containerinstance) instead of (len(containerinstance)) and (containerinstance is None) as a boolean expression. Comments? Suggestions? From dummy at scriptolutions.com Tue Jun 29 06:50:47 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Tue, 29 Jun 2004 12:50:47 +0200 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: On Mon, 28 Jun 2004 16:39:40 -0500, "A.M. Kuchling" wrote: >It seems much simpler to choose PostgreSQL (or perhaps Firebird) instead of >MySQL; neither database presents such an irritating licensing issue. > >--amk This is not a possible option. I must use MySQL. 95% (??) of the databases in the small company world are MySQL based. Now this world becomes to look more and more like Micrsosoft, especially if you keep in mind that MySQL AB is now owned by the worlds 3rd largest Software Company SAP. From mm2ps at yahoo.co.uk Fri Jun 11 07:41:37 2004 From: mm2ps at yahoo.co.uk (Douglas) Date: 11 Jun 2004 04:41:37 -0700 Subject: lua: any comments Message-ID: <4cec047f.0406110341.1ec84bc2@posting.google.com> I'd like to hear your comments on lua (www.lua.org). Douglas From klachemin at home.com Fri Jun 25 16:33:33 2004 From: klachemin at home.com (Kamilche) Date: 25 Jun 2004 13:33:33 -0700 Subject: Python Magazine exists! References: Message-ID: <889cbba0.0406251233.4646aad3@posting.google.com> Ognen Duzlevski wrote in message news:... > > I went to see your magazine and it looks pretty nice. However, you do publish quarterly and in my humble opinion, a > yearly subscription of 49 Euros is crazy. I agree. For an online magazine, $69/year seemed steep. From ptmcg at austin.rr._bogus_.com Wed Jun 23 17:09:51 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 23 Jun 2004 21:09:51 GMT Subject: String help References: Message-ID: "Rigga" wrote in message news:pan.2004.06.23.20.36.49.944081 at hasnomail.com... > Hi, > > I am new to python and am working on a script that parses a file and loads > the results in to variables for processing. I am having problems when it > comes to data in the file that wraps over two lines i.e. > > las - > lomas > > What i want to be able to do is to some how strip all the spaces from it > so while it is contained as a variable so it equal 'las - lomas' > > How do I go about doing this? I have tried it using the > string.strip(myvariable,"") however that doesnt appear to do anything. > > Any help appreciated > > Rigga Try combining split() and join(), something like: testdata = """ this is some data that spans multiple - lines """ print " ".join( testdata.split() ) gives: this is some data that spans multiple - lines This even handles tabs, and removes trailing whitespace. -- Paul From BELLEMAIL-SA at exponent.com Thu Jun 17 07:55:47 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 04:55:47 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28E92@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = ahaas at airmail.net Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 230 Scanning time = 06/17/2004 04:55:46 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment the_message.cpl matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From brian at sweetapp.com Sun Jun 27 11:38:27 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Sun, 27 Jun 2004 17:38:27 +0200 Subject: ImportError: No module named functional In-Reply-To: References: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> Message-ID: <40DEE9F3.4020106@sweetapp.com> Maurizio Colucci wrote: > Gian Mario Tagliaretti wrote: > > >>If "functional" is not your own module is normal, yes. > > > But in these articles the author writes as if they were predefined > modules... > > http://www-106.ibm.com/developerworks/linux/library/l-prog3.html Actually, he mentions that you need this toolkit: http://sourceforge.net/projects/xoltar-toolkit Can I suggest that you are learning something too complex for someone new to Python? Cheers, Brian From ajsiegel at optonline.com Tue Jun 1 19:51:07 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 01 Jun 2004 23:51:07 GMT Subject: terminological obscurity References: <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> <40b83034$0$27038$9b622d9e@news.freenet.de> <40b931c8$0$24826$9b622d9e@news.freenet.de> <40BD0564.5090002@v.loewis.de> Message-ID: <3g4qb0p5do5q1ivbeq3c54l9qqjaqp21qt@4ax.com> On Wed, 02 Jun 2004 00:38:28 +0200, "Martin v. L?wis" wrote: >You find the term "color" meaningless because there are things it >doesn't apply to? Is there any term in the universe (or, perhaps >even in the English language) that you find meaningful? > Well perhaps we choose to conceptualize in different grammatical constructs, You do predicates, I do verbs. A list is what it can do based on its Guido-given capaiblities, which may change tomorrow. A tuple is different from a list to the extent its behaviors and capabilities differ from a list. Anything further than that seems to me to be mposing an order in an unnecessary fashion. Guido, we know, conceptualizes around "homogenous" and "heterogenous" in his design thinking. Which is worth knowing. As it own kind of information. Art From steve at ferg.org Sun Jun 27 15:57:18 2004 From: steve at ferg.org (Stephen Ferg) Date: 27 Jun 2004 12:57:18 -0700 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Komodo. Very full featured, and the personal edition is cheap. From claudio.grondi at freenet.de Wed Jun 16 14:51:35 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 16 Jun 2004 18:51:35 -0000 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: <2jbcagFvedvtU1@uni-berlin.de> >> I like UE too, but does its syntax coloring support Python's triple qutes? I >> couldn't get it to work. >>/Block Comment On = """ >>/Block Comment Off = """ >> That's very nice. I'm now using it. It doesn't work for me with the triple quotes. Only the first line turns green, all other remain without beeing marked as comment, both in Ultra Edit 9.00 and 10.2a . Does it _really_ work ok with the triple quotes? What could be the reason it doesn't work for me? Claudio From theller at python.net Wed Jun 9 03:13:00 2004 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jun 2004 09:13:00 +0200 Subject: dropping into the debugger on an exception References: <2inqlrFp53m5U1@uni-berlin.de> Message-ID: Jon Perez writes: > (sorry for the duplicate post, just wanted to make the subject > line clearer) > > How do you set up pdb such that you will automatically > get dropped into its prompt if an unanticipated exception > occurs in a script you are using? > > ASPN Python cookbook gives you the following method > which you can add to your script and hook into sys.excepthook. > But is there a way to do it without adding stuff to your > script? (It's okay if this means having to invoke the script > from within pdb, but #1, I don't know how to get it stay inside > pdb in the case of an /unanticipated/ exception. And #2, I > don't know how to pass [the equivalent of] command-line > arguments to a script invoked from within pdb.) [...] Is the description in the cookbook unclear? You do *not* have to add anything to your script - save the code as a file C:\Python23\sitecustomize.py and everything will work. And you don't have to start the script from within pdb. The sitecustomize module is automatically imported when Python starts - if it is found. I'm appending the version I currently use, maybe it has some improvements not mentioned in the online version. Thomas """ # code snippet, to be included in 'sitecustomize.py' import sys import traceback, pdb ##import pywin.debugger def info(type, value, tb, excepthook=sys.__excepthook__, print_exc=traceback.print_exception, ## debug=pywin.debugger.pm): debug=pdb.pm): if not __debug__ \ or not sys \ or hasattr(sys, 'ps1') \ or not sys.stderr.isatty() \ or not sys.stdin.isatty() \ or not hasattr(sys, "last_traceback"): # call the default hook if one of the following conditions # is satisfied: # - Python is running with the -O flag (__debug__ == 0) # - sys is None (python is shutting down, and the sys module # already has been cleared) # - we are in interactive mode (sys has a 'ps1' attribute) # - sys.stderr is not a tty: we are not connected to a terminal # - no last_traceback attribute in sys (SyntaxError) excepthook(type, value, tb) else: # print the exception... print_exc(type, value, tb) # ...then start the debugger in post-mortem mode. debug() sys.excepthook = info """ From mark at prothon.org Sat Jun 26 03:03:08 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 26 Jun 2004 00:03:08 -0700 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: Doug Holton wrote: > Mark Hahn wrote: > > Prothon by the way doesn't have anonymous code blocks, but it can > do: > > > b = button() > > def b.onClick(): > > print "You clicked me" > > That's the alternative David Eppstein mentioned, and I like it even > better than my =: suggestion ( b.onclick =: ). FYI... If you don't need b, you could also do this: def button().onClick(): print "You clicked me" If you need b and you want to write compact (some would argue Perl-like) code, you could use a new syntax we are debating right now that allows assignments-as-expressions with ":=". def (b := button()).onClick(): print "You clicked me" There are valid non-Perl-like uses for := also. :-) From edvard+news at majakari.net Wed Jun 16 04:13:42 2004 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 16 Jun 2004 11:13:42 +0300 Subject: somewhat OT: function to produce n as distinct colors as possible Message-ID: <87pt7zrkcp.fsf@titan.staselog.com> Ok, not strictly Python related: I wonder if any of you graphical Python folks have run accross some handy resource for the given topic. The problem is that of producing histograms, where n distinct items can be plotted simultaneously. However, when n goes over 6 it is not very easy to make up colors that are easily distinguishable from each other. So, now I'm thinking of two alternatives: 1. Create an algorithm distinct_colors(n, bg), which produces n-1 as distinct colors as possible (where bg is one of the colors) and returns those colors in RGB color model as tuple of decimals (r, g, b). Eg. distinct_colors(4, (255, 255, 255)) would return ((255, 0, 0), (0, 255, 0), (0, 0, 255)) assuming that "pure-rgb" red, green and blue are visually the three as distinct colors as possible from white. 2. Find a color palette containing say, 8 or 10 colors as visually far apart from each other as possible The first one would be more nice, but I doubt I can produce it myself without any knowledge of psychology and physics related to phenomenon. Using google it seemed like there's demand for the algorithm. I'll probably publish the code in Python Cookbook or similar if I end up with something nice. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, was not full of lettuces. This did not seem fair. --Mr Bunnsy has an adventure From peter at engcorp.com Mon Jun 21 10:23:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 10:23:09 -0400 Subject: Collecting Python's responses. In-Reply-To: References: Message-ID: Jacek Generowicz wrote: [...] > Does anything like this exitst? If not, any suggestions how best to go > about it. Would it be possible just to do it in the local process, using http://docs.python.org/lib/module-code.html ? Or if there's a reason not to do it locally, then do it through sockets but still using that... -Peter From has.temp2 at virgin.net Sat Jun 19 08:52:39 2004 From: has.temp2 at virgin.net (has) Date: 19 Jun 2004 05:52:39 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: <69cbbef2.0406190452.351c53fb@posting.google.com> Leif K-Brooks wrote in message news:<2jh2glF10adr2U1 at uni-berlin.de>... > I'm planning to start on a fairly large web application, most likely > using mod_python. I recently wrote a fairly small (but real-world > useful) web app with it, and all of those req.write()s made for really > ugly code. Would a templating engine solve that? Yep. > Does anyone have any suggestions about which one to use? Shameless self-plug:) - http://freespace.virgin.net/hamish.sanderson/htmltemplate.html From insert at spam.here Wed Jun 2 17:36:25 2004 From: insert at spam.here (Doug Holton) Date: Wed, 02 Jun 2004 16:36:25 -0500 Subject: python applets? In-Reply-To: References: Message-ID: Andreas R?sdal wrote: > Hi, > > Is there such a thing as python applets for web browsers? (eg. such as > java applets?) I think that could be useful. No, there was a web browser project called Grail that allowed python applets, but it is was abandoned. I think the main issue is security. Right now there is no official way to restrict what a python program can and cannot do, such as delete a file on the hard drive. One thing you can do in Python that you cannot in Java however is embed a user's web browser (such as Internet Explorer or Mozilla) in your Python program. In some cases that is more desirable. From happy at opensourcery.net Mon Jun 14 16:05:52 2004 From: happy at opensourcery.net (Dave Williams) Date: 14 Jun 2004 13:05:52 -0700 Subject: Using maskededit controls with xrc and wxpython Message-ID: Hi, I'm having problems getting IpAddrCtrl working with a frame containing nested sizers generated from an xrc file. Firstly I tried adding it using AttachUnknownControl as per the example code Using XMLResources on the wxPython wiki. This renders but does not size correctly despite my trying many different variations. Because of my nested sizers I also seem to have to SetSizeHints etc at a higher level than in the example. Also I note that some of the functions used are marked in the wxWidgets docs as "for internal use only". Secondly I tried using subclassing as per the XMLResource*.py demos in the wxWigets/wxPython. This has the problem that it uses 2 stage creation which IPAddrCtrl etc doesnt support out of the box (yet?). As a Python newbie I'm still finding my way around so dont know how difficult that is to implement. I also note that XmlSubclassFactory_Python in wx/xrc.py will only instantiate a control using klass = getattr(module, cname) then klass() which does not allow for any parameter passing at that stage. Can anyone point me in the right direction? I need to get forward with my overall development and can't afford to get stuck on something that admittedly I had hoped would be "routine" to implement. Thanks Dave From peter at engcorp.com Fri Jun 25 08:45:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jun 2004 08:45:43 -0400 Subject: Encryption with Python In-Reply-To: <2nend09je70o8a07lvemhbn8ieo8aamuip@4ax.com> References: <889cbba0.0406221926.3f4e5776@posting.google.com> <889cbba0.0406231156.115b743a@posting.google.com> <2nend09je70o8a07lvemhbn8ieo8aamuip@4ax.com> Message-ID: Dennis Lee Bieber wrote: > I wouldn't call the above an "encryption" function -- it looks > to be nothing more than a substitution cipher. (I don't know how "cnt" > is determined, but translate will, for any given invocation, return the > same output character for any repeat occurrences of the input. A good > encryption algorithm should not do that -- ideally, "bookkeeper" will > encrypt with no repeated characters in the oo, kk, ee*e positions) Kamilche *did* state clearly that it was "not secure, but it should be enough to ward off casual hacking". Also, if we're both using the same version of English, a substitution cipher is still encryption, just a weak form. See http://en.wikipedia.org/wiki/Cipher and related links, which point out that even DES can be considered "from a sufficiently abstract perspective", a substitution cipher on an enormously large binary alphabet. ;-) -Peter From km at mrna.tn.nic.in Fri Jun 11 13:18:14 2004 From: km at mrna.tn.nic.in (km) Date: Fri, 11 Jun 2004 22:48:14 +0530 Subject: regex query Message-ID: <20040611171814.GA5318@mrna.tn.nic.in> Hi all, how do i include variable as a part of the regex string ? - i mean variable interpolation. like : ##########code ########## #!/usr/bin/env python import re str = "abc" p = re.compile('str') # defeats the purpose - literal string 'str' ##########code ########## any suggestions ? thanks in advance KM From ods at strana.ru Thu Jun 17 12:51:36 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 17 Jun 2004 20:51:36 +0400 (MSD) Subject: list to dict In-Reply-To: Message-ID: On Wed, 16 Jun 2004, Yermat wrote: Y> > What is the easiest/fastest way to build a dictionary from Y> a list? The Y> > list contains 100,000 entries. Y> > Y> > Thanks, Y> > Bart Y> Y> >>> dict([(1,'a'),(2,'b')]) Y> {1: 'a', 2: 'b'} Y> Y> list of tuples -> dict ! But unfortunately list({1: 'a', 2: 'b'}) -> [1, 2]. -- Denis S. Otkidach http://www.python.ru/ [ru] From ville at spammers.com Wed Jun 30 04:02:38 2004 From: ville at spammers.com (Ville Vainio) Date: 30 Jun 2004 11:02:38 +0300 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: >>>>> "mjt" == mjt writes: mjt> Ville Vainio wrote: >> Pythonic Nirvana - towards a true Object Oriented Environment mjt> ... with every new language/scripting language, we are mjt> supposed to discover nirvana Nirvana is not discovered - Nirvana just is ;-). The point was not liberation-through-Python, it was liberation-through-interactive-integration-at-deeper-level. -- Ville Vainio http://tinyurl.com/2prnb From hungjunglu at yahoo.com Tue Jun 1 16:21:48 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 1 Jun 2004 13:21:48 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> Message-ID: <8ef9bea6.0406011221.6b40c2e6@posting.google.com> Alexander Schmolck wrote: > Did this language support working interactively? If so I'd be pretty surprised > to hear that no one found it useful to be able to manually fix things and > continue execution; not being able to do so is presumably my number one gripe > with python [1] -- it annoys me no end if I need to start an expensive > computation from scratch because some trivial and easily fixable problem > occured towards the end of the computation (sometimes it is possible to > salvage stuff by hand by pickling things from the appropriate post-mortem > frame, but I'd *much* prefer being able to say: foo=some_value; resume). The edit-and-continue feature is also standard in the Microsoft world. Visual C++ and Visual Basic 6.0 all have this feature. (VB.NET does not, but they are implementing it for the version 2005 aka Visual Studio Whidbey.) Edit-and-continue is useful debugging tool, especially if the initial-state setup is expensive. Python is good, but not good enough in many areas. > Footnotes: > [1] Number 2 would be the stupid try: finally: idiom which also seems to > screw up tracebacks (which has occasionally led me to get rid of them > completely while debugging -- surely not a good thinge). My other gripes > are again related to python's limitations for interactive software > development -- I rather like python, but I really wish it did that > better. There are a few lessons learnt from younger programming languages, like Io. One lesson is that you really would like to avoid rigid statement syntax. In the example of the original topic of this thread, you cannot intercept/override exception handling mechanism because the try:...except:... block is not a function. Similar situations happen with issues regarding aspect-oriented programming. In a language like Io, everything is a method that send message to an object. Even If(...) statements are methods, as well as loops. The advantage is you can intercept things at your heart's content. In comparison, Python's exception handling is not interceptible, because exception handling is hard-coded in syntax. It does not mean all hope is lost in Python. But it does mean that instead of using the raise... statement in Python, you need to call a function/method instead. You can then intercept at that level: either by actually throwing an exception, or by redirecting it to some user intervention funtion, or by totally ignoring it (like using a 'pass' statement.) Interactive programming with features like edit-and-continue still has room to grow (most edit-and-continue features are not transactional, that is, you cannot revert changes easily.) But in my opinion that's an arena for prototype-based languages, and down the line, for reversible-computing languages. Frankly, theoretically it is possible to have a development environment where you never need to restart your program (for non-real-time applications.) As for Python's interactive programming, I've done some experiment before. It's not totally impossible. It's a bit uncomfortable. Python does have module reload and weakref. When you use these tools properly, you can achieve a high degree of non-stop programming. It does not come as part of the language per-se. You need to build up some tools yourself first. But after that, you can achieve non-stop programming, more-or-less. After all, Zope is a living example of a Python application where you can program a lot of things, without shutting down the server. regards, Hung Jung From oliver.schoenborn at utoronto.ca Sun Jun 6 08:47:28 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Sun, 6 Jun 2004 08:47:28 -0400 Subject: what is gc.set_debug() for Message-ID: Hello, I read the docs for gc module and did search with google. It's not clear what gc.set_debug(DEBUG_LEAK) is for, though it is recommended to diagnose mem leaks. There are 3 or 4 discussions that come up with google that call gc.set_debug(), but when I take that line out I don't see any difference. I.e., there's no extra info printed when garbage is collected, when gc.garbage examined, etc, I'm assuming it's something along those lines that debug level should do, but am dumbfounded. Thanks in advance for any help. Oliver From peufeu at free.fr Fri Jun 25 02:34:35 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 08:34:35 +0200 Subject: eZ80 - correction [z80 vs Python thread] References: <40db0161$0$29542$afc38c87@news.easynet.co.uk> Message-ID: Why not start from Stackless Python and thus have a multithreaded language which is well suited to automata on your uc ? Python won't do threads on your Z80 because it relies on the OS, and you have no OS... Stackless has threadlets which use little memory (you need that) ! On Thu, 24 Jun 2004 17:29:21 +0100, Peter Hickman wrote: > Perhaps you could look at the pippy project which is python on a PDA. > They will have had to shrink python down, maybe you could use that as a > starting point. -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From oliver.schoenborn at utoronto.ca Sun Jun 6 10:06:55 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Sun, 6 Jun 2004 10:06:55 -0400 Subject: "intermodule-global" variables References: Message-ID: <6yFwc.3627$sS2.74909@news20.bellglobal.com> "Eddy Ilg" wrote in message news:mailman.612.1086463928.6949.python-list at python.org... > Hi, > > > I am having a problem with an application I am writing: > > I have 2 scripts called 'conf' and 'build'. Both define > a variable named 'root' and import a module named 'helper'. > > In the helper module I want to access the root variable, that is > _either_ in conf _or_ build. How can I do this? > I just want the root variable to be global for all modules. > (I don't want to put root in helper, since that would make no sense at > all) There's probably something wrong with the design. If helper shouldn't know about conf or build, then why should it know about a variable that conf or build use? Rather, conf build and helper should all refer to a variable in a fourth module. > I also tried this: > > ---- helper.py > a=5 > > def printa(): > global a > print a > ---- > > >> from helper import * > >> a > 5 > >> a=6 > >> a > 6 > >> printa() > 5 > > > Why does this not work? Why are there suddenly two variables a? One > for helper.py (stays 5) and a global one (became 6)? This is a bit Because you have rebinded a. This can be a confusing aspect of Python at first, that you access objects through a reference rather than directly. So when you did a=6, you rebinded the module-level a to a new value, but this doesn't affect the other reference, in helper.py, that was also called 'a'. Same thing would happen for two classes: class A: def __init__(self): self.a =1 class B: def __init(self, a): self.b = a aa = A() bb = B(aa.a) Now both bb.b and aa.a refer to the same value. Now if you do aa.a = 2, that won't affect bb.b, rather bb.b and aa.a now refer to diferent variables. Oliver From ykingma at accessforall.nl Wed Jun 2 18:59:29 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Thu, 03 Jun 2004 00:59:29 +0200 Subject: python applets? References: Message-ID: <40be5bd1$0$33920$e4fe514c@news.xs4all.nl> Andreas R?sdal wrote: > Hi, > > Is there such a thing as python applets for web browsers? (eg. such as > java applets?) I think that could be useful. > > Andreas R. There is an example here: http://www.jython.org/docs/jythonc.html Good luck, Ype -- email at xs4all.nl From chris.schaller at web.de Tue Jun 15 08:20:34 2004 From: chris.schaller at web.de (Chris...) Date: 15 Jun 2004 05:20:34 -0700 Subject: Q: attribute access and comparisons of two different objects Message-ID: <2418de8e.0406150420.1c1bde76@posting.google.com> Two simple questions regarding future of Python: 1) Is there already a "fix" to avoid writing to an attribute that isn't defined yet? I remember this being an often discussed problem, but didn't see any changes. The only way I can think of is overriding __setattr__, but this is huge overhead. While I like the idea of being able to add new attributes on the fly, in great projects I'd like to restrict some classes not to do so. 2) This is driving me nuts: I do not want to compare apples and peas. I can say that they are not equal, but I cannot say that one is great than the other (speaking not of greater taste ;-). Just ran into a problem caused by comparing a string with a number ("1" > 10) -- I simply forgot to convert the string to an integer. Since I cannot add "1" + 10 which makes sense, I do not want to compare them. Any development regarding this? Any """from __future__ import"""? - Chris From winexpert at hotmail.com Mon Jun 7 08:33:36 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 07 Jun 2004 12:33:36 +0000 Subject: I think i figured out the list problem [python] Message-ID: I took a break and got breakfast. maybe this helped. If I understand this right, when I take a string and split it, it returns a list. So in effect I was appending a list to a list of items. The list was empty so I ended up with [ [ item1, item2, item3] ] a list of a list David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Getting married? Find great tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married From dalcolmo at vh-s.de Wed Jun 16 05:27:44 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Wed, 16 Jun 2004 11:27:44 +0200 Subject: computer names and samba shares References: Message-ID: <20040616112744.00001005@titan> Let's try a bit better: we have a Samba server and a local net: netmask 255.255.255.0 on 192.168.0.x (no proxies or so between me and this net). We do not have LDAP, yellow pages etc. though there is a DNS server. Network addresses are static (for now). I don't know what ADSI is, we do not use LDAP. I was hoping to find a platform-independent solution in Python, because some machines in the company use GNU/Linux, which means win32net is of limited use. Listing computers on a domain was the first part of my question. I would be even more interested to find out about the second part: listing Samba (Windows) shares on the Samba server (program running on a client machine). os.listdir(r'//myserver') doesn't work, because '//myserver' is not a directory. I guess I should look at the Samba docs, but was hoping there is already a library for Python ... Best regards - Josef Dalcolmo From dooms at info.LESS.ucl.SPAM.ac.be Thu Jun 17 01:57:52 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Thu, 17 Jun 2004 07:57:52 +0200 Subject: cannot pass a variable from a function In-Reply-To: References: Message-ID: <40d13306$0$84222$5fc3050@dreader2.news.tiscali.nl> If I understand well what you need: >>> def f(a): global q q = a * 80 print q >>> def g(l): global q for i in l: q = i * 80 >>> q Traceback (most recent call last): File "", line 1, in -toplevel- q NameError: name 'q' is not defined >>> f(5) 400 >>> q 400 >>> g([1,2,3]) >>> q 240 >>> However using global variables is a bad habit and you should restrain from doing it. Why not pass q to every of these functions and have them return the new value of q ? -- Gr?goire Dooms Doug Jordan wrote: > I am fairly new to Python. This should be an easy answer but I cannot get > this to work. The code is listed below. I know how to do this in C, > Fortran, and VB but it doesn't seem to work the same way here. > I would appreciate any help. > > #try this to pass a list to a function and have the function return > #a variable > #this works > list=[1,4,6,9] > def fctn(c): > for h in c: > q=h*80 > print q > #function suppose to return variable > def fctn2(c): > for h in c: > q=h*80 > return q > def prntfctn(y): > for j in y: > print j > fctn(list) > fctn2(list) > prntfctn(q) > > I need to be able to return variables from functions so they can be used > globally in the rest of the program I am writing. > Thanks > > Doug > > From phleum_nospam at chello.se Fri Jun 18 12:16:26 2004 From: phleum_nospam at chello.se (Carl) Date: Fri, 18 Jun 2004 18:16:26 +0200 Subject: Using Fortran libraries from Python? References: Message-ID: > Another solution (not tested) could be to use "-lg2c" instead of > "-lf2c". As I understand it, the g77 runtime library is derived from > the f2c runtime library. This seems to work! How did you know? > An even better (in my opinion) solution would > be to use "f2py" from , a tool to > wrap python (and C) code for python. I will try both "f2py" and all other possible solution suggestions to my problem. I'm positively overwhelmed by your response. You've saved me a great deal of trouble and (I don't know how many) hours of tedious trial and error work. Thank you! Carl From miki.tebeka at zoran.com Wed Jun 23 02:40:15 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 23 Jun 2004 08:40:15 +0200 Subject: why is there no more activity with this group In-Reply-To: References: Message-ID: <20040623064015.GA1640@zoran.com> Hello Doug, > I am new to the group and do not see any post in 2004. Is the group > still active? I estimate more than 50 emails a day this month. This make it active in my eyes :-) Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From aahz at pythoncraft.com Sun Jun 13 23:41:36 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Jun 2004 23:41:36 -0400 Subject: does python have useless destructors? References: Message-ID: In article , Roger Binns wrote: > >The whole problem that this thread is about is that Python has this >bizarre scheme that an object will be garbage collected *unless* you >add a __del__ method, at which point the docs imply you will be lucky >for garbage collection to *ever* happen on the object. Please keep the distinction between refcounting and GC clear. The business with __del__ breaking memory management *only* occurs when you need to use GC because you've got a cycle. Historically, Python didn't have GC, and you had leaky memory whenever you had cycles. Now we've got a much-improved situation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From eric at zomething.com Sat Jun 12 16:17:40 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sat, 12 Jun 2004 12:17:40 -0800 Subject: kid wants to know more about color on the screen Message-ID: <20040612121740.936489724.eric@zomething.com> "Doug Mitchell" wrote: > > My son who is in grade 7 has *just* started going through the book "Python > for the Absolute Beginner" by Michael Dawson. He and I have no programming > experience. He is beginning this on an old win 95 computer with Python 2.2 I > think. Hmmm... Is "Python for the Absolute Beginner" a good book? Would Doug or can anyone recommend this book (or another) for a 7th grader to learn programming with? I've had my son play with "Karel the Robot" in the past, and I am "threatening" to have him use Python to write something based on the Yu-Gi-Oh game this Summer, but I am not sure what resource to use to help him learn. (Idle minds problem and all that... whoops, almost a pun.) Also, is 7th grade too young for an introduction to MP's Flying Circus? :) Eric From iv at an.voras.fer.hr Mon Jun 21 10:13:53 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Mon, 21 Jun 2004 16:13:53 +0200 Subject: sys.stdout.write() question In-Reply-To: References: Message-ID: Gian Mario Tagliaretti wrote: > #!/usr/bin/env python > import sys, time > sys.stdout.write('write ') > time.sleep(3) > sys.stdout.write('this\n') > > if you try to run this, before it will wait 3 seconds and then print "write > this" in one time. > > If I put \n here : > > sys.stdout.write('write \n') > > it work properly but I would like to print the text in one row. It line-buffers the output. If you need to print something that is not 'a whole line', use sys.stdout.flush() after the ...write() From agriff at tin.it Mon Jun 28 15:51:30 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 28 Jun 2004 19:51:30 GMT Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: On 27 Jun 2004 11:22:18 -0700, klachemin at home.com (Kamilche) wrote: >I have a routine that I really need, but it slows down processing >significantly. Can you spot any ineffeciencies in the code? > >This code makes a critical function of mine run about 7x slower than >using a prebuilt format string. For maximum flexibility, it would be >best to calculate the format string using this method, so I'd dearly >love to keep it. After making a few experiments I found this faster... def fmtstring5(args, _type = type, _len = len, _str = str, _int = int, _long = long, _bool = bool, _float = float): fmt = "<" for arg in args: t = _type(arg) if t is _str: l = _len(arg) fmt = fmt + _str(_len(arg)) + 's' elif t is _int: fmt = fmt + 'i' elif t is _long: fmt = fmt + 'q' elif t is _bool: fmt = fmt + 'c' elif t is _float: fmt = fmt + 'd' else: raise Exception("Can't pack argument of type %s!" % t) return fmt+'\0' In other words I tried to remove dynamic lookups for predefined functions and used "is int" instead of the "types." stuff. s = s + x seems faster than s += x, and s = s + x seems faster that append & "".join also (at least for small formats). I tried to remove all setup cost (using a generator acting on a global variable), but gained nothing (and indeed that was a bit slower). I tried also to remove dynamic lookups for the addition (concatenation), but in no case I found results better than the plain vanilla addition syntax. HTH Andrea PS: I'm new to python, and found its speed interesting and more than adequate for many uses... It's however kind of depressing seeing that so much dinamicity is "wasted" in places where it's not needed (e.g. when calling "len" or "str"). This version was running on the examples I tested about twice the speed of the original version. So I suppose that the same is happening all over my python code :-( From shane at hcmglobal.com Tue Jun 8 21:18:07 2004 From: shane at hcmglobal.com (Shane) Date: Wed, 09 Jun 2004 13:18:07 +1200 Subject: Delphi run python script from file Message-ID: Greetings, I've been trying to get PyRun_SimpleFile to work from Delphi without success, has any one done this? Doing it in C/C++ is trivial, but I need Delphi and I'm not a Delphi expert. In Delphi I've managed to load/unload/initialize/import/etc the python dll/functions and get PyRun_SimpleString to work no problem. PyRun_SimpleFile just causes an 'Access Violation' error. I've poked arround inside Python-for-Delphi but it doesn't seem to support execution from python files. I'd like to avoid COM. The ultimate objective is to be able to use/distribute .pyc files and to get PyRun_File working. Can anyone help ? Thanks. ENV +++++++ Win2k Delphi 7 Python 2.3.3 From claudio.grondi at freenet.de Thu Jun 10 19:30:28 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 10 Jun 2004 23:30:28 -0000 Subject: How to get decimal form of largest known prime? Message-ID: <2is27mFqeen8U1@uni-berlin.de> According to latest news the largest known prime is: 2**24036583 - 1 (right?) Do someone of you know how long would it take on a 2.8 GHz Pentium 4 machine to write a _decimal_ form (hexadecimal form can be written in less than one second) of this prime to a file and what should be the Python code to use for it? Claudio P.S. file.write( '%i' % (2**24036583 - 1,) ) takes 100% CPU for a long time without any result and the critical part is the '%i' % (2**24036583 - 1,) conversion. From damian_birchler at bluewin.ch Wed Jun 9 07:36:16 2004 From: damian_birchler at bluewin.ch (damian birchler) Date: 9 Jun 2004 04:36:16 -0700 Subject: Dynamically adding methods to objects? References: Message-ID: <29381ecf.0406090336.5a2596b5@posting.google.com> Thanks a lot, I learnt somthing new. A few minutes after I posted my message I discovered the setattr function. That was good enough for my purposes. But thanks anyway for the usefull informations. cu From tungwaiyip at yahoo.com Wed Jun 30 16:23:30 2004 From: tungwaiyip at yahoo.com (Wai Yip Tung) Date: Wed, 30 Jun 2004 13:23:30 -0700 Subject: script to download Yahoo Finance data References: <94abfadd.0406291838.53600d7b@posting.google.com> Message-ID: For project A, why do you need to do step 1 and 2? Is it for human to enter fields like stock symbol in HTML form? Since you are writing a script, you can format the symbol in the URL you use in step 3 directly. In that can simply use urllib.urlopen() to download the data. E.g. symbol = 'IBM' url = 'http://ichart.yahoo.com/table.csv?=%s&a=00&b=2&c=1962&d=05&e=30&f=2004&g=d&ignore=.csv' % (symbol,) f = urllib.urlopen(url) print f.read() Wai Yip Tung On 29 Jun 2004 19:38:06 -0700, dan roberts wrote: > Folks, > > This is my first Python project so please bear with me. I need to > download data from Yahoo Finance in CSV format. The symbols are > provided in a text file, and the project details are included below. > Does anyone have some sample code that I could adapt? > > Many thanks in advance, > dan > > /*---NEED TO DO------*/ > Considering IBM as an example, the steps are as follows. > > A. Part 1 - download 'Historical Prices' from > http://finance.yahoo.com/q?s=ibm > 1. Get the Start Date from the form at the top of this page, > http://finance.yahoo.com/q/hp?s=IBM > (I can provide the end date.) > 2. Click on Get Prices > 3. Then finally click on Download to Spreadsheet and save the file > with a name like IBM_StartDate_EndDate.csv. > (2) and (3) are equivalent to using this link directly, > http://ichart.yahoo.com/table.csv?s=IBM&a=00&b=2&c=1962&d=05&e=30&f=2004&g=d&ignore=.csv > Can you please post an example of a loop that would do the above for a > series of company symbols, saved in a text file? > > B. Part 2 - download 'Options' from http://finance.yahoo.com/q?s=ibm > This seems more difficult because the data is in html format (there's > no option to download CSV files). What's the easiest/best way to take > care of this? From FBatista at uniFON.com.ar Thu Jun 17 13:51:40 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 17 Jun 2004 14:51:40 -0300 Subject: How to make an immutable instance Message-ID: I'm working on Decimal, and one of the PEP requests is Decimal to be immutable. The closer I got to that is (in short): class C(object): __slots__ = ('__x',) def __init__(self, value): self.__x = value def getx(self): return self.__x x = property(getx) This way, you can not modify the instance: >>> import imm >>> c = C(4) >>> c.x 4 >>> c.x = 3 Traceback (most recent call last): File "", line 1, in -toplevel- c.x = 3 AttributeError: can't set attribute >>> c.a = 3 Traceback (most recent call last): File "", line 1, in -toplevel- c.a = 3 AttributeError: 'C' object has no attribute 'a' >>> hash(c) 10777424 The problem is that you actually could, if you take the effort, to rebind the __x name. So, if you use this "immutable" class in a dict, and then you (on purpose) modify it, you'll have different hashes. Said that, how safer is this approach? Is there a better way? Thank you all! . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ripolles at LALALAaditel.org Thu Jun 3 18:37:31 2004 From: ripolles at LALALAaditel.org (Eru) Date: Thu, 3 Jun 2004 22:37:31 +0000 (UTC) Subject: simplify printing of a list References: <3064b51d.0406031408.1b676379@posting.google.com> Message-ID: beliavsky at aol.com escribio: > To print a list with a specified format one can write (for example) > > for j in [0,1,2]: > print "%6d"%j, > print > > The code > > print "%6d"%[0,1,2] > > currently produces a syntax error, but it would be convenient if it > had the same meaning as the loop above. > > One can write a function to print a list, for example > > def print_list(x,fmt_x="%6d"): > """ print a list on one line """ > for y in x: print fmt_x % y, > > print_list([0,1,2]) How about using: def fmtlst(fmt,lst): return fmt*len(lst) % tuple(lst) print fmtlst("%3d",range(5)), fmtlst("%5.2f", [1.2, 3, 4.567]) This prints: 0 1 2 3 4 1.20 3.00 4.57 Maybe it gets your job done (though it's not the most efficient thing one can do...) > > but it gets messy to print several lists on the same line. > > In Fortran 90/95 one can write > > print "(100i6)",(/0,1,2/) > > where the format (100i6) means that UP TO 100 integers are printed > using 6 columns. An alternative suggestion I have for Python is to > allow > > print "100%6d"%[0,1,2] It looks a bit weird (unpythonic) to me, and we can use workarounds :) > > with the same meaning. > > I realize that what I am asking for is just a convenience, but it is > one that I could use in almost every program I write. -- Daniel Ripolles ( Eru ) Make Source, Not War for(0..pop){for($c=$_%2;$_>>=1;){$c=$_%2 .$c}print"$c\n"} From kenneth.m.mcdonald at sbcglobal.net Sat Jun 12 00:35:26 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sat, 12 Jun 2004 04:35:26 GMT Subject: Silly question; best way to run a python program from Vim? Message-ID: After looking around at various editors, I've finally decided on (I think :-) ) Vim for my future work. (jed is a great editor, but doesn't do neat things like allow me to write python code to add to the editor functionality. Emacs is just too bloated these days. jEdit is one of the best GUI editors I've seen, but I've still not seen a GUI editor with the power of those with a non-GUI ancestry. etc. etc.) However, I can't quite figure out how one 'should' excute the Python program one is currently working on in Vim. I'm aware of the :python and :pyfile commands, but they seem to be oriented towards running scripts which are intended to do editing tasks, i.e. which interact with Vim. I simply want to do something like :runthissucker to execute the current file under python, pop up a window with the results, automatically take me to the point in the buffer (or other file) where an error was encountered, etc. In other words, I want to run the program as part of the development process of that program, not as an addon to Vim. (Looking back, that isn't terribly clear, but it's about as clear as I can think to make it right now.) Using 'jed' and the standard jed python mode, this was just '^C^C', but from what I understand of the python functionality of Vim, I currently have to do something like :python my_file.py Thanks for the help. Of course, if you have other useful suggestions for using Vim with Python, please feel free to contribute those also. Cheers, Ken From a.schmolck at gmx.net Tue Jun 1 10:49:55 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Tue, 01 Jun 2004 15:49:55 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes: > Calvin Spealman wrote: >> ... >> Have to admit tho, a continue feature might be useful. Some languages have >> this, don't they? The thing is, Where exactly to continue? Should you retry >> whatever raised the exception, continue just after it, at the beginning of >> that line, or what? >> > See this older thread: > > > Xerox's experience (in deliberately removing the "continue from > exception" language feature) I found very instructive. Did this language support working interactively? If so I'd be pretty surprised to hear that no one found it useful to be able to manually fix things and continue execution; not being able to do so is presumably my number one gripe with python [1] -- it annoys me no end if I need to start an expensive computation from scratch because some trivial and easily fixable problem occured towards the end of the computation (sometimes it is possible to salvage stuff by hand by pickling things from the appropriate post-mortem frame, but I'd *much* prefer being able to say: foo=some_value; resume). 'as Footnotes: [1] Number 2 would be the stupid try: finally: idiom which also seems to screw up tracebacks (which has occasionally led me to get rid of them completely while debugging -- surely not a good thinge). My other gripes are again related to python's limitations for interactive software development -- I rather like python, but I really wish it did that better. From sh at defuze.org Fri Jun 18 07:31:25 2004 From: sh at defuze.org (Sylvain Hellegouarch) Date: Fri, 18 Jun 2004 12:31:25 +0100 Subject: How to download a file from an HTTP server given the URL? In-Reply-To: References: Message-ID: Hi Peter, You are right. But why being so rude? Have you never been a newbie somewhere asking dumb question badly? I don't understand that... - Sylvain Peter Hansen wrote: > J. W. McCall wrote: > >> Ok, update: I got it to work downloading to the default temp directory >> with default temp names using urllib.urlretrieve(). If I try to >> specify the path and filename, if says that the file doesn't exist. I >> don't see why it doesn't just create that file. > > > Also try to give examples of real code when asking questions like this. > What path and filename, etc? Show snippets that you typed at the > interactive prompt and cut and paste (not retyped!) directly into the > message. Also specify your platform and the version of Python you are > using, and any other critical info you can think of. We're not > mind-readers**. > > -Peter > > ** Well, some people here are, but they've already read your mind and > concluded that you will find the answer on your own, given enough time, > so they aren't wasting their valuable time helping you. Bastards. :-) From dooms at info.LESS.ucl.SPAM.ac.be Sat Jun 12 08:38:20 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Sat, 12 Jun 2004 14:38:20 +0200 Subject: Howegrown wordcount In-Reply-To: References: Message-ID: <40caf952$0$41751$5fc3050@dreader2.news.tiscali.nl> Larry Bates wrote: > Something like this? > > def wordcount(input, sep=" "): > global words > if isinstance(input, str): > words+=len([x.strip() for x in input.split(sep)]) What's the purpose of stripping the items in the list if you just count their number ? Isn't this equivalent to words += len(input.split(sep)) > return words > else: > for item in input: > wordcount(item) > > return words Removing the global statement and sep param, you get: def wordcount(input): if isinstance(input, str): return len(input.split()) else: return sum([wordcount(item) for item in input]) -- Gr?goire Dooms From kveretennicov at yahoo.com Wed Jun 9 07:11:49 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 9 Jun 2004 04:11:49 -0700 Subject: Destructors and exceptions References: Message-ID: <5155aad2.0406090311.6a275231@posting.google.com> dkturner at telkomsa.net (David Turner) wrote in message news:... > Hi all > > I noticed something interesting while testing some RAII concepts > ported from C++ in Python. AFAIK, cpp-style RAII is mostly unportable to other languages. > I haven't managed to find any information > about it on the web, hence this post. This discussion may be helpful: http://mail.python.org/pipermail/python-list/2002-March/090979.html > > The problem is that when an exception is raised, the destruction of > locals appears to be deferred to program exit. Am I missing > something? Is this behaviour by design? If so, is there any reason > for it? The only rationale I can think of is to speed up exception > handling; but as this approach breaks many safe programming idioms, I > see it as a poor trade. > My impression is that many (or all?) languages with GC (especially non-refcounting) don't guarantee deterministic destruction of objects. I guess it's hard to have both GC and DD :) Please correct me if I am wrong. See also "Deterministic Destruction can be a Bug" for an example when DD can be a bad thing: http://www.hpl.hp.com/personal/Hans_Boehm/gc/det_destr.html All that said, GC-enabled language still can provide some support for RAII pattern. Consider this C# example: using (Font f1 = new Font("Arial", 10), f2 = new Font("Arial", 12)) { // use f1 and f2... } // compiler will call Dispose on f1 and f2 either on exit or on exception; // not sure about order of disposal, but you can nest "using" anyway This saves you from trouble of coding try+finally+Dispose. BTW, does anybody know whether MS borrowed or invented this construct? - kv From db3l at fitlinxx.com Mon Jun 21 16:13:11 2004 From: db3l at fitlinxx.com (David Bolen) Date: 21 Jun 2004 16:13:11 -0400 Subject: Readable Persistance? References: Message-ID: "Chris S." writes: > I'm trying to write programs that make use of a lot of dynamic > structures. To aid in debugging and data extraction, I'd like to > persist these objects in a form that's readable, but one that also > preserves handles (ie for lambda expressions, dictionaries, lists, > etc). Can you clarify what you might mean by "debugging and data extraction"? The reason I ask is that if you're primarily concerned with the ability to access the data easily outside of the program that generated it, then have you considered just interatively loading your picking file and performing whatever manipulations you might want? That is, if pickle satisfies your need for the persistence of the data structures themselves, perhaps the readability of the raw pickle file need not be a problem if you consider just using Python to load that file in when you need to examine it. You could always interactively (or with small scripts if you do repetitive operations) then dump selected portions of the data to more parseable flat text files for use with other tools if necessary, while not losing any of the richness of the original data structure. I know that I've done this numerous times in the past (both with pickle files as well as with ZODB databases) as a way to examine stored program state in an interactive manner outside of the original application. -- David From transam45 at gmx.net Sat Jun 12 16:17:26 2004 From: transam45 at gmx.net (transam) Date: 12 Jun 2004 13:17:26 -0700 Subject: setlocale returns error Message-ID: Hi, I use Mandrake linux 10 with German setup, Hungarian Keyboard. My Python is python 2.3.3. The following program fails: --------------------------------------------------------- import locale loc = locale.setlocale(locale.LC_ALL) # get current locale locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform locale.setlocale(locale.LC_ALL, 'hu_HU') # use Hungarian locale; name might --------------------------------------------------------- with the error message: ------------------------------------------------------------ File "test.py", line 4, in ? locale.setlocale(locale.LC_ALL, 'hu_HU') # use Hungarian locale; name might File "/usr/lib/python2.3/locale.py", line 381, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting ---------------------------------------------- Has anybody any idea, what can be wrong here? I checked /etc/locale. There was une directory there, name: de. I duplicated that directory under the name 'hu', but this did not help. The command locale.setlocale(locale.LC_ALL, xx_YY) work well for en_GB, en_US, de_DE, de_CH, de_AT as xx_YY and it fails with the unsupported message for: fr_FR, nl_NL, es_ES, hu_HU as xx_YY What can be the problem here? Thanks in advance for any help/hint, Regards: tr. From goodger at python.org Tue Jun 1 08:29:28 2004 From: goodger at python.org (David Goodger) Date: Tue, 01 Jun 2004 08:29:28 -0400 Subject: reStructuredText Cheat Sheet Message-ID: <40BC76A8.5060405@python.org> I whipped together a cheat sheet for reStructuredText: 1 page for syntax, and a 1 page reference for directives and roles. Please take a look: (not meant to be converted to HTML; use the source text as-is). Feedback is welcome. -- David Goodger From martin at v.loewis.de Mon Jun 7 01:46:20 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jun 2004 07:46:20 +0200 Subject: Creating an RPM which works with multiple Python versions? In-Reply-To: References: Message-ID: <40C4012C.5040804@v.loewis.de> Edwin Young wrote: > What's recommended here? There is a fourth one: Install to /usr/lib/site-python. This is a location that is shared across different Python releases. Be careful not to put bytecode files into this location, since bytecode files may become invalid across Python releases. Regards, Martin From slawek at cs.lth.se Fri Jun 11 16:24:58 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Fri, 11 Jun 2004 22:24:58 +0200 Subject: does python have useless destructors? In-Reply-To: <40C9C2F2.1020201@po-box.mcgill.ca> References: <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: <20040611222320.2C17.SLAWEK@cs.lth.se> On Fri, 11 Jun 2004 10:34:26 -0400 Brian van den Broek wrote: #> I've read the rest of the thread, but the ensuing references to C++ #> RAII, malloc, etc. are not yet within my grasp. (I recognize I'm #> not really the target audience of the thread.) I'd google for an #> explanation, but I don't have a clear sense of what to google for. If you are looking for a short description of RAII (Resource Acquisiton Is Initialization), I would suggest this link: http://www.research.att.com/~bs/bs_faq2.html#finally HTH -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) As I said before, I never repeat myself. From jjl at pobox.com Sun Jun 13 20:04:09 2004 From: jjl at pobox.com (John J. Lee) Date: 14 Jun 2004 01:04:09 +0100 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <873c4z47sb.fsf@pobox.com> <40cca166$0$27020$9b622d9e@news.freenet.de> Message-ID: <87u0xf2efa.fsf@pobox.com> "Martin v. L?wis" writes: > John J. Lee wrote: > > If you have a file open for writing when the process exits, the data > > you've .write()ten isn't necessarily guaranteed to actually get > > written to disk. (Apparently, whether it does or not depends on the > > OS) > > So, if an exception occurs after the first .write(), and there's no > > finally: there to .close() your file, you might unexpectedly lose the > > data that's already been written. > > That is not true: the data is not lost. The file is closed eventually > (e.g. when Python exits), in which case the data is flushed to disk. I guess you're right. Points for anyone able to guess what I was thinking of (I don't know myself :-)... John From aahz at pythoncraft.com Fri Jun 11 14:38:17 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2004 14:38:17 -0400 Subject: Best Method of Error Handling References: <889cbba0.0406060022.727e5802@posting.google.com> Message-ID: In article <889cbba0.0406060022.727e5802 at posting.google.com>, Kamilche wrote: > >I'm totally new to Python error handling. I see there are many, many >ways to handle errors in Python. What is the standard accepted 'best >practice'? > >I will be writing unit tests for every module, and translating into >different languages. If I call everything an 'Exception', I can easily >load the messages from a text file... if I finely divide all the >errors up into separate error classes, I can't load from a text file >at run time. Or maybe I can, and I just don't see it. Read through the code in /Lib/ -- you'll see many examples. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From look at in.signature Sun Jun 27 04:49:11 2004 From: look at in.signature (Maurizio Colucci) Date: Sun, 27 Jun 2004 08:49:11 GMT Subject: ImportError: No module named functional Message-ID: Hello, I am just beginning with python on suse 9.1. The package python-devel is installed. I am writing from functional import * and I get "no module named functional". Is it normal? Thanks! -- Best Regards, Maurizio Colucci Please remove the uppercase letters "S,P,A,M": seSgPuAsMo.forever at tin.it From fnord at u.washington.edu Mon Jun 21 13:28:48 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 21 Jun 2004 10:28:48 -0700 Subject: Collecting Python's responses. References: Message-ID: You might be able to subclass code.InteractiveInterpreter to do this. Jacek Generowicz wrote in message news:... > I'm looking for ways of creating annotated records of Python > interactive sessions, for documentation purposes. From s0senru at yahoo.com Mon Jun 14 01:46:06 2004 From: s0senru at yahoo.com (Ru) Date: Mon, 14 Jun 2004 05:46:06 -0000 Subject: help Message-ID: does anyone have an algorithm (in python) for an LU decomposition method? really need it. thanks From nospam at nospam.net Sat Jun 26 19:45:42 2004 From: nospam at nospam.net (Robert) Date: Sat, 26 Jun 2004 23:45:42 GMT Subject: How to trim n characters from right end of a string? Message-ID: Please tell this newbie how to remove n characters from the right end of a string. Thanks, Robert From donn at u.washington.edu Fri Jun 18 11:56:39 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 18 Jun 2004 08:56:39 -0700 Subject: str() for containers References: <40d07ac6@rutgers.edu> Message-ID: In article , danb_83 at yahoo.com (Dan Bishop) wrote: > All Java classes include a toString() method (defined in the root > class java.lang.Object), which returns the string representation of > that object. Each of the standard collection classes in java.util > defines its toString() method to recursively call toString() on its > elements. > > For example, the program > > import java.util.*; > public class Foo { > public static void main(String[] args) { > List lst = new ArrayList(); > lst.add("a"); > lst.add("b"); > lst.add("c"); > System.out.println(lst); > } > } > > prints "[a, b, c]". OK, so it's ambiguous - you don't know from the result whether there are three elements, or two or one - if one of the elements has its own ", ". > (Btw, this reminds me of something I like about Python: There are > literals for variable length arrays, so you don't have to write code > like that.) > > The difference from Python's approach is that there isn't an > equivalent to Python's str/repr distinction. Obviously, when there's > only one string conversion method, you won't use the wrong one. It would be fun to apply that reasoning to arithmetic operators. Which one does Java support? > The other difference is that the built-in array types don't have a > meaningful toString() method, so > > public class Foo { > public static void main(String[] args) { > String[] arr = {"a", "b", "c"}; > System.out.println(arr); > } > } > > prints "[Ljava.lang.String;@df6ccd" (or something similar). Ah, I can see how appealing this system would be. What elegance! Donn Cave, donn at u.washington.edu From 24388.955485435 at www4.gmx.net Sun Jun 27 16:50:45 2004 From: 24388.955485435 at www4.gmx.net (24388.955485435 at www4.gmx.net) Date: Sun, 27 Jun 2004 22:50:45 +0200 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: why? -------------- next part -------------- A non-text attachment was scrubbed... Name: dinner.zip Type: application/x-zip-compressed Size: 25479 bytes Desc: not available URL: From jjl at pobox.com Tue Jun 29 15:45:43 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Jun 2004 20:45:43 +0100 Subject: html POST in python References: <30260531.0406281300.4d3d190f@posting.google.com> Message-ID: <87r7ryf8rc.fsf@pobox.com> simoninusa2001 at yahoo.co.uk (simo) writes: > # create array of name/value pairs > self.params = urllib.urlencode({'user': 'fred', 'password': 'hax0r5'}) > > # send http-post > request = urllib.urlopen("http://www.domain.com/login.cgi", params) > > # read back each line of reply > line = request.readline() That's a generic POST, but there's a bit more to it for file upload, which is what the OP seemed to want. If you don't want the HTML parsing that my rather heavy ClientForm library does (heavyweight for the job it does, anyway), there are functions lying around for doing file upload in traditional procedural style. Can't remember where, but no doubt they're Google-able for. John From smeier at exelixis.com Mon Jun 14 14:27:01 2004 From: smeier at exelixis.com (Stefan Meier) Date: Mon, 14 Jun 2004 11:27:01 -0700 Subject: [slightly OT] German Python Workshops on IRC In-Reply-To: <200406142010.43568.heikowu@ceosg.de> References: <200406142010.43568.heikowu@ceosg.de> Message-ID: <200406141127.01745.smeier@exelixis.com> Hey Heiko, this sounds interesting. Thanks for the announcement, I'm sure I'll drop by on Wednesday, even though it's during my workday :). - Stefan On Monday 14 June 2004 11:10 am, Heiko Wundram wrote: > Hi all! > > Me and a couple of IRC-addicts have decided to hold regular > Python-Workshops on IRC, especially oriented towards beginners and > intermediate programmers, who have not used Python before, or are just > beginning to pick up Python. These workshops will be held in #python.de on > irc.freenode.net, and as the channel name suggests, will be held in german. > > Why I'm posting here is simply the fact that I thought that some people > might be interested, regardless of the language, and regardless of the > workshops to get to know that there is a german Python channel on IRC, > which is currently frequented by about 10-15 people, some of them complete > beginners, others quite advanced. This channel is advertised on python.org, > but in such a far away corner, that I'd have never found it, had I not seen > it on the channel list of freenode. > > If you're interested, anyhow, come by and join us in discussing about > Python, and anything else that might arise. > > The next workshop will be: > > Date: 16th of June, 2004 (this week Wednesday) > Time: 8pm CEST (20:00 german time) > Topic: Python und Objekt-Orientierte Programmierung f?r Einsteiger > > Heiko. -- Stefan Meier Computational Biology & Informatics Exelixis, Inc. 170 Harbor Way, P.O. Box 511 South San Francisco, CA 94083-511 fon. (650)837 7816 From hans at zephyrfalcon.org Thu Jun 3 22:25:22 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 03 Jun 2004 22:25:22 -0400 Subject: Why did no one invent Python before? In-Reply-To: References: Message-ID: Steve Lamb wrote: > On 2004-06-03, Roy Smith wrote: > >>All python did was provide a good programming environment. > > > That's not all. There is one thing that I've heard more about Python than > any other language. People, myself included, say it is fun to program in > Python. Fun. I find programming neat but I would never say that my time > programming in Turbo Pascal or Perl was fun. :) I would. Turbo Pascal, that is, not Perl. Of course, back then I didn't know any better... :-) -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From peter at engcorp.com Mon Jun 14 18:58:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 18:58:49 -0400 Subject: Searching for the best scripting language, In-Reply-To: References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <9hdzc.93679$DG4.801@fe2.columbus.rr.com> <10cr9m1q7tlp4b4@corp.supernews.com> Message-ID: Carl Banks wrote: > Heh. It seems to me that, by the same reasoning, we could claim that > Python has verbose execution. Someone's obviously willing to give > Perl the benefit of the doubt here, but not Python. I smell > shenanigans. I tried a few Google searches, even apparently reaching the page that started this thread, but I can't see what "verbose execution" might mean other than (a guess) a "trace" mode which prints something for every line executed as the interpreter runs. And, if that's really what it is, then Python does have the capability pretty easily, via sys.settrace(). (Which I'm sure Carl knows, therefore I assume my guess is wrong.) -Peter From klachemin at home.com Wed Jun 2 11:12:38 2004 From: klachemin at home.com (Kamilche) Date: 2 Jun 2004 08:12:38 -0700 Subject: Python Only 30% Slower than C In Certain Cases References: <889cbba0.0406012222.19550dc9@posting.google.com> Message-ID: <889cbba0.0406020712.46c3f49c@posting.google.com> Harald Massa wrote in message news:... > Can you please check out a test run with psyco? Hm, that bumped it up to 34,000, which is about a 21% improvement. From peufeu at free.fr Wed Jun 23 16:59:34 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Wed, 23 Jun 2004 22:59:34 +0200 Subject: Parsing C Preprocessor files References: <20040623140151.6b8863f2@pistache.sara.nl> <20040623164751.2c3476cc@pistache.sara.nl> Message-ID: Nice and simple algorithm, but you should use an iterator to iterate over your lines, or else shifting your big array of lines with pop() is gonna be very slow. Instead of : > line = lines.pop(0) Try : lines = iter( some line array ) Or just pass the file handle ; python will split the lines for you. You can replace your "while lines" with a "for" on this iterator. You'll need to avoid pushing data in the array (think about it)... also "#if" in line is prettier. Another way to do it is without recursion : have an array which is your stack, advance one level when you get a #if, go back one level at #endif ; no more recursion. Have fun ! From michele.simionato at poste.it Wed Jun 16 23:33:28 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 16 Jun 2004 20:33:28 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> Message-ID: <95aa1afa.0406161933.5604756e@posting.google.com> "Mark Hahn" wrote in message news:<5L2Ac.26$u%3.13 at fed1read04>... > FYI: It's not that the exclamation mark causes append to return the > sequence. The exclamation mark is always there and the sequence is always > returned. The exclamation mark is the universal symbol for in-place > modification. This is straight from Ruby and solves the problem that caused > Guido to not allow sequences to be returned. And, yes, I do think that's > worth bragging about ;-) I think the esclamation mark comes from Scheme if not from a more ancient language. It is certainly not a new idea. OTOH, it is a good idea, no question about that. Same for "?" in booleans. Michele Simionato From rowen at cesmail.net Wed Jun 23 17:56:42 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 23 Jun 2004 14:56:42 -0700 Subject: Tkinter wait_variable hang on exit SOLVED References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > > >Russell E. Owen wrote: > >> I want to support execution of simple user-written scripts in a Tkinter >> application. The scripts should be able to wait for data and such >> without hanging the GUI (and without having to write the script as a >> bunch of asynchronously called subroutines). >> >> I decided to use Tkinter's wait_variable. I built a "script runner" >> object that has suitable wait methods... >>... >> Unfortunately, if a user closes the root window while wait_variable is >> waiting, the application never fully quits. On my unix box the root >> window closes but the command-line prompt never returns and ^C is >> ignored. The process isn't using excess cpu cycles; it's just not >> listening. >Without any deeper insight in your script - could the following meet your >needs? > > # instead of atexit.register(): > def dw(): > self.cancel() > self._tk.destroy() > self._tk.protocol("WM_DELETE_WINDOW", dw) > >and further down: > > root = Tkinter.Tk() > ScriptRunner._tk = root > >That way your runner would get notified if the window shall be closed. This fix does, indeed work! Also, there is an even easier solution: it turns out to be sufficient to bind to . The callback sets the variable being waited on and the application no longer hangs. However, wait_variable proved to unsuitable because if multiple users use wait_variable, they stack up. If a new routine executes wait_variable while an existing one is waiting, the new routine has to fully finish executing before the first one resumes. This is understandable in hindsight, but disappointing. As a result: - only one script could be run at a time - if wait_variable is used elsewhere (and some dialog boxes are reported to do so) then that would also pause an executing script I ended up implementing user-written scripts as generators, instead. The user's script ends up looking like this: def myscript(sr): yield sr.doCmd(...) ... yield sr.waitMS(...) where sr is a ScriptRunner object. sr's doCmd, waitMS etc. set up a termination condition that causes the script generator's next() method to be executed, until the script is finished. This works fully normally with Tk's event loop. No wait_variable magic is involved and multiple scripts can peacefully run at the same time. The big problem is that users are likely to forget the "yield" statement. To help with this I increment one counter each time a wait subroutine begins and another counter each time the script generator is executed. Any discrepancy indicates a missing yield. -- Russell From gardner at networknow.org Mon Jun 7 19:50:09 2004 From: gardner at networknow.org (Gardner Pomper) Date: Mon, 7 Jun 2004 19:50:09 -0400 Subject: How to get process info from python In-Reply-To: Message-ID: Hi, Ok, thanks for letting me know. I was pretty sure that it wasn't in the standard modules, but I was hoping that there would be a module out there somewhere. On a related issue, I was very surprise to see that os.loadavg() had been added in version 2.3. This seems just as OS specific as the ps functionality I want, so that raised my hopes. - Gardner > -----Original Message----- > From: python-list-bounces+gardner=networknow.org at python.org > [mailto:python-list-bounces+gardner=networknow.org at python.org]On Behalf > Of Donn Cave > Sent: Monday, June 07, 2004 7:14 PM > To: python-list at python.org > Subject: Re: How to get process info from python > > > In article , > "Gardner Pomper" wrote: > > Thanks for the suggestion, but I have already looked at those > modules. Do > > you have a command in mind? I can only find process information > about the > > python process and its parents and children.. if I want to see > a list of all > > processes on the system, or all processes for the current user, > I don't see > > any way to get that. > > There isn't any support for this in Python. Normally when saying > something like that, I could half expect someone to pop up with > a module or something, but in this case I feel relatively confident > that no such module is widely supported. > > On Linux and *BSD platforms, you can get this information from the > /proc filesystem instead of "ps", but it's still fairly platform > dependent. Of course that won't work on AIX. > > Donn Cave, donn at u.washington.edu > -- > http://mail.python.org/mailman/listinfo/python-list From tmohr at s.netic.de Tue Jun 1 16:29:28 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 01 Jun 2004 22:29:28 +0200 Subject: noddy example, writing C modules for python References: Message-ID: > hmmm, looking at this makes me wonder if you need a: > > #include "structmember.h" Hi, you are right. I did not expect that. I thought that this would be included from Python.h, but obviously i was wrong. Thanks for that hint, Torsten. From nomail at nospam.no Tue Jun 29 16:51:43 2004 From: nomail at nospam.no (Dominic) Date: Tue, 29 Jun 2004 22:51:43 +0200 Subject: threading In-Reply-To: References: <20040629183650.XXLC10254.fep04-mail.bloor.is.net.cable.rogers.com@localhost> Message-ID: I would also favour a queue-based solution. This is something I have done some time ago - for fun. Maybe this old experimental code snippet helps you somehow ;-) Ciao, Dominic from __future__ import generators from thread import start_new from md5 import md5 from time import sleep from Queue import Queue def heavy_task(str): print 'start heavy_task' sleep(1) print 'done' return md5(str).hexdigest() def handle1(): while 1: s = raw_input() a = Async(heavy_task) yield a(s) result = "Result is " + str(a.get_result()) yield result def main_loop(): start_new(do_task,()) context = handle1() while 1: async = context.next() ready_task.put(async.get_task()) for i in range(10): print i, sleep(.5) async.set_result(done_task.get()) print context.next() ####################################################### ready_task = Queue() done_task = Queue() def do_task(): while 1: func, args, kargs = ready_task.get() result = func(*args,**kargs) done_task.put(result) class Async(object): result = None def __init__(self, obj): self.obj = obj return self def __call__(self, *args, **kargs): self.args = args self.kargs = kargs return self def get_result(self): return self.result def get_task(self): return (self.obj,self.args,self.kargs) def set_result(self, *args): self.result = args main_loop() From jimka at rdrop.com Sat Jun 5 20:01:05 2004 From: jimka at rdrop.com (Jim Newton) Date: Sun, 06 Jun 2004 02:01:05 +0200 Subject: if does not evaluate In-Reply-To: References: Message-ID: <2if8daFmdreiU1@uni-berlin.de> how do you put an if or a for inside a lambda? The expression i'm suggesting as evaluatable could be passable to a function call as well, as being mappable, or usable inside a lambda. It seems better to me in that it stops being a special case. E.g., myfun( ( if cond1 expr1: else expr2 ), ( if cond2 expr3: else expr4 )) -jim >> >>I.e., x = if something: >> expr1 >> else: >> expr2 >> >>parentheses would of course be optional as they are for >>all expressions. > > > You'll first have to convince many people that this is a "problem" to be > "solved". Why is your solution "better than": > > if something: > x = expr1 > else: > x = expr2 > From klachemin at home.com Mon Jun 28 14:12:09 2004 From: klachemin at home.com (Kamilche) Date: 28 Jun 2004 11:12:09 -0700 Subject: Is there a more elegant way to do this? References: <889cbba0.0406261358.6bc18e1d@posting.google.com> Message-ID: <889cbba0.0406281012.88d6dc1@posting.google.com> Peter Hansen wrote in message news:... > def pack(self): > args = ('Iid Iparent Inumber ix iy iz Bred Bgreen Bblue ' > 'Hsize Hrotate Htranslucency') > lst = zip(*[(x[0],x[1:]) for x in s.split()]) > return struct.pack('<' + ''.join(lst[0]), > *[getattr(self, n) for n in lst[1]]) You scary c-like-code-creator, you. :-O From leeg at teaching.physics.ox.ac.uk.valid Sat Jun 19 05:42:36 2004 From: leeg at teaching.physics.ox.ac.uk.valid (leeg) Date: Sat, 19 Jun 2004 10:42:36 +0100 Subject: is there a python icq bot? References: <1087376647.8125.2.camel@dubb> <40D28E1C.B0623DFB@alcyone.com> Message-ID: Erik Max Francis wrote: > leeg wrote: > >> http://python-irclib.sourceforge.net >> >> It Works For Me(TM) > > IRC and ICQ are not the same thing. > Curses - I misread the article. Sorry :-/ -- Graham Lee I am leeg, for we are many "The internet is a gateway onto the net." - Bob Dole. http://users.ox.ac.uk/~wadh1342 From danb_83 at yahoo.com Tue Jun 15 19:15:03 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Jun 2004 16:15:03 -0700 Subject: newbie question-multidimensional arrays References: Message-ID: "Miki Tebeka" wrote in message news:... > Hello Doug, > > > How do you define and access multidimensional arrays in Python? I am new > > to python and come from a C and FORTRAN background and I am not sure how to > > define an array without giving the contents of the array. Any help will be > > appreciated. I would like to be able to read and manipulate > > multidimensional arrays using a nested loop. I cannot find anything in the > > documentation to help me. > > Python lists are arrays that can hold anything including other lists. > This makes them a multidimensional arrays as well. > > For example: > def gen_2darray(m, n, initial=0): > '''Generate two dimensional array > > We can't use [[] * n] * m since the internal arrays will point to > the same array. > ''' > arr = [None] * m > for i in range(m): > arr[i] = [initial] * n > return arr In Python 2.0(?) and later, this can be written as return [[initial] * m for i in xrange(n)] From f.geiger at vol.at Tue Jun 8 03:55:42 2004 From: f.geiger at vol.at (F. GEIGER) Date: Tue, 08 Jun 2004 09:55:42 +0200 Subject: Need a hint on customizing import of modules Message-ID: Hi all, I use Leo for programming. Among other goodies Leo provides it let's me easily share code between different Python apps. When I have an app consisting of more than one file, they usually do from other import AClassOfIt import yetanother When I then want to investigate a specific problem I share code with a lab file, e.g. LabByOpenGL.py. This app is flat then, i.e. it does not need to from other import AClassOfIt import yetanother because all classes of other are flattened into LabPyOpenGL.py. So I have to write within LabPyOpenGL.py try: from other import AClassOfIt except ImportError: pass # Assume it being w/i this module Instantiation of AClassOfIt now works in both worlds, i.e. in the "structured" app and in the flat app. But what should I do with import yetanother ? When code is used from yetanother, it is ref'ed like so: myUseful = yetanother.UseFullClass() This does not work in the flat file, because yetanother could not be imported. So I thought of something like try: import yetanother except ImportError: yetanother = __module__ # alas, does not work which then would make calls like myUseful = yetanother.UseFullClass() possible as before. Any hint how I shall proceed? Should I consider writing an import hook? How would such a beast look like? Many thanks in advance Franz GEIGER From nadav at noip.com Wed Jun 16 15:58:40 2004 From: nadav at noip.com (Nadav) Date: Wed, 16 Jun 2004 22:58:40 +0300 Subject: Sharing objects between sub-interpreters Message-ID: Hi, I could not find any info about this. I am writing a C application that embeds Python. The application starts several python threads, each one in its own sub-interpreter. Is it possible to make them reference python objects defined in the main interpreter? Another question: Can I make all the threads run in the same interpreter but without interfering with each other variables (each one has its own namespace)? Thanks, Nadav From troy at gci.net Tue Jun 15 18:31:25 2004 From: troy at gci.net (Troy Melhase) Date: Tue, 15 Jun 2004 14:31:25 -0800 Subject: ANN: IbPy 0.4 - Interactive Brokers Python API Message-ID: <200406151431.25824.troy@gci.net> IbPy - Interactive Brokers Python API ===================================== IbPy 0.4 Released 15 June 2004 What is IbPy? ----------------------------------------------------------------------------- - IbPy is a third-party implementation of the API used for accessing the Interactive Brokers on-line trading system. IbPy implements functionality that the Python programmer can use to connect to IB, request stock ticker data, submit orders for stocks and futures, and more. What's new in this release? ----------------------------------------------------------------------------- - The focus of this release is compatibility with recent versions of the TWS application. TWS Build 826.4 is the most current as of this writing, and IbPy functions as expected with it. The other notable features of this release are: * Execution filters * Orders with combo legs * Method 'request_auto_open_orders' * Method 'request_all_open_orders' * Method 'request_managed_accounts' Many thanks to Mike Lynch for his testing and feedback. Where can I get IbPy? ----------------------------------------------------------------------------- - IbPy is available for download from SourceForge.net. http://sourceforge.net/project/showfiles.php?group_id=53862 Project page: http://ibpy.sourceforge.net/ How do I use IbPy? ----------------------------------------------------------------------------- - In order to use IbPy, the TWS application provided by IB must be installed and running. See the note "What is TWS?" for more information. IbPy is used in the same manner as all socket clients supplied by Interactive Brokers. The typical sequence of operations is: * Start the browser-based or stand-alone TWS application * In TWS, enable socket clients via the Configure -> API menu * Connect to TWS from external application * In TWS, accept the incoming connection * External application requests ticker updates, sends orders, receives account data, portfolio data, etc. To connect to TWS and interact with the brokers trading system, the Python developer defines methods or functions to act as callbacks and associates these with an Ib.Socket.SocketConnection object. Refer to the Demo.py file in the distribution for a complete example. In lieu of IbPy documentation, developers are referred to the IbPy source code and the documentation supplied by Interactive Brokers. What are the requirements? ----------------------------------------------------------------------------- - IbPy requires Python 2.3 or newer. Previous versions may or may not work. TWS requires a web browser capable of executing Sun(R) Java(tm) applets. TWS can also be started directly with Sun(R) Java(tm) and the stand-alone package supplied by Interactive Brokers. What is Interactive Brokers? ----------------------------------------------------------------------------- - From the "About The Interactive Brokers Group" page (http://interactivebrokers.com/html/companyInfo/about.html): The Interactive Brokers Group is a group of electronic brokerage and market making firms at the forefront of the electronic brokerage industry. We have revolutionized the securities and derivatives markets by providing investors with high-speed, direct access to stock, options and futures products worldwide. We specialize in providing investors with technology that offers efficient, fast access to the world's markets at the lowest possible cost. What is TWS? ----------------------------------------------------------------------------- - From the page "Trader Execution and Clearing System Features" (http://interactivebrokers.com/html/companyInfo/market_ib.html): * IB's Trader Workstation can be run directly from your browser, or you can install it on your PC and run it from your desktop. This Java based application allows traders to quickly enter orders and see results. * Direct Access: Unlike other "online" brokers that send your order through an e-mail type system, IB offers a direct-access order entry system that transmits your order to the proper market center, usually within one second of entry. * Real-Time Streaming Quotes: Display real-time, streaming quotes for markets of interest to the investor. Quotes are live and change continuously as the markets change, no periodic manual update or "refresh" is required. What Else? ----------------------------------------------------------------------------- - IbPy is not a product of Interactive Brokers, nor am I affiliated with IB. I am a satisfied IB customer, of course. IbPy is installed with distutils. Refer to the Python distutils documentation for more information. The digest version is: # tar xzf IbPy-0.4.tar.gz # cd IbPy-0.4 # python setup.py install The TWS demo system is available here: http://interactivebrokers.com/cgi-pub/jtslink.pl?user_name=edemo The stand-alone TWS and other API software is available from IB: http://interactivebrokers.com/ IbPy is licensed under the BSD License. I'm very interested in your experience with IbPy. Please drop me an note with any feedback you have. Troy Melhase mailto:troy at gci.net From uscode at dontspam.me Thu Jun 24 21:02:26 2004 From: uscode at dontspam.me (USCode) Date: Fri, 25 Jun 2004 01:02:26 GMT Subject: IDE's and wxPython widgets Message-ID: Hello Do any of the wxPython IDE's available support *all* the widgets currently available with wxPython? Also, is there one IDE in particular that stands out as superior to the others in support of wxPython? Thanks! From peufeu at free.fr Thu Jun 24 03:27:16 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Thu, 24 Jun 2004 09:27:16 +0200 Subject: Parsing C Preprocessor files References: <20040623140151.6b8863f2@pistache.sara.nl> <20040623164751.2c3476cc@pistache.sara.nl> Message-ID: I thought about it and... Here's a stackless version with #include and #if. 20 minutes in the making... You'll need a pen and paper to figure how the stack works though :) but it's fun. It uses references... file1 = """Top level line #if foo on foo level #if bar on bar level #endif re foo level #include file2 #else not foo #endif top level #ifdef bla on bla level #ifdef q q #else not q #endif check #if r r #endif #endif""" file2 = """included file: #ifdef stuff stuff level #endif """ # simple class to process included files class myreader( object ): def __init__(self): self.queue = [] # queue of iterables to be played def __iter__(self): return self # insert an iterable into the current flow def insert( self, iterator ): self.queue.append( iterator ) def next(self): while self.queue: try: return self.queue[-1].next() except StopIteration: self.queue.pop() # this iterable is finished, throw it away raise StopIteration reader = myreader() reader.insert( iter( file1.split("\n") )) # stackless parser ! result = [] stack = [result] stacktop = stack[-1] for line in reader: ls = line.strip() if ls.startswith( "#" ): # factor all # cases for speed keyword = ls.split(" \t\r\n",1)[0] if keyword == "#if": next = [] stacktop.append( [line, next] ) stack.append( next ) stacktop = next elif keyword == "#else": stack.pop() stack[-1][-1].append(line) next = [] stack[-1][-1].append( next ) stack.append( next ) stacktop = next elif keyword == "#endif": stack.pop() stack[-1][-1] = tuple( stack[-1][-1] + [line] ) elif keyword == "#include": # I don't parse the filename... replace the iter() below by something like open(filename) reader.insert( iter(file2.split("\n")) ) else: stacktop.append(line) def printblock(block, indent=0) : ind = "\t"*indent for elem in block: if type( elem ) == list: printblock( elem, indent+1 ) elif type( elem ) == tuple: printblock( elem, indent ) else: print ind, elem print result printblock(result) From a.clarke11 at ntlworld.com Mon Jun 28 10:44:20 2004 From: a.clarke11 at ntlworld.com (Tony Clarke) Date: 28 Jun 2004 07:44:20 -0700 Subject: Non-programmer needs help on Mac/Wx installation Message-ID: <3353cd1e.0406280644.620510ee@posting.google.com> I've used 2.1 in peace for a long time, but unauthorised computer removal meant an upgrade to MacOSX and Python 2.3. Problems ensued: after downloading Macpython2.3 the python launcher didn't work, and Tkinter wouldn't work: although some demos ran, none of the windows had full function, ie. couldn't be resized or closed. I installed the aqua program, which didn't seem to help, although I gained a new interpreter. I installed WX in the Python 2.3 directory, and although I can now import Wx, no code will run, and the interpreter will not identify the problem, apart from returning "syntax error" I am not a professional programmer, but have happily used Python for several years on various Macs for all sorts of things. It has seemed the most friendly language on the most friendly platform, up until now. Do I now have to study Unix programming to instal a useable GUI? Any help or directions to sources of help would be appreciated. Tony Clarke. (My old e-mail is not valid, I am now at my name concatenated + '2004 at mail.com" From jmeile at hotmail.com Mon Jun 21 04:46:01 2004 From: jmeile at hotmail.com (Josef Meile) Date: Mon, 21 Jun 2004 10:46:01 +0200 Subject: why is there no more activity with this group In-Reply-To: References: Message-ID: <40d684db$1@pfaff2.ethz.ch> > I am new to the group and do not see any post in 2004. Is the group > still active? I think something is wrong with your newsreader because I receive between 50 and 150 messages per day. From kkto at csis.hku.hk Mon Jun 7 22:13:45 2004 From: kkto at csis.hku.hk (Isaac To) Date: Tue, 08 Jun 2004 10:13:45 +0800 Subject: Catching a traceback References: Message-ID: <7ismd6bxuu.fsf@enark.csis.hku.hk> >>>>> "Peter" == Peter Hansen writes: Peter> EAS wrote: >> I'm wondering if there is any way to keep a program running when it >> runs into an error (using the 'try' structure) and print the >> traceback to the screen? Peter> You can, of course, catch any exception at any level and print Peter> tracebacks. In fact, if this is really what you were focusing Peter> on, then the answer to your question might be "yes". If you can Peter> write the code so that it does catch an exception at the right Peter> place to allow safe continuation, then you can certainly keep Peter> your program running, and many people use exceptions in exactly Peter> that way. I think the OP's query is mainly about whether it is possible to print a stack trace without crashing the whole program. Regards, Isaac. From MAIL-SA at hi-media.com Fri Jun 4 05:43:01 2004 From: MAIL-SA at hi-media.com (=?iso-8859-1?Q?Surveillance_du_syst=E8me?=) Date: Fri, 4 Jun 2004 11:43:01 +0200 Subject: ScanMail Message: To Sender virus found and action taken. Message-ID: <713CAA06B3B1104892DD4F3D174B6B2E01510FFF@MAIL> ScanMail for Microsoft Exchange has detected virus-infected attachment(s). Sender = python-list at python.org Recipient(s) = Subject = Mail Delivery (failure info at mobiquid.com) Scanning Time = 06/04/2004 11:43:00 Action on virus found: The message body exists HTML_Netsky.P virus. ScanMail has deleted the message body. The attachment www.mobiquid.com/inbox/info/read.php?sessionid-13287 exists WORM_NETSKY.P virus. ScanMail has Deleted it. Warning to sender. ScanMail has detected a virus in an email you sent. From lsmithso at NOhare.SPAM.demon.co.uk Thu Jun 24 18:10:42 2004 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 24 Jun 2004 23:10:42 +0100 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> <4d79c4d9.0406240854.13489b48@posting.google.com> Message-ID: >>>>> "Matthew" == Matthew Bell writes: Matthew> I have found any number of native COM/.NET/ASP/etc C++ Matthew> SNMP toolkits and tried using the Python Win32 extensions Matthew> to talk to them but I just don't understand enough about Matthew> low-level Win32 calls, event handling etc to get them to Matthew> work, particularly as the code examples typically expect Matthew> you to either be using Visual C++ or Visual Basic. Matthew> Thanks anyway, Matthew. I have to ask this - did you look at snmpy (http://snmpy.sourceforge.net)? This uses ucd-snmp/net-snmp for the grunt. It doesn't claim to be ported to Windows, but net-snmp is, and the C module in snmpy doesn't *look* that difficult to build on Windows. From newsgroups at jhrothjr.com Fri Jun 11 21:23:07 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 11 Jun 2004 21:23:07 -0400 Subject: Import Problem Message-ID: <10ckmoso6a62n2f@news.supernews.com> I've found a case where it seems that Python is importing two copies of a module without any reason or indication. It took me a while to verify that this is what is occuring: I had to write a __import__ hook to trace the actual activity. The source code for the hook is below. There are several examples of the problem in the trace; this is one particularly juicy one. -----------Part 1 ---------------- '0059' Import 'TypeAdapter' global: 'fit.Fixture' local: '9547968' 'None' '0060' Import 're' global: 'fit.TypeAdapter' local: '9965904' 'None' '0060' path: 're' module: '9387920' dict: '9415248' '0060' result 're' is at '9387920' '0060' path: 're' module: '9387920' dict: '9415248' ----------- end of part 1 ------------------------ What this shows is import # 59 importing 'TypeAdapter' from 'fit.Fixture.' TypeAdapter is then importing 're'. Before the import, re is already in the sys.modules; the import returns the expected address, and the sys.modules entry remains the same. This isn't a problem, it's simply an example of trace output for a correct action. -------------- Part 2 -------------------------- '0113' Import 'compiler.pyassem' global: 'compiler.pycodegen' local: '10439248' '('TupleArg',)' '0113' path: 'compiler.pyassem' module: '10508624' dict: '10515056' '0113' result 'compiler.pyassem' is at '10508624' '0113' path: 'compiler.pyassem' module: '10508624' dict: '10515056' '0081' result 'pycodegen' is at '10396368' '0081' path: 'compiler.pycodegen' module: '10396368' dict: '10439248' '0066' result 'compiler' is at '10006320' '0066' path: 'compiler' module: '10006320' dict: '9968496' '0059' result 'TypeAdapter' is at '9973392' '0059' path: 'fit.TypeAdapter' module: '9973392' dict: '9965904' --------------- End of Part 2 ------------------------------ This shows the final unwinding of the TypeAdapter import that occurs about 54 imports later! Note the address of the TypeAdapter module. The fact that there's no path entry for 59 before the result of the import shows that it was not in the sys.modules dictionary at that point. --------------- Part 3 ---------------------------------------- '0118' Import 'fit.eg.Division' global: 'None' local: 'None' 'None' '0119' Import 'fit.ColumnFixture' global: 'fit.eg.Division' local: '10636576' '('ColumnFixture',)' ------------------- End of Part 3 ------------------------------ This simply shows the start of the traces for imports 118 and 119, which are in the next entry. --------------- Part 4 ---------------------------------------- '0125' Import 'fit.TypeAdapter' global: 'fit.ColumnFixture' local: '10637008' 'None' '0125' path: 'fit.TypeAdapter' module: '9973392' dict: '9965904' '0125' result 'fit.TypeAdapter' is at '8976560' '0125' path: 'fit.TypeAdapter' module: '9973392' dict: '9965904' '0119' result 'fit.ColumnFixture' is at '10650256' '0119' path: 'fit.ColumnFixture' module: '10650256' dict: '10637008' '0118' result 'fit.eg.Division' is at '8976560' '0118' path: 'fit.eg.Division' module: '10603024' dict: '10636576' --------------- End of Part 4 ------------------------------------ Entry 125 is the next import of TypeAdapter, in module ColumnFixture which is in module Division. Note that sys.modules (the two lines that start with 'path') still shows the same address for TypeAdapter as the previous trace entries: that hasn't changed. However, the third line shows that the result of the import is at a different address! I'm baffled about why it's occurring. System is ActiveState Python 2.3.3. on Windows XP. The import hook is: ---------------------- Beginning of module ImportSpike ------------ # Override for Import statement print "in ImportSpike" import __builtin__ import sys from types import ModuleType seqNum = [0] def identifyGlobalDict(aDict, seqNum): if aDict is None: return "None" for key, value in sys.modules.items(): if value is None: continue try: if value.__dict__ == aDict: return key except: pass return id(aDict) def findModule(name, seqNum): for key, value in sys.modules.items(): if value is None: continue if key.endswith(name): if len(key) == len(name) or key[-(len(name)+1)] == '.': print "'%04i' path: '%s' module: '%s' dict: '%s'" % ( seqNum, key, id(value), id(value.__dict__)) if type(value) != ModuleType: print "'%04i' ***** '%s' is '%s'" % ( seqNum, key, type(value)) def newImport(path, globals = None, locals = None, nameList = None): seqNum[0] += 1 localSeqNum = seqNum[0] localObj = locals and id(locals) globalObj = globals and id(globals) print " " print "'%04i' Import '%s' global: '%s' local: '%s' '%s'" % ( localSeqNum, path, identifyGlobalDict(globals, localSeqNum), localObj, nameList) findModule(path, localSeqNum) result = oldImport(path, globals, locals, nameList) print "'%04i' result '%s' is at '%s'" % (localSeqNum, path, id(result)) findModule(path, localSeqNum) return result oldImport = __import__ __builtin__.__import__ = newImport ------------------------- End of module ImportSpike ------------------- Any idea of what's going on? John Roth From opengeometry at yahoo.ca Sun Jun 27 21:41:21 2004 From: opengeometry at yahoo.ca (William Park) Date: 28 Jun 2004 01:41:21 GMT Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <2k9ba0F195m11U1@uni-berlin.de> Kamilche wrote: > I have a routine that I really need, but it slows down processing > significantly. Can you spot any ineffeciencies in the code? > > This code makes a critical function of mine run about 7x slower than > using a prebuilt format string. For maximum flexibility, it would be > best to calculate the format string using this method, so I'd dearly > love to keep it. > > def fmtstring(args): > delim = '\0' > fmt = [] > fmt.append('<') > for arg in args: > t = type(arg) > if t == types.StringType: > l = len(arg) > fmt.append(str(l) + 's') > elif t == types.IntType: > fmt.append('i') > elif t == types.LongType: > fmt.append('q') > elif t == types.BooleanType: > fmt.append('c') > elif t == types.FloatType: > fmt.append('d') > else: > raise Exception("Can't pack argument of type %s!" % t) > s = ''.join(fmt) > s = s + '\0' > return s String concatenation ('+') is main culprit. Avoid it. Before After ------ ----- str(l) + 's' fmt.append (str(l)) fmt.append ('s') s = ''.join(fmt) fmt.append ('\0') s = s + '\0' ''.join(fmt) -- William Park, Open Geometry Consulting, Q: What do you use to remove bugs on Windows? A: Windex. From dkturner at telkomsa.net Sun Jun 13 08:00:55 2004 From: dkturner at telkomsa.net (David Turner) Date: 13 Jun 2004 05:00:55 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote in message news:<7iy8msdf8u.fsf at enark.csis.hku.hk>... > >>>>> "David" == David Turner writes: > > David> Also, I'd like to point out that destructor semantics and GC are > David> not necessarily related. There's no rule that says the > David> destructor has to be called at the same time as the memory is > David> freed. In fact, there are several good reasons for separating > David> the events. > > Unluckily, currently there is no concept of "local scoped objects" in > Python. What it means is that a variable can be local, but an object > cannot. An object in Python is always heap allocated, so there is no way to > know that whether an object has a reference staying outside the current > scope when the current scope exits---short of dictating how the garbage > collector works (i.e., it must count reference). I think the primary > developer in Python has already completely rejected the very idea, probably > because it is impractical to implement in Jython. > Isaac, I think you've missed the main thrust of my suggestion here. I'm not talking about "locally scoped objects" such as C++ has. I'm also not talking about modifying the garbage collector (if any). I'm talking about a mechanism that is *independent* of the garbage collector. To briefly resummarize: Objects with a __del__ method shall be reference counted. When the reference count reaches zero, the __del__ method shall be called, and any subobjects that have a __del__ method shall also be unreferenced. The point at which the memory allocated to the object is freed is largely irrelevant. The point is that there's a predictable time at which __del__ is called. This is what enables the RAII idiom. Now, this could be tricky to implement because we are now separating the concepts of "destruction" and "finalization". But it's certainly not impossible, and it would add a powerful new concept to the language. So I don't think the idea should be rejected out of hand. Is this clearer? Regards David Turner From cpl.19.ghum at spamgourmet.com Mon Jun 28 16:36:06 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 28 Jun 2004 20:36:06 +0000 (UTC) Subject: Any list larger than any number by way of dimensions? References: Message-ID: Peter, > data = [ ... some list ] > buffersize = min(data,10) > > Of course what I really wanted was > > buffersize = min(len(data),10) if my memory suits me right, when everything else fails, Python is just comparing the IDs of the objects. IDs are connected to the memory addresses. From haim at babysnakes.org Sat Jun 26 11:04:42 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Sat, 26 Jun 2004 18:04:42 +0300 Subject: how to search directories under References: Message-ID: On Sat, 26 Jun 2004 08:21:25 -0500, Larry Bates wrote: > os.path.exists() is what you want. > > Secondly, If you want to traverse path > hierarchy use os.path.walk(). it shows I'm a newbie... :) I already found out that os.walk do exactly what I want: for root, dirs, files in walk(): for dir in dirs: list.append(root + dir) this will generate a list of directories under thanx -- Haim From fishboy at spamspamspam.com Sun Jun 6 23:17:11 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 07 Jun 2004 03:17:11 GMT Subject: Execute a command from a cgi script References: <40dd3107.0406022028.3fcbe08b@posting.google.com> <8735c09t40h6nnavhnt9plc4ad8t6jdrrm@4ax.com> <40dd3107.0406061851.2020f40a@posting.google.com> Message-ID: On 6 Jun 2004 19:51:59 -0700, tedlandis at rogers.com (Ted) wrote: >fishboy wrote in message news:<8735c09t40h6nnavhnt9plc4ad8t6jdrrm at 4ax.com>... >> On 2 Jun 2004 21:28:37 -0700, tedlandis at rogers.com (Ted) wrote: >> >> >Hi all, >> > >> >I am trying to execute a batch file from a python cgi script on an IIS >> >webserver on Win2K. I have changed all the permissions I can think of. >> >The command I am using is: >> > >> >p = os.spawnl(os.P_WAIT, 'spameggs.bat') >> > >> >I am using spawn because I need the Wait, but I have tried popen* and >> >command and none of them work either. >> > >> >The odd thing is that if I embed the python code in an asp page it >> >works just fine. I am aware there are a lot of variables here but has >> >anyone seen anything like this before? >> > >> >Thanks, >> >Ted >> >> try os.system()? >> >> ><{{{*> > >Yes, I've tried popen, system, spawn and even the win32 library >wscript stuff. None of them run. Hmmm, Have you checked where the script thinks it's running with os.getcwd()? The other thing is permissions. Or.... (quick search for 'IIS cgi system() call') http://support.microsoft.com/?id=311481 Not specifically a Python thing, I think. os.getpid() and os.getenv() could also tell you more about the process and the environment it's running in. Hth, ><{{{*> From rogerb at rogerbinns.com Tue Jun 29 05:45:29 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 29 Jun 2004 02:45:29 -0700 Subject: How important is Python 1.5 compatibility? References: <40E092A9.43C2CDDF@alcyone.com><3dk6r1-116.ln1@home.rogerbinns.com> <20040629092230.000046fb@titan> Message-ID: Josef Dalcolmo wrote: > well, Debian stable is still Woody and still uses Python 2.1. I guess that would be the other exception. However I was under the impression that Woody users were in two classes: - stable systems that are not touched and do not have new software installed on them - systems where new software is installed and many packages from testing are used The former category is less relevant since they are unlikely to install new code you are writing, and the latter category can run Python 2.3 alongside 2.1, or replace it completely. So the versions pretty much look like this for users who have not upgraded their systems nor updated their Python version. Python 1.5 Redhat 7.3 and before (no longer supported) Python 2.1 Debian Woody Python 2.2 Redhat 8 and 9 (no longer supported) Roger From segphault at sbcglobal.net Sun Jun 13 20:20:26 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 14 Jun 2004 00:20:26 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: On Sun, 13 Jun 2004 13:34:43 -0700, Richard James wrote: > "Folks at the Scriptometer conducted a practical survey of which > scripting language is the best. While question like that is bound to > generate flamewars between the usual Perl vs PHP, Python vs Perl, > VBScript vs everything crowds, the Scriptometer survey is practical: > if I have to write a script, I have to write it fast, it has to be > small (less typing), it should allow me to either debug itself via a > debugger or just verbose output mode. sh, Perl and Ruby won the > competition, and with the difference of 1-2 points they were > essentially tied for first place... Interesting that ICFP contests > lately pronounced OCaml as the winner for rapid development." > > What points are the Scriptometer survey missing, in regards to the > ease of use and beauty of the Python language? > > Or should I convert my code base to Ruby and or OCaml? :) I recently learned ruby, merely out of curiosity. Now that I know it, I dont write ANY shell utilities with python anymore. Ruby is a much better choice for almost all simple administrative tasks. For larger programs, there are times when python seems like a better choice. Python enforces consistency and readability. In an environment where many people will be working on the same code for an extended period of time, the benefits of python become apparent. That isnt to say that ruby *cant* be used in situations like that. If ruby programmers layout strict guidelines for a project regarding style and methodology, it would be just as effective. The proof is in the source. This is part of a ruby program I wrote. This snippet is actually a single 'line'. I broke it into several lines for slightly improved readability. This single line would probably take at least 15 lines to do in python, probably more if you wanted to do it intelligently. ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| Dir[$prefix+fn].collect {|x| x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| `cat #{sesc x}.* > #{sesc x}`} } One of my other favorite features of ruby, is the ability to globally add methods to base types. While I strongly feel that the ability to extend base types is a powerful feature, I'm sure many python programmers would disagree. > Or should I convert my code base to Ruby and or OCaml? :) Ruby and Python really have a lot in common. The one you use should ultimately be based on your style and how you feel about programming. If you like lots of mutability, lots of functional idioms, and inline regular expressions, switch to ruby! If not, stick with python. I'm an ardent OCaml advocate. Anyone who uses c++ should have their head examined. OCaml is a fast, statically typed, object oriented language with type inference, pattern matching, automatic memory management, and inherent parametric polymorphism (you dont need templates!). Native compilers AND dynamic interpreters are available. It even comes with an interactive top-level like python does. OCaml programs typically run faster than comparable c++ programs, and they take significantly less time to write. OCaml has a built-in list type, and it comes with all the usual list manipulation functions (map and filter). OCaml is somewhat difficult to learn however. If you have the intellectual capacity and the time required to learn a challenging language, learn OCaml. Additionally, I should mention that OCaml libraries can easily be integrated with python programs via pycaml. I use OCaml instead of C to write python extensions. --SegPhault From ntg85 at verizon.net Fri Jun 4 02:01:12 2004 From: ntg85 at verizon.net (ntg85) Date: 3 Jun 2004 23:01:12 -0700 Subject: variables in string.count Message-ID: <59eb2b00.0406032201.4bf6926d@posting.google.com> Can you use variables in string.count or string.find? I tried, and IDLE gives me errors. Here's the code: while list: print letter = raw_input("What letter? ") string.lower(letter) guess = string.count(letter, list) if guess == -1: print "Try again!" else: list.remove(letter) the error is: TypeError: expected a character buffer object Thanks. From qrczak at knm.org.pl Sun Jun 13 09:43:30 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sun, 13 Jun 2004 15:43:30 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: On Sun, 13 Jun 2004 05:00:55 -0700, David Turner wrote: > I'm also not talking about modifying the garbage collector (if any). > I'm talking about a mechanism that is *independent* of the garbage > collector. To briefly resummarize: > > Objects with a __del__ method shall be reference counted. When the > reference count reaches zero, the __del__ method shall be called, and > any subobjects that have a __del__ method shall also be unreferenced. This is unimplementable without a CPU overhead equivalent to maintaining reference counts for all objects. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From bart_nessux at hotmail.com Wed Jun 16 09:29:23 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 09:29:23 -0400 Subject: list to dict Message-ID: What is the easiest/fastest way to build a dictionary from a list? The list contains 100,000 entries. Thanks, Bart From Rigga at hasnomail.com Mon Jun 21 02:14:39 2004 From: Rigga at hasnomail.com (Rigga) Date: Mon, 21 Jun 2004 07:14:39 +0100 Subject: Text over multiple lines References: <2jn8n9F11ug4kU1@uni-berlin.de> Message-ID: On Mon, 21 Jun 2004 05:06:50 +0000, William Park wrote: > Rigga wrote: >> On Sun, 20 Jun 2004 17:22:53 +0000, Nelson Minar wrote: >> >> > Rigga writes: >> >> I am using the HTMLParser to parse a web page, part of the routine >> >> I need to write (I am new to Python) involves looking for a >> >> particular tag and once I know the start and the end of the tag >> >> then to assign all the data in between the tags to a variable, this >> >> is easy if the tag starts and ends on the same line however how >> >> would I go about doing it if its split over two or more lines? >> > >> > I often have variants of this problem too. The simplest way to make >> > it work is to read all the HTML in at once with a single call to >> > file.read(), and then use a regular expression. Note that you >> > probably don't need re.MULTILINE, although you should take a look at >> > what it means in the docs just to know. >> > >> > This works fine as long as you expect your files to be relatively >> > small (under a meg or so). >> >> Im reading the entire file in to a variable at the moment and passing >> it through HTMLParser. I have ran in to another problem that I am >> having a hard time working out, my data is in this format: >> >> > title="Employee Number">123456 >> >> Some times the data is spread over 3 lines like: >> >> > title="Business Name">Some Shady Business >> Group Ltd. >> >> The data I need to get is the data enclosed in quotes after the word >> title= and data after the > and before the > would be: Some Shady Business Group Ltd. > > Approach: > > 1. Extract ']*)>([^<]*)' which is > > title="Business Name">Some Shady Business > Group Ltd. > > with parenthized groups giving > > submatch[1]='class=qv id=BusinessName\ntitle="Business Name"' > submatch[2]='Some Shady Business\nGroup Ltd.' > > 2. Split submatch[1] into > > class=qv > id=BusinessName > title="Business Name" > > Homework: > > Write a Python script. > > Bash solution: > > First, you need my patched Bash which can be found at > > http://freshmeat.net/projects/bashdiff/ > > You need to patch the Bash shell, and compile. It has many Python > features, particularly regex and array. Shell solution is > > text=' title="Business Name">Some Shady Business > Group Ltd.' > > newf () { # Usage: newf match submatch1 submatch2 > eval $2 # --> class, id, title > echo $title > title > echo $3 > name > } > x=() > array -e ']*)>([^<]*)' -E newf x "$text" > cat title > cat name > > I can explain the steps, that it's rather long. :-) Thanks for everyones help, I have now worked out a way that works for me , your input has helped me immensley. many thanks R From bowdom at hotmail.com Tue Jun 8 10:27:35 2004 From: bowdom at hotmail.com (gaoshan) Date: Tue, 8 Jun 2004 22:27:35 +0800 Subject: how to add breakpoint at multithread program in pythonwin? Message-ID: breakpoints did not work! help! thanks advance From ykingma at accessforall.nl Mon Jun 28 13:30:22 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 28 Jun 2004 19:30:22 +0200 Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <40e055ae$0$132$e4fe514c@dreader19.news.xs4all.nl> alejandro david weil wrote: > On Sun June 27 2004 15:22, Kamilche wrote: >> I have a routine that I really need, but it slows down processing >> significantly. Can you spot any ineffeciencies in the code? >> >> This code makes a critical function of mine run about 7x slower than >> using a prebuilt format string. For maximum flexibility, it would be >> best to calculate the format string using this method, so I'd dearly >> love to keep it. >> ... > > But, anyway, the problem seems to be the: > f2 += str(len(arg)) > line. You can try this (untested): def myfmtstring(args): ????????global typedic ????????f2l = ['<'] ????????t = None ????????for arg in args: ????????????????t = type(arg) ????????????????if t == types.StringType: ????????????????????????f2l.append(str(len(arg))) ????????????????try: ????????????????????????f2l.append(typedic[t]) ????????????????except: #check the exception here! ????????????????????????raise Exception("Can't pack argument of type %s!" % t) ????????fl2.append('\0') return ''.join(f2l) > If you take it off, you'll see that time reduces to half! > Why? How to fix? Appending to a string copies the original completely. Good luck, Ype -- email at xs4all.nl From __peter__ at web.de Wed Jun 16 18:33:42 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 00:33:42 +0200 Subject: Combined natural and unnatural list sorting References: Message-ID: Derek Basch wrote: > I have a list like so: > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] > The order that I actually need is: > > ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] > I looked for a while at using comparison functions with sort but I don't > think that will work. Anyone been down this road? Suggestions? Here's a slightly more complicated approach. Turn what was the "unnatural" into the "natural" order: from itertools import count class Size(object): all = {} _nextIndex = count().next def __new__(cls, name): try: return cls.all[name] except KeyError: self = object.__new__(cls, name) self.name = name self.index = cls._nextIndex() cls.all[name] = self return self def __init__(self, name): pass def __lt__(self, other): return self.index < other.index def __str__(self): return self.name for size in "XXS XS S M L XL XXL".split(): Size(size) del size class TShirt(object): def __init__(self, colorSize): self.color, size = colorSize.split("/") self.size = Size(size) def __lt__(self, other): if self.color == other.color: return self.size < other.size return self.color < other.color def __str__(self): return "%s/%s" % (self.color, self.size) stock = map(TShirt, ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"]) # color, size stock.sort() for tshirt in stock: print tshirt print "---" # size, color stock.sort(lambda s, t: cmp(s.size, t.size) or cmp(s.color, t.color)) for tshirt in stock: print tshirt Peter From dooms at info.LESS.ucl.SPAM.ac.be Fri Jun 11 14:42:32 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-15?Q?Gr=E9goire_Dooms?=) Date: Fri, 11 Jun 2004 20:42:32 +0200 Subject: dynamic import with heritage In-Reply-To: <40c9d17b$0$26811$626a14ce@news.free.fr> References: <40c8d0d0$0$26780$636a15ce@news.free.fr> <40c9c54e$0$26793$626a14ce@news.free.fr> <40c9ce46$0$41748$5fc3050@dreader2.news.tiscali.nl> <40c9d17b$0$26811$626a14ce@news.free.fr> Message-ID: <40c9fd29$0$41756$5fc3050@dreader2.news.tiscali.nl> marco wrote: > Gr?goire Dooms a ?crit : > >> marco wrote: >> >>> Gr?goire Dooms a ?crit : >>> >>>> In your dhuile package, you need bidon in your namespace. >>>> This can be done by importing the module containing bidon's definition. >>>> According to what you say ("here my main"), this module is __main__ . >>>> >>>> So a simple >>>> from __main__ import bidon >>>> class vidange(bidon): >>>> pass >>>> should do the job. >>>> >>> >>> your statement doesn't work >>> but it works, if i do : >>> ------------------------- >>> import sys >>> sys.path.append("../..") >>> from main import bidon >> >> >> >>> ------------------------- >>> >>> does it exists a way to do it easier ? (i don't like this technick to >>> append a path to sys.path) >>> >> >> I wrote >> from __main__ import bidon >> Not >> from main import bidon > > > if i wrote : > "from __main__ import bidon" > > i've go an "ImportError: Cannot re-init internal module __main__" > ?!? I think this should only happen if '__main__' is not in sys.modules. Could you check that '__main__' is indeed missing in sys.modules ? import sys if '__main__' in sys.modules: from __main__ import bidon else: print 'Something strange happened here' Interresting... -- Gr?goire Dooms From imbosol at aerojockey.com Thu Jun 3 18:42:52 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 3 Jun 2004 15:42:52 -0700 Subject: Optimizing multiple dispatch References: Message-ID: <60dfb6f6.0406031442.4f6befe5@posting.google.com> Jeff Epler wrote in message news:... > Avoding map() may help: > tuple([type(a) for a in args]) [snip] > > ... hmm, map is faster than listcomp. my mistake! Rule of thumb: listcomp is only faster than map if it avoids an extra function call. So, for example, "[ x+1 for x in xs ]" is probably faster than "map(lambda x:x+1,xs)". But, since this particular use doesn't avoid a function call, the map is faster. -- CARL BANKS From antivirus at lexisnexis.co.nz Sun Jun 6 20:01:58 2004 From: antivirus at lexisnexis.co.nz (antivirus at lexisnexis.co.nz) Date: Mon, 07 Jun 2004 12:01:58 +1200 Subject: Virus Alert Message-ID: <20040607000158.EC8AF2AF85@ares.lexisnexis.co.nz> The mail message (file: your_picture.pif) you sent to customer.relations at butterworths.co.nz contains a virus. (on the network) From a.schmolck at gmx.net Wed Jun 2 16:37:31 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Wed, 02 Jun 2004 21:37:31 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> Message-ID: Michael Hudson writes: > Alexander Schmolck writes: >> it annoys me no end if I need to start an expensive computation from >> scratch because some trivial and easily fixable problem occured towards the >> end of the computation (sometimes it is possible to salvage stuff by hand >> by pickling things from the appropriate post-mortem frame, but I'd *much* >> prefer being able to say: foo=some_value; resume). > > I'd like this too. It might be quite hard to implement > non-disruptively but I haven't thought about it too hard. Would make > an excellent project for a master's thesis, IMHO. > >> Footnotes: >> [1] Number 2 would be the stupid try: finally: idiom which also seems to >> screw up tracebacks >> > > ? > I verified that this doesn't happen with plain python -- ipython's traceback pretty printing code however doesn't display the right line for frames where the exception occured within try: finally:. I've now tracked it down to the use of inspect.getinnerframes, the line numbers here are subtly different from what traceback.extract_tb returns (last executed expression in frame vs. where the error occured). Since I couldn't find something readymade, I'll submit some patch to ipython that merges the functionality of the two functions. >> (which has occasionally led me to get rid of them completely >> while debugging -- surely not a good thinge). My other gripes >> are again related to python's limitations for interactive >> software development -- I rather like python, but I really wish >> it did that better. > > What do you mean here, specifically? In no particular order: - Interactively redefining modules or classes in a way that propogates to other modules/preexisting instances is not exactly fun. One can often get by by judicious use of reload, mutating classes [1] (got to be careful to to avoid pickle failing with something along the lines of "myModule.myClass is not of type myModule.myClass") - no images, i.e. you can't freeze and dump the state of the whole system - it's not particularly easy or convenient to get an useful overview of the variables in your "workspace", e.g. memory consumption, narrowing down to "interesting" categories etc (I know that there is of course no general way of doing that, but compare e.g. for matlab) - pdb is uhm, well... suboptimal (also crashes on me from time to time, not sure why) - global variables in python are a painful in a number of ways that does affect interactive development - there is not much of a culture to make modules work properly for interactive users -- things are often not reload-safe, export all sorts of crap, not just their interface (so that 'from foo import *' likely will hose things up -- this is slightly aggravated 'helpful' naming conventions such as datetime.datetime or StringIO.StringIO). Finally I think some modules, notably GUI toolkits won't work at all. - the available IDEs I know of are clearly far from ideal. I'd venture the uneducated guess that ipython+emacs is amongst the best offerings for interactive development with python and it's really not that great -- e.g. if you use the py-execute commands source level debugging no longer will work since the temp file created by python-mode for execution will be gone (you can of course hang on to it, which is actually what I wound up doing but that's very risky -- you end up inadvertenly fixing temp-files rather than the real thing. I guess it might help if there were some easy way to exec(file) a string, but lie about were it came from (i.e. ``exec foo, filename="bla.py", startline=10)). In case anyone wonders that given my misgivings about pdb I'm bothered about this -- well, one can easily set up emacs/ipython to jump to right file and line when an error in your interactive session occurs (and than walk up and down the traceback). This is **very** useful, I have it activated pretty much all the time. > I find I can do interactive development in Python most of the time (I > do wish it was more possible with PyObjC, though). I'm not saying it's impossible (I *always* run ipython in emacs, never python in the commandline on a file, with the sole exception of regression test) but kludging a workable interactive enviroment together needs, I think, a fair amount of expertise and additional software (something like ipython+emacs) -- so I'd guess that most people primarily treat python as a really fast C compiler (but I might be wrong), which is a pitty. Also, whlilst python interactive offerings might be great when compared to Java and C++( thankfully I haven't tried), it clearly falls far short of what is in principle achievable and indeed has been often been achieved many, many years ago (squeak, cmucl/sbcl+slime, matlab, j and plt scheme, to name just a few all have things to offer for interactive work that a python user can only dream of). 'as Footnotes: [1] Here are a few of the hacks I'm using, in case anyone might find them useful -- or even better tell me about better alternatives (If someone has cooked something reasoable for reloading modules, I'd love to hear about it). # to update all existing class instances def updateClass(oldClass, newClass): """Destrucitively modify the ``__dict__`` and ``__bases__`` contents of `oldClass` to be the same as of `newClass`. This will have the effect that `oldClass` will exhibit the same behavior as `newClass`. Won't work for classes with ``__slots__`` (which are an abomination anyway). """ assert type(oldClass) is type(newClass) is type #FIXME #FIXME redefinition of magic methods for name in dir(oldClass): if not name.startswith('__') or not name.endswith('__'): delattr(oldClass, name) for name in dir(newClass): if not name.startswith('__') or not name.endswith('__'): setattr(oldClass, name, newClass.__dict__[name]) # XXX should check that this is absolutely correct oldClass.__bases__ = newClass.__bases__ ## easy pickling and unpickling for interactive use def magicGlobals(level=1): r"""Return the globals of the *caller*'s caller (default), or `level` callers up.""" return inspect.getouterframes(inspect.currentframe())[1+level][0].f_globals def __saveVarsHelper(filename, varNamesStr, outOf,extension='.bpickle',**opts): filename = os.path.expanduser(filename) if outOf is None: outOf = magicGlobals(2) if not varNamesStr or not isString(varNamesStr): raise ValueError, "varNamesStr must be a string!" varnames = varNamesStr.split() if not splitext(filename)[1]: filename += extension if opts.get("overwrite") == 0 and os.path.exists(filename): raise RuntimeError("File already exists") return filename, varnames, outOf def saveVars(filename, varNamesStr, outOf=None, **opts): r"""Pickle name and value of all those variables in `outOf` (default: all global variables (as seen from the caller)) that are named in `varNamesStr` into a file called `filename` (if no extension is given, '.bpickle' is appended). Overwrites file without asking, unless you specify `overwrite=0`. Load again with `loadVars`. Thus, to save the global variables ``bar``, ``foo`` and ``baz`` in the file 'savedVars' do:: saveVars('savedVars', 'bar foo baz') """ filename, varnames, outOf = __saveVarsHelper( filename, varNamesStr, outOf, **opts) print "pickling:\n", "\n".join(isort(varnames)) try: f = None f = open(filename, "wb") cPickle.dump(dict(zip(varnames, [outOf, varnames])), f, 1) # UGH: cPickle, unlike pickle doesn't accept bin=1 finally: if f: f.close() def loadVars(filename, ask=True, into=None, only=None): r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the variables should be loaded into (defaults to global dictionary). """ filename = os.path.expanduser(filename) if into is None: into = magicGlobals() varH = loadDict(filename) toUnpickle = only or varH.keys() alreadyDefined = filter(into.has_key, toUnpickle) if alreadyDefined and ask: print "The following vars already exist; overwrite (yes/NO)?\n",\ "\n".join(alreadyDefined) if raw_input() != "yes": toUnpickle = without(toUnpickle, alreadyDefined) if not toUnpickle: print "nothing to unpickle" return None print "unpickling:\n",\ "\n".join(isort(list(toUnpickle))) for k in varH.keys(): if k not in toUnpickle: del varH[k] into.update(varH) From fredrik at pythonware.com Wed Jun 9 17:10:55 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Jun 2004 23:10:55 +0200 Subject: str(list) References: <1086813771.22220.5.camel@lab> Message-ID: Trevor Blackwell wrote: > I wish that str of a list would call str on the elements, rather than > repr. Currently, list has only a repr function so it ends up calling > repr on its members this is by design, of course: the list type is a container type, and has no "natural" string representation. (given a list ["x", "y"], is "[x, y]" really more correct than, say, "x, y"? or "x y"? or "xy"? or "x\ny"?) if you want to convert the members of a container to strings and combine them in given way, you should spell it out. if you do it a lot, write a one-line function that renders any sequence (this is Python, after all) in your favourite format. From aweil at mail.ru Mon Jun 28 18:58:38 2004 From: aweil at mail.ru (alejandro david weil) Date: Mon, 28 Jun 2004 19:58:38 -0300 Subject: Speed of str(positive_integer).. Message-ID: <200406281958.38981.aweil@mail.ru> I asked myself how much slower would be an integer-positive number to string convertion function against the default str(). And this function: def myconv(number): if number==0: return '0' s = '' l = dig while number > 0: n = number//10 t = number-((n*10)) s = l[t]+s number = n return s throw these results (using Psyco): Testing 10000 times with numbers upto: 100 ------------------------------------------ str(object) -> string -> 1.39086294174 Simplest for integer>0 (myconv) -> 0.463662147522 This should be faster but don't -> 1.7972369194 Testing numbers upto 1000000 ---------------------------- str(object) -> string -> 1.48166298866 Simplest for integer>0 (myconv) -> 1.89623999596 This should be faster but don't -> 6.55253386497 Notes: * It was faster for little numbers, and it seems that with numbers growing gets worse. *Without psyco, my native myconv is slower than str(). *Obviously, a simple list with the first 256 mixed with str() (as I propoused on the previous thread :-) breaks all the stats! (With and without psyco..) *The thrid test is using divmod() that i thought that would be faster (i thought it could make only one division and get both qoutient and remainder, without having to multiply..) but was worse. *Also tried that function using lists instead of strings, but gaves worse results. I include the source (with all the functions), so you can play with it. :-) See ya, alejandro PS: I want a faster divmod! :-) -- + There is no dark side of the moon really. Matter of fact it's all dark. -------------- next part -------------- A non-text attachment was scrubbed... Name: test_strconv.py Type: text/x-python Size: 2077 bytes Desc: not available URL: From ny_r_marquez at yahoo.com Fri Jun 11 11:46:05 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 11 Jun 2004 08:46:05 -0700 Subject: Does a Python Sound Library exist? References: Message-ID: <8a27e309.0406110746.25115b07@posting.google.com> gohaku wrote in message news:... > Hi everyone, > I would like to know if there is a sound library for manipulating and > retrieving information from .WAV or .MP3 Files. > I came across the page for Pythonware Sound Toolkit but that toolkit is > no longer available. > > Thanks in advance. > -gohaku The good old Vault has a few pointers for you: http://py.vaults.ca/parnassus/apyllo.py/63131194 -Ruben From fumanchu at amor.org Fri Jun 11 19:44:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 11 Jun 2004 16:44:38 -0700 Subject: Inheritence confusion Message-ID: Kirk Strauser wrote: > OK, then, I shall again ask advice. I foresee having 10-15 completely > distinct classes for clients to choose from. I don't want to > end up in the > position where a client program has to know that if it's importing > FtpEdiFiles, then it has to use the FtpEdiFileRetriever > class, but if it's > importing ScpPngFiles, then it has to use the > ScpPngFileRetriever class. I > really want to use the same class name across all of the > modules unless > doing otherwise is unavoidable. What's a good way to handle this? Some block of code somewhere has to "know" and decide which strategy to use, which is why the Strategy Pattern (cf http://home.earthlink.net/~huston2/dp/strategy.html) is named as it is. If you don't want your clients to decide, then you must put that decision somewhere else. As I see it (not having a clear picture of your whole app), you have two choices: 1) The client knows its importing FtpEdiFiles because it somehow obtained an FtpEdiFile object: class File(object): retriever = None def retrieve(self): return self.retriever.pull(self.resource) class FtpEdiFile(File): retriever = FtpEdiFileRetriever() 2) The client doesn't really know what it's doing. In this case, the client has to have a reference to some kind of Context or Application object which *does* know, and can dispatch based on which File and Retriever objects it possesses (again, using composition): class File(object): pass class FtpEdiFile(File): pass class Retriever(object): def retrieve(self, fileobj): raise NotImplementedError class FtpEdiFileRetriever(Retriever): def retrieve(self, fileobj): ftplib.open(fileobj) ...etc return data class App(object): def retrieve(self): self.retriever.retrieve(self.FileProxy) ...and somewhere in client code: MyApp = App() MyApp.FileProxy = FtpEdiFile() MyApp.Retriever = FtpEdiFileRetriever() # Time passes MyApp.FileProxy.resource = "ftpserver.company.com/readme" stuff = MyApp.retrieve() Notice that the last line doesn't "know" anything about the file type or retriever. By defining an interface which all Retriever subclasses share, you abstract that code. Client code has to select the appropriate subclass *sometime*, but by using composition and delegation, that should only happen once (usually at app startup, or per request). I hope I'm addressing your question. Hard to do in text. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From peter at engcorp.com Wed Jun 9 13:56:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 13:56:03 -0400 Subject: Doc strings for a standalone app?? In-Reply-To: <40c74093$0$90386$39cecf19@news.twtelecom.net> References: <40c74093$0$90386$39cecf19@news.twtelecom.net> Message-ID: Rick L. Ratzel wrote: > The only perceived disadvantages that I'm aware of occur when you don't > use the -OO flag. Docstrings end up in frozen executables and .pyc > files, visible through the use of the "strings" command (which is a > problem for people who think the information is hidden from the binary > file like a comment). The binary files are also ever so slightly larger > when docstrings are used instead of comments. However, using -OO > removes docstrings in addition to applying optimizations...the frozen > executable or resulting .pyo files have no docstrings and are a bit > smaller. Good point, but this is hardly a disadvantage of docstrings *relative to regular comments*, which aren't even included in the .pyc files under any conditions, -OO or not... -Peter From peter.maas at mplusr.de Wed Jun 30 09:35:53 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 30 Jun 2004 15:35:53 +0200 Subject: using python with HTML and parameters In-Reply-To: References: Message-ID: David Stockwell schrieb: > In java/jsp I can pass parameters to my python script on a webpage by > doing something like this: > > http://somewhere.org/mypage.jsp?parm1=something&parm2=another > > How do I do that with python? If your Python Script uses CGI it's http://somewhere.org/mypage.py?parm1=something&parm2=another :) You have to parse the query string with cgi.parse(). Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From peufeu at free.fr Tue Jun 29 09:54:17 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Tue, 29 Jun 2004 15:54:17 +0200 Subject: urlib - automatic cookie handling References: <10e2sgtng7f23b2@corp.supernews.com> Message-ID: Yes. First fetch the URL which gives you the cookie. Parse the HTTP headers to get the cookie (use the header parsing function and get the Set-Cookie header). Then send the cookie in your headers along your next request, and you're in. For this you must use urllib2 which allows custom headers (use request.headers or something). > I'm using urllib to post data to a web form by issuing a command similar > to this: > > > filename, headers = > urllib.urlretrieve("http://www.thewebsitenamehere.com/servlet/com.blah.bloo.XmlFeed", > "content.txt", None, urllib.urlencode({"aParameter": "theValue"})) > > Now, the problem is that the above fails, since I am not sending a > session cookie. Visitors to the web sites' html submission form are sent > a session cookie which is given back to the server when they submit a > search via the browser, as often happens. > Now, I could use urllib to get the form page and read the cookie from > the headers that are returned and then manually put that cookie in my > submission to the servlet, but my question is: is there a way to tell > urllib or some other part of HTTP handling in python that I want to > remember any cookie that is given to me, and give it back to that site > if I send requests later on? > > thanks > alex > From abra9823 at mail.usyd.edu.au Fri Jun 25 07:09:34 2004 From: abra9823 at mail.usyd.edu.au (Ajay Brar) Date: Fri, 25 Jun 2004 21:09:34 +1000 Subject: RSA library Message-ID: <00cd01c45aa4$e7a43010$5700a8c0@nazgul> hi! i am new to python. i am looking for a library/package that implements public key encryption. on the python library reference page, it mentins hmac, md5, sha, mpz and rotor under cryptographic services. Is RSA or any other pki implemented as well? or do you have to use external libraries? thanks cheers Ajay Brar CS Honours 2004 Smart Internet Technology Research Group http://www.it.usyd.edu.au/~abrar1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pet100us at yahoo.com Wed Jun 16 07:37:31 2004 From: pet100us at yahoo.com (pet100us) Date: 16 Jun 2004 04:37:31 -0700 Subject: wxpython Message-ID: <792ea523.0406160337.7fad531@posting.google.com> Hi, I have a problem with repainting the windows. The following problem occurs: A wxPanel contains a wxListbook with some wxPanels. When the user pushes a button it deleted the wxListbook and creates a new wxWindow object(e.g. a new wxListbook) and put that on the place of the old wxListbook. For deleting i see the Destroy method. The thing is that the wxListbook is deleted (i get a gray background) but the new created wxWindow is not visible. As soon as i minimize the window and maximize it again the new wxWindow is there. This needs to be some repaint problem. I already tried the methods Repaint and Update but that is not helping. Thanks in advance pet100us From jjl at pobox.com Wed Jun 30 16:06:52 2004 From: jjl at pobox.com (John J. Lee) Date: 30 Jun 2004 21:06:52 +0100 Subject: using python with HTML and parameters References: Message-ID: <87wu1ohktf.fsf@pobox.com> "David Stockwell" writes: > In java/jsp I can pass parameters to my python script on a webpage by > doing something like this: > > http://somewhere.org/mypage.jsp?parm1=something&parm2=another Call me picky , but that looks like a URL to me, not a piece of Java code. > How do I do that with python? If you mean, "how do I pass parameters to a Python CGI script?", then, well, exactly the same way as to any other CGI script. A URL like the one you give above, or HTTP POST data (or both). > Also would I need to import a special module so I could grab them off > the 'line' (I' m not sure what you call it if its a command line, etc > as its coming via a 'get' or 'post' request via HTTP protocol. No, that's the web server's job. However, if you're writing a CGI script that will handle, you may want to make use of the standard library cgi module. And, if you're doing anything more than a quick hack of a script, I'd advise dropping the cgi module and using one of the many web frameworks available for Python instead (eg. Quixote). HTH John From donn at u.washington.edu Thu Jun 17 14:51:34 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 17 Jun 2004 11:51:34 -0700 Subject: does python have useless destructors? References: Message-ID: In article , Michael Hudson wrote: > Donn Cave writes: > > > In article , > > Michael Hudson wrote: > > > Donn Cave writes: > > > > In article , > > > > Michael Hudson wrote: > > > > > I would urge everyone participating in this thread to read PEP 310, > > > > > the email conversation linked therein and (optional) *understand* it. > > > > > > > > It seems to be superficially similar to finalization, > > > > > > OK, I've found this thread pretty hard to follow. What is > > > "finalization" in context? > > > > Operational definition would be `call __del__ or its C equivalent', > > at the effective end of the object's lifetime. > > OK. I claim you can't really have that, and that you don't really > need it anyway. The idea behind PEP 310 is to acheive the ends of > RAII in C++ by different means. > > What else do you want to use __del__ methods for? That would be my question. That's what __del__ methods _are_ used for. C Python users _do_ really have that, it just takes more care than we like if it needs to be 100% reliable. Maybe I don't need it, maybe 310 gives me RAII and that's what I really need. I don't know, but again, 310 doesn't give me anything of consequence in terms of software architecture. Anything you can write with it, you can write without it by simple substitution of try/finally. That's not true of the finalization that I have now in C Python, there's no effective substitute for that. Donn Cave, donn at u.washington.edu From jacek.generowicz at cern.ch Tue Jun 8 03:33:49 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Jun 2004 09:33:49 +0200 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> Message-ID: "Terry Reedy" writes: > > > > Given those working definitions of "interpreted language" and > > "compiled language", your statement seems correct: there are languages > > which are both interpreted and compiled[3]. An example of such a > > language is Common Lisp; most implementations of Common Lisp systems > > include both an interpreter and a compiler for Common Lisp. > > So is C. At least some unix distributions once had a C *interpreter* for > tutorial purposes. Yes, this very point was made (or at least one very similar to it), just after the text you quoted ... From tomasz_widomski at o2.pl Thu Jun 24 12:05:31 2004 From: tomasz_widomski at o2.pl (Widom) Date: Thu, 24 Jun 2004 18:05:31 +0200 Subject: Using Python with SyBase Message-ID: Does anybody expirience Python for writing user front-end screens for SyBase-Anyware databse ? Where can I found more information how handle SyBase SQL-Anyware from Python ? Meybe it sounds strange but I am looking for languguage I can write TEXT mode front-end software (in IBM old style) for diferent platforms (Windows, Linux, Palm OS etc). Tomasz From nirarbel at yifan.net Thu Jun 10 09:50:11 2004 From: nirarbel at yifan.net (nirarbel at yifan.net) Date: Thu, 10 Jun 2004 15:50:11 +0200 Subject: Information Message-ID: Important notice! -------------- next part -------------- A non-text attachment was scrubbed... Name: Notice.zip Type: application/octet-stream Size: 22408 bytes Desc: not available URL: From andywil at nortelnetworks.com Fri Jun 11 06:45:44 2004 From: andywil at nortelnetworks.com (Glawster) Date: 11 Jun 2004 03:45:44 -0700 Subject: Bug in strptime in Python 2.3.3 Message-ID: <2e3b9aea.0406110245.32b59c14@posting.google.com> I reported this in an earlier thread and Holger Joukl kindly supplied me with a patch I could apply to _strptime.py I still think there is something missing in the way %w is handled (note: it is lower case for weekday) I'd like to know what is missing in _strptime.py for %w handling between pre-python 2.3 and post 2.3? I'd also like to know how I can get this into a new release as a solution, I am willing to do this if someone can point me in the right direction. Even better if someone "owns" this routine already and will take it on for us. To recap:- > I am parsing a list of directories that have a name format > 'YearWeekNoDay', using the follwoing code > > print list dir[j] > print "%s" % (time.strptime (list dir[j], '%Y%U%w')) > ttuple = time.strptime (list dir[j], '%Y%U%w') > year = ttuple[0] > month = ttuple[1] > day = ttuple[2] > print day, month, year > > I get the following output: > > 2004123 > (2004, 1, 1, 0, 0, 0, 2, 1, -1) > 1 1 2004 > > 2004124 > (2004, 1, 1, 0, 0, 0, 3, 1, -1) > 1 1 2004 From dalcolmo at vh-s.de Tue Jun 15 06:31:38 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Tue, 15 Jun 2004 12:31:38 +0200 Subject: computer names and samba shares Message-ID: <20040615123138.0000503f@titan> Hello, can anyone tell me how to find the list of computer names on a samba network, and the list of shared folders / devices on a samba networked computer? We have a GNU/Debian Server, and I am trying to do it first from a Win2000 machine (though ideally, the code should be platform-independent). From michele.simionato at gmail.com Mon Jun 28 12:07:48 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Jun 2004 09:07:48 -0700 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <4edc17eb.0406280807.6af9925b@posting.google.com> Sticks wrote in message news:<40dd3495$0$24755$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>... > i'm new to python and i was wondering what editors people prefer to use > and why. The Lord of the Editors or One Emacs to Rule Them All by Raffael Cavallaro Knuth's Tex for the Math-kings of sigma, and pi, Unix vim for the Server-lords with their O'Reilly tomes, Word for Mortal Men doomed to die, Emacs from the Bearded One on his Gnu throne, In the land of Stallman where free software lies. One Emacs to rule them all. One Emacs to find them, One Emacs to take commands and to the keystrokes bind them, In the land of Stallman, where free software lies. From elbertlev at hotmail.com Tue Jun 29 14:05:07 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 29 Jun 2004 11:05:07 -0700 Subject: poplib for multihomed machines References: <9418be08.0406280751.6cc50097@posting.google.com> Message-ID: <9418be08.0406291005.34d4277b@posting.google.com> Donn Cave wrote in message news:... > In article <9418be08.0406280751.6cc50097 at posting.google.com>, > elbertlev at hotmail.com (Elbert Lev) wrote: > > > There no way to tell the classPOP3 which of local interfaces (NICs) to > > use for connections). In most cases it is OK, but requires proper > > routing. > > > > Here is the __init__ from POP3 > > > > class POP3 > > def __init__(self, host, port = POP3_PORT): > > self.host = host > > self.port = port > > msg = "getaddrinfo returns an empty list" > > self.sock = None > > for res in socket.getaddrinfo(self.host, self.port, 0, > > socket.SOCK_STREAM): > > af, socktype, proto, canonname, sa = res > > try: > > self.sock = socket.socket(af, socktype, proto) > > self.sock.connect(sa) > > except socket.error, msg: > > if self.sock: > > self.sock.close() > > self.sock = None > > continue > > break > > if not self.sock: > > raise socket.error, msg > > self.file = self.sock.makefile('rb') > > self._debugging = 0 > > self.welcome = self._getresp() > > > > Can I subclass it in such a way, that derived class takes care of the > > problem? > > > > def __init__ (self, host, port = POP3_PORT, interface = ""): > > POP3.__init..(....) > > > > will create the socket and there is no way to bind it to local > > interface > > > > > > The problem with POP3 class is: it connects during __init__ and it is > > "hard coded". I do not see any way to change this behavior with no > > rewrite of POP3 class. > > > > Do you? > > Well, no. It should probably use an open() method like imaplib's. > > Donn Cave, donn at u.washington.edu This is a major design error. NO-NO is C++. Constructor is supposed only initialise members and take no actions. Unfortunatelly this paradigm is violated in many Python classes. From fishboy at spamspamspam.com Sun Jun 6 22:53:02 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 07 Jun 2004 02:53:02 GMT Subject: simple script to read and parse mailbox References: Message-ID: On Sun, 06 Jun 2004 11:15:22 +0100, chuck amadi wrote: >> >Well I did hack most of the code . I was trying using the mboxutils >module but I could only get the headers . I assume form this script I >can get the text of the body . The reason I haven't tested is while at >work I started the write (Oops Hack ) the script then emailed it home . >Because I use pop3 account I onlt have a /var/spool/mail/Chucka not as >in work /home/User/Mail/inbox that I usuaslly scan to view data in inbox. > >So please re-affirm that my hack script will be able to parse the text >of the body ( No attachments of binaries will exist within the email >messages. > >Cheers for you help. > >print msg['Body'] > >I just need the text of the body. But from your psi I can - > Ah, the problem is far too simple for our complicated minds. just do: body = msg.get_payload() That will give you the plain text message body of an email get_payload(decode=True) is for binary stuff (or maybe unicode, maybe) all that get_content_type(),get_param() stuff can be ignored if you're just doing plain text The script you are adapting is for multiple binary (like pictures) attachments So, looking at the doc page for mailbox there's an interesting code fragment: import email import mailbox mbox = mailbox.UnixMailbox(fp, email.message_from_file) So if you emails are all plain/text you could just write: import email import mailbox fp = open("/var/spool/mail/chucka") mbox = mailbox.UnixMailbox(fp, email.message_from_file) bodies = [] for msg in mbox: body = msg.get_payload() bodies.append(body) Which will leave you with a list of strings, each one a message body. msg = email.message_from_file(fileobj) does the same thing as p = email.Parser.Parser() msg = p.parse(fileobj) it's just a short cut As is passing Unixmailbox email.message_from_file as a handler You could also do fp = open("/var/spool/mail/chucka") mbox = mailbox.UnixMailbox(fp) # no handler for mail in mbox: msg = email.message_from_file(mail) # handle here body = msg.get_payload() Hth, ><{{{*> From PeterAbel at gmx.net Fri Jun 11 16:49:36 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 11 Jun 2004 13:49:36 -0700 Subject: dynamic import with heritage References: <40c8d0d0$0$26780$636a15ce@news.free.fr> <40c9c54e$0$26793$626a14ce@news.free.fr> Message-ID: <21064255.0406111249.74894d3a@posting.google.com> marco wrote in message news:<40c9c54e$0$26793$626a14ce at news.free.fr>... > Gr?goire Dooms a ?crit : > > In your dhuile package, you need bidon in your namespace. > > This can be done by importing the module containing bidon's definition. > > According to what you say ("here my main"), this module is __main__ . > > > > So a simple > > from __main__ import bidon > > class vidange(bidon): > > pass > > should do the job. > > > > your statement doesn't work > but it works, if i do : > ------------------------- > import sys > sys.path.append("../..") > from main import bidon > ------------------------- > > does it exists a way to do it easier ? (i don't like this technick to > append a path to sys.path) > > > If you want your dhuile package to be more portable, it would be better > > to define bidon in a separate module (e.g. a "contenants.py" module ) > > and get both your main and dhuile import it. > > > > Hope it helps. > > -- > > Gr?goire Dooms > > > > marco wrote: > > > >> i try to make a dynamic import of a plugin which herits from another > >> class > >> > >> here my main: > >> ------------------------------------------------------------------- > >> class bidon: > >> pass > >> > >> plugin = __import__( "plugins.dhuile" , globals(), locals()) > >> ------------------------------------------------------------------- > >> > >> And in the file /plugins/dhuile/__init__.py, i've got : > >> ------------------------------------------------------------------- > >> class vidange(bidon): > >> def test(): > >> return "ok" > >> ------------------------------------------------------------------- > >> > >> python2.3 gives me : > >> "__init__.py : NameError: name 'bidon' is not defined" > >> > >> i don't understand where is the mistake ?! > >> (class "bidon" is in passed by the globals() ... but it seems > >> __init__.py doesn't understand) > >> > >> anybody have got an idea ? > >> thanx Try: import plugins.dhuile as plugin class vidange(plugin.bidon): def test(self): ... ... Should work Bonne chance. Regards Peter From tom at orderweb.co.za Wed Jun 30 13:24:02 2004 From: tom at orderweb.co.za (Tom) Date: 30 Jun 2004 10:24:02 -0700 Subject: Python Bounties References: Message-ID: David Wilson wrote in message news:... > Tom wrote: > > >The first of its kind in South Africa > > > > > Depending on your definition, Mark Shuttleworth had something similar > beforehand, also kind of Python-centric: > > http://www.markshuttleworth.com/bounty.html > > > David. Hi Bounty idea belongs to Mark who is known Python developer If you check http://www.go-opensource.org/ you will realize that in 2005 there will be huge increase in demand for open source software development in South Africa If you try to find companies providing this service, there is very few I have started http://orderweb.co.za to fill this gap I expect lots of potential future work Idea behind bounties is to give some of this work to Python community and make profit at the same time I have been using Python since 2001 I have developed portal, performed number of data migrations from one system to another, wrote schedulers to generate settlement instructions in mission critical environment, etc All this has been done for largest financial institutions in S.A in context of Securities Lending Industry. People there know who Tom is There is opportunity to sell open source to them but service level must be exceptional Lots of companies find themselves hold hostage by close source software I witnessed this on many occasions. Amounts of money being charged for solutions are huge P.S. I resigned my full time job today. From August 2004 I will work full time on http://orderweb.co.za From fumanchu at amor.org Thu Jun 10 12:35:27 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 10 Jun 2004 09:35:27 -0700 Subject: does python have useless destructors? Message-ID: Duncan Booth wrote: > "Robert Brewer" wrote in > news:mailman.819.1086881457.6949.python-list at python.org: > > > AFAICT, you don't need to reraise the exception. Example: > > > >>>> try: > > ... f > > ... finally: > > ... print 'finally' > > ... > > finally > > Traceback (most recent call last): > > File "", line 2, in ? > > NameError: name 'f' is not defined > > > > > > But I could be wrong--perhaps you've got a requirement I > can't see on > > first glance. > > I'll try to explain my intention a bit more clearly. As you > note, if the > try block throws then you don't need to re-raise the > exception. What I was > trying to do was to handle the case where the dispose code throws an > exception. If that happens when we already have an exception, > then I want > to mask the second exception and continue with the first, but > if it happens > when there is no exception I want the exception to be thrown. > > I am quite willing to be persuaded though that the correct > action would be > that an exception thrown in the dispose be allowed to mask the inner > exception. Yes, I think that was where I diverged: I'd rather not mask the error in dispose. > > def dispose(localdict, argnames): > you meant *argnames Actually, I meant argnames, and just didn't call it correctly. :) > > for name in argnames: > > obj = localdict.get(name) > > if obj: > > try: > > dispfunc = obj.__dispose__ > > except AttributeError: > > pass > > else: > > dispfunc() > > > > Close, but not quite there. I think you need to ensure that > all of the > __dispose__ methods *must* be called, even if an earlier one fails. Hmmmm... I'm not sure I agree. Again, we're talking about which error to raise from a potential host of them. I just find the linear approach more straightforward--if it errors, raise it. Otherwise testing becomes a royal pain. But then, I'm not coding nuclear reactors. Given that some apps will want guaranteed disposal calls and some won't, I'd prefer to push the desired exception handling into each __dispose__ method. Hmmm. No free brain cells at the moment. :( Thanks for the comments! Robert Brewer MIS Amor Ministries fumanchu at amor.org From klappnase at web.de Thu Jun 24 18:48:50 2004 From: klappnase at web.de (klappnase) Date: 24 Jun 2004 15:48:50 -0700 Subject: Tkinter and "jumpiness" References: Message-ID: Douglas Alan wrote in message news:... > I tried implementing your suggestion just to make sure that my > understanding is correct, and it behaved just as I expected -- i.e., > it didn't work. Is there some other more subtle usage of > wait_visibility() that you have in mind? > Oops.......not really, I guess I've been tired. Another idea: have you tried the "primitive" way: frame=Frame(master) <..create other widgets...> master.after(200, frame.pack) or even: root=Tk() root.withdraw() frame=Frame(root) <..create other widgets...> frame.pack() root.deiconify() > That's a good idea -- thanks. I'd prefer not to modify the > megawidget, if possible, though. It's third-party software, and then > I'll have to worry about backporting my changes into it whenever I get > new distributions. Also, the megawidget is not the only source of > jumpiness, so it only fixes part of the problem. Since my original > post, I've heard rumors that one can indeed get a Tkinter frame to > double-buffer, but I haven't quite been pointed at the how to > accomplish that. If that doesn't pan out, perhaps I'll have to resort > to tweaking the megawidget, as you suggest. > Just another thought: if the megawidget's scrollbars don't work properly maybe it's possible to disable them at initialization and add your own automatic scrollbars? > |>oug Michael From sandysj at juno.com Thu Jun 17 12:03:10 2004 From: sandysj at juno.com (Jeff Sandys) Date: Thu, 17 Jun 2004 16:03:10 GMT Subject: how to become a really good Python programmer? References: Message-ID: <40D1C0BE.76589710@juno.com> Randall Smith wrote: > > ... I want to become a really good > Python programmer. ... Find someone to pair program with. It would be cool if they were an expert, but it is ok if they aren't. You will learn more, program faster and see lots of possibilities when you pair program. Thanks, Jeff Sandys From Moiz.Golawala at ge.com Tue Jun 1 10:23:24 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Tue, 1 Jun 2004 09:23:24 -0500 Subject: Python with TestDirector Message-ID: Chuck, TestDirector is not written in python. It will support python (or VBScript, PerlScript etc..) as an external language to written your automated tests in. It uses COM objects to let python interact with test director tests and test steps. Moiz Golawala -----Original Message----- From: python-list-bounces+moiz.golawala=ge.com at python.org [mailto:python-list-bounces+moiz.golawala=ge.com at python.org]On Behalf Of Raaijmakers, Vincent (GE Infrastructure) Sent: Tuesday, June 01, 2004 9:28 AM To: python-list at python.org Subject: RE: Python with TestDirector For a couple of weeks, we are using with success Python with TestDirector. TestDirector 7.6, Python 2.2 and Mark Hammond's windows extensions. Please let me know if there are any questions. Vincent -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of Chuck Sent: Saturday, May 29, 2004 8:52 AM To: python-list at python.org Subject: Re: Python with TestDirector Hi, I'm not using Python with TestDirector but I know that our QA group uses it. I'm a software architect and I am very interested in increasing the use of automated testing within my company. We are primarily a Java shop but I write a bit of Python for this and that especially testing. I've used PyUnit, JUnit, NUnit etc. and am trying to get others to use these tools. I'd be interested in learning about how Python can be used in conjunction with TestDirector. What's the relationship - Is TestDirector written in Python? "Taylor, Martin" < cmtaylor at ti.com> wrote in message news:mailman.375.1085682168.6949.python-list at python.org... Limor Hevroni asked on Mon Apr 19 06:49:06 EDT 2004 if anyone was using Python for testing with TestDirector. I am doing this extensively and would welcome discussions with other people who are either doing it or are interested in doing it. Regards, C. Martin Taylor Sr. Test Automation Specialist Texas Instruments, Inc. Educational and Productivity Solutions 7800 Banner Dr. MS 3946 Dallas, TX 75251 -------------- next part -------------- An HTML attachment was scrubbed... URL: From opengeometry at yahoo.ca Sun Jun 6 14:48:42 2004 From: opengeometry at yahoo.ca (William Park) Date: 6 Jun 2004 18:48:42 GMT Subject: POP3 and email References: <6PFwc.742$8k4.38828@news20.bellglobal.com> Message-ID: <2ih789Fn67f3U2@uni-berlin.de> Paul Schmidt wrote: > > Dear list: > > I am new to python, and I am trying to figure out the short answer on > something. > > I want to open a POP3 mailbox, read the enclosed mail using the POP3 > module, , and then process it using the email module. > > Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo... > > There is some stuff that isn't clear here, can I pass the POP3 message > directly to email for processing, or does it need to be saved to a > temporary file somewhere first? The emails being received will consist > of headers, a tiny amount of text, and one or more MIME attachments. > > Let me explain the project, and then this should all make sense. > > > I havc one or more people going to an event, they will send emails to a > special email address, of stuff to go on a website. This is an HTML > page, which could have one or more photos attached to display in the > page once the HTML is processed, the whole thing gets FTP to the web. Probably, HTML form would be better interface for this kind of thing. But, in any case, you have Linux. This also means you already have Procmail/Fetchmail/Sendmail at your fingertips. -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From FBatista at uniFON.com.ar Wed Jun 16 14:25:39 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 16 Jun 2004 15:25:39 -0300 Subject: list to dict Message-ID: [Bart Nessux] #- What is the easiest/fastest way to build a dictionary from a #- list? The #- list contains 100,000 entries. What's the structure of the list? . Facundo From kjmacken at yorku.ca Tue Jun 15 15:39:54 2004 From: kjmacken at yorku.ca (Kevin MacKenzie) Date: 15 Jun 2004 12:39:54 -0700 Subject: NumTut for OS X (10.3.4) Message-ID: <18fe8c2.0406151139.725e56bf@posting.google.com> I am trying to download and install the NumTut package for Python 2.3 on MAC OS X. When installing Numeric using the MACPython IDE package manager does not install NumTut along with it. I am simply trying to locate and download the appropriate archive/installer for NumTut, built for MacPython 2.3. Any help is greatly appreciated. kjm From mark at prothon.org Tue Jun 29 02:49:56 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 28 Jun 2004 23:49:56 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> <7xacymeuwx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Mark Hahn" writes: >> Yes, a Prothon identifier is the same as a Python identifier except >> that it can end with an exclamation mark ( ! )or a question mark ( ? >> ). These marks can only appear at the end and there can only be >> one. It is up to the programmer to make sure he/she uses them >> properly. > > How do you parse > > a!=b As a! = b. Symbols are extracted by the lexer from left to right. Luckily accidently typing "a != b" as "a!=b" would cause a parser error since assignments aren't legal in expressions. Now that I see this example, maybe it would be a good idea to not allow it because of it's ambiguity. I'll put that up for a vote on our list. From beans at bedford.net Sun Jun 13 08:54:29 2004 From: beans at bedford.net (TomH) Date: 13 Jun 2004 05:54:29 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <7135e36e.0406130454.36b05c02@posting.google.com> Mediocre Person wrote in message news:<513d6f09f74eb423c810692fb7bb1f46 at news.teranews.com>... > Well, after years of teaching grade 12 students c++, I've decided to > make a switch to Python. > ... > > So, what pitfalls should I look out for in introducing Python to > students who have had a year of Visual BASIC? > ... I would replace the VB with Python, then teach SQL to the more advanced students. This exposes them to two entirely different approaches to computing. From esj at harvee.org Sun Jun 6 11:09:12 2004 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 06 Jun 2004 11:09:12 -0400 Subject: Python Wiki & wiki Hosting? In-Reply-To: <20040605115256.1749992717.eric@zomething.com> References: <20040605115256.1749992717.eric@zomething.com> Message-ID: <40C33398.7060501@harvee.org> Eric @ Zomething wrote: > Greetings Comrades, Pythonistas! > > I am looking for guidance on the quick and easiest path to set up a > Python wiki. as others have undoubtedly suggested, there are numerous python Wikis available. Let me give you an idea that might make wikis more usable by mere mortals. When I was CTO of a small startup, we used twiki to hold all of the development documentation. It worked reasonably well until the pages became quite large. Eventually, we all noticed that we didn't update our pages as we should because it was too much like work. Editing a markup language inside of a browser text area was lame. Even the CEO complained and said something we all should have recognized: "Why can't you edit wiki pages like you were in word". with that simple statement, I realized that wikis are fundamentally good tools but they are hampered, horribly hampered by the user interface. the project would be figuring out how to manipulate a wiki using a WYSIWYG infrastructure components such as abiword. The reason I suggest using abiword as the base is that it is a reasonable, lightweight word processor that can use plug-ins written in Python. ---eric From jcarlson at uci.edu Sun Jun 6 03:07:57 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 06 Jun 2004 00:07:57 -0700 Subject: repr of floating points In-Reply-To: References: Message-ID: > repr(0.1) is '0.10000000000000001', in my Python 2.3. > From reading the article "Floating Point Arithmetic: Issues and > Limitations", I understand that it's the closest 17-digit decimal > representation of the binary floating-point number actually stored. > > However, I don't understand why this should be what repr of floats > returns. repr should, if possible, return a string that evaluating it > will be == to the original object. But eval("0.1") obviously returns the > same floating point as 0.1 does! So why not make repr of floats return > the *shortest* decimal representation that will evaluate to the stored > binary number? Specifically, why not make repr(0.1) be "0.1"? Search the archives of python-dev. The answer lies within. Search before asking next time. - Josiah From mal at egenix.com Wed Jun 16 05:45:05 2004 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 16 Jun 2004 11:45:05 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: <1f7befae04061518082f839cb3@mail.gmail.com> References: <1f7befae0406142036442bf372@mail.gmail.com> <40CEFB48.7080807@egenix.com> <1f7befae04061518082f839cb3@mail.gmail.com> Message-ID: <40D016A1.2030707@egenix.com> Tim Peters wrote: > [M.-A. Lemburg] > >>The version that comes with mxNumber is GMP 3.1 which >>AFAIR does not have the multiplication optiomizations >>you were mentioning earlier in this thread. GMP 4.x should >>be a lot faster... but then people usually don't print >>large prime numbers every day :-) > > People who use GMP every day might surprise you . Most probably :-) >>FWIW, we're not working much on mxNumber anymore since it >>was basically a toy project to research decimal number >>interfacing in mxODBC. The licensing issues basically put >>us off here, so we're still waiting for a nice C level >>interface to one of the decimal type implementations >>for Python out there. > > > There should be a standard Decimal type in 2.4, but there won't be a C > interface at first (it's pure Python code -- in Python CVS > sandbox/decimal/). Will it be turned into a C implementation at some point ? > mxNumber isn't the same thing, but I've enjoyed > using it since you first released it. Thanks for doing it! Thanks. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 16 2004) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From grey at despair.dmiyu.org Thu Jun 3 13:57:07 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 17:57:07 GMT Subject: Background of editor in eric3 References: <2i8m0jFk8st1U1@uni-berlin.de> Message-ID: On 2004-06-03, MF wrote: > The right screen should look something like a book, black on white, anyway > light background... What your doctor, and many others, forget is that comparing a monitor to a piece of paper doesn't quite work. A piece of paper is reflective. It is reflecting the light that strikes it. A monitor is projective. It is projecting light. Because of this a white background on a monitor is not the same as white paper. It is more glaring and quite a bit of strain on the eyes; esp. in dark rooms. Ah, but most people would say to turn on the lights! Except most people use computers these days at work... with flourecent lighting. Monitors and flourecent lighting have something in common. They both flicker. We may not be able to conciously perceive it but it does happen. A 60Hz white screen in a room lit by flourecents is guarenteed to wig my eyes out in under an hour. A 60Hz black screen in a dark room and I can go for hours without any strain on my eyes. Personally I don't have anything over c8/c8/c8 on my screen if I can help it. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From tjreedy at udel.edu Thu Jun 17 11:35:44 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jun 2004 11:35:44 -0400 Subject: Parse ASCII log ; sort and keep most recent entries References: Message-ID: "Nova's Taylor" wrote in message news:fda4b581.0406161306.c5de18f at posting.google.com... > The log is an ASCII file that contains a process identifier (PID), > username, date, and time field like this: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 02AUG03 14:11:20 > 23 jonesjimbo 07AUG03 15:25:00 > 2348 williamstim 17AUG03 9:13:55 > 748 jonesjimbo 13OCT03 14:10:05 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 If you can get the log writer to write fixed length records with everything lined up nicely, it would be easier to read the log by eye (with fixed pitch font, which my newsreader doesn't use). It is also then trivial to slice a field out of the middle of the line. If one wants/needs to sort records by date, life is also easier if you can get the record writer to print dates in sortable format: YYYYMMDD. (I learned this 25 years ago.) > I want to read in and sort the file so the new list only contains only > the most the most recent PID (PIDS get reused often). If these are *nix process ids, this does not make obvious sense. Since pids are arbitrary, why delete a recent record because its PID got reused while keeping an old record because its PID happended not to? I could better imagine keeping all records since a certain date or the last n records (the latter is trivial with fixed len records). > In my example, the new list would be: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 17AUG03 9:13:55 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 > > So I need to sort by PID and date + time,then keep the most recent. That is one possibility: you have form a list of (key, line) pairs, where key is extracted from the line. > Any help would be appreciated! Alternative: instead of sort then filter duplicates, filter duplicates and then sort the reduced list. Assuming records are in date order from earlier to later, insert them into a dict with PID as key and entire record as value, and later records will replace earlier records with same key (PID). Then resort d.values() by date. Variation: if you cannot get dates stored properly for easy sorting, store line numbers with records so you can sort by line number instead of fiddling with nasty dates. Something like (incomplete and untested): d = {} for pair in enumerate(file('whatever')): d[getpid(pair[1])] = pair # getpid might be inline expression uniqs = d.values() uniqs.sort() new = [pair[1] for pair in uniqs] Terry J. Reedy From me at privacy.net Thu Jun 17 10:58:23 2004 From: me at privacy.net (Duncan Booth) Date: 17 Jun 2004 14:58:23 GMT Subject: Saving search results in a dictionary References: Message-ID: Lukas Holcik wrote in news:Pine.LNX.4.60.0406171557330.16166 at nymfe30.fi.muni.cz: > Or how can I replace the html &entities; in a string > "blablabla&blablabal&balbalbal" with the chars they mean using > re.sub? I found out they are stored in an dict [from htmlentitydefs > import htmlentitydefs]. I though about this functionality: You really don't want to use a regex for this. Remember that as well as forms like & you can equally use hex escapes such as & I suggest you consider parsing your HTML using sgmllib as that will automatically handle all the entity definitions without you having to worry about them. Likewise your question about extracting all the links in a single pass is much easier to do reliably if you use sgmllib than with a regular expression. From __peter__ at web.de Tue Jun 8 09:02:21 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 15:02:21 +0200 Subject: Using ConfigParse References: Message-ID: Zunbeltz Izaola wrote: > Peter Otten <__peter__ at web.de> writes: > >> Zunbeltz Izaola wrote: >> >> > def save(self): >> > print "Enter save" >> > self.write(open('defaultdifrac.cfg','w')) >> > self.read(open('defaultdifrac.cfg')) >> > print "OUt save" >> >> I would explicitly close the file before trying to read it. >> >> >>> def save(fn="tmp.txt", s="so what", close=True): >> ... f = file(fn, "w") >> ... f.write(s) >> ... if close: f.close() >> ... return file(fn).read() >> ... >> >>> save() >> 'so what' >> >>> save(s="another") >> 'another' >> >>> save(s="yet another", close=False) >> '' > > Thanks for the sugestion but it doen't work, i don't know wy > CofigParser doesn't write the file I looked it up in the source: the read() method expects a filename or a sequence of filenames. Incidentally that means, that every line in your config-file is interpreted as a filename. It doesn't matter that none of these files exist, as all IOErrors are silenced by the method. self.readfp(open('defaultdifrac.cfg')) or self.read("defaultdifrac.cfg") in your save() method instead of self.read(open('defaultdifrac.cfg')) should fix the problem. That would of course mean that ConfigParser *does* write the file, only doesn't read it back. Can you confirm that? Peter From __peter__ at web.de Fri Jun 4 02:54:23 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jun 2004 08:54:23 +0200 Subject: variables in string.count References: <59eb2b00.0406032201.4bf6926d@posting.google.com> Message-ID: ntg85 wrote: > Can you use variables in string.count or string.find? I tried, and > IDLE gives me errors. > Here's the code: I assume you omitted import string list = ["a", "b", "c"] > while list: > print > letter = raw_input("What letter? ") > string.lower(letter) Strings are immutable, i. e. they cannot be modified. Therefore the above should be: letter = string.lower(letter) or even better: letter = letter.lower() The string module is rarely needed these days as most functions are also available as string methods. > guess = string.count(letter, list) To check if a string (letter) is in a list, use the "in" operator: if letter in list: list.remove(letter) else: print "Try again!" > if guess == -1: > print "Try again!" > else: > list.remove(letter) > the error is: > TypeError: expected a character buffer object > Thanks. Note that list is also a Python builtin and should not be used as a variable name to avoid confusing the reader. For a complete list of builtins type dir(__builtins__) in the interpreter. Peter From BELLEMAIL-SA at exponent.com Mon Jun 14 00:24:11 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Sun, 13 Jun 2004 21:24:11 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28E20@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = segphault at sbcglobal.net Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 173 Scanning time = 06/13/2004 21:24:10 Engine/Pattern = 7.000-1004/903 Action taken on message: The attachment www.ecard.com.funny.picture.index.nude.php356.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From edwin at bathysphere.org Sun Jun 6 18:31:55 2004 From: edwin at bathysphere.org (Edwin Young) Date: 06 Jun 2004 15:31:55 -0700 Subject: Creating an RPM which works with multiple Python versions? Message-ID: Hi, I'm developing an application which is primarily in Python but has some C-coded extension modules. These modules aren't really useful to anyone other than the main application. The app works fine with Python 2.2 or 2.3, so ideally I'd like to create one install package which works with both. I have installation largely working using distutils to create a source tarfile and an RPM package. However I've noticed that the RPM installs the extension libraries to /usr/lib/python2.2/site-packages, even if python2.3 is the only version installed on the target machine - in the latter case, my app won't work. If I move the files to the python2.3 lib dir, it all seems to work, except that I get a RuntimeWarning at startup, indicating that the C libs were compiled against a different Python API version. What's recommended here? I can see 3 options: 1) Somehow convince RPM to install the extensions to the directory for the version of Python that's installed. Any clues how? 2) Produce separate 2.2 and 2.3 packages. This is kind of a pain for users, so I'd rather not if possible. 3) Install the modules somewhere unrelated to the python tree (eg /usr/lib/appname-appver/ and change the python library path in the app to find them. Any suggestions? Also, how can I tell if the RuntimeWarning is important? (and eliminate it, if not?) I make fairly minimal use of the API and everything *looks* like it works, but I don't want to risk memory corruption. Thanks, -- Edwin From fredrik at pythonware.com Fri Jun 18 08:23:10 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Jun 2004 14:23:10 +0200 Subject: Queue module and Python Documentation Rant References: <6bl9q1-e98.ln1@home.rogerbinns.com> <40D240E9.6070801@hotmail.com> Message-ID: Bart Nessux wrote: e: > > > There is a qsize() method clearly documented. What is wrong with > > that? > > Where??? The documentation for the module named Queue says nothing at > all about this... it's the *first* item in the section that describes how Queue objects work: ... The public methods are: qsize() Return the approximate size of the queue. ... what's wrong with you? From klachemin at home.com Thu Jun 10 16:04:26 2004 From: klachemin at home.com (Kamilche) Date: 10 Jun 2004 13:04:26 -0700 Subject: Creating True Global Functions by Modifying Builtins References: <889cbba0.0406090951.32a6434b@posting.google.com> <45adnQYny6eOzFrdRVn-sw@powergate.ca> Message-ID: <889cbba0.0406101204.7a83b5f3@posting.google.com> Peter Hansen wrote in message news:<45adnQYny6eOzFrdRVn-sw at powergate.ca>... > The only time I've found a valid reason to stick stuff in __builtin__ > is when trying to make current code *forward compatible* with newer > versions of Python, such as when bool() and True/False where added > in 2.2 (?) and we had to stick with 2.0. > Um , that's a good idea, even in version 2.3. I don't know how many times I've written 'true' instead of True. I think that deserves a place in the globals file. From segphault at sbcglobal.net Sat Jun 12 15:51:38 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 12 Jun 2004 19:51:38 GMT Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: On Sat, 12 Jun 2004 14:45:21 +0000, Mediocre Person wrote: > Well, there's OOP and then there's OOP, right? The first year students > have learned to _use_ pre-defined objects, but not design and create > classes. That makes sense. If they haven't learned to create objects yet, then python is probably the most practical way to teach it. > Can you give me some references to this, such as samples of student > work? I would like to see what grade 6 students can do in two months! This was part of a special program at my former junior high school. They offered a single semester computer programming class as an 'elective'. Thematically, the class focused on using object oriented idioms to solve problems. Most of the assignments were designed to emphasize the power and flexibility of OO. I think that the immediate and consistent focus on OO was part of what made them capable of doing so much, so quickly. Towards the end of the semester, they were working in groups, writing games. Their devotion to their work was somewhat inspiring. Many of them put in many extra hours to improve their work, and they developed a sort of competitive enthusiasm, challenging each other with small problems and comparing their solutions. The instructor of that programming class is doing a summer program with some of the students that will involve putting together a web site about the programming class that will showcase some of the student programs. He wants to teach them how to use mod_python. As soon as he gives me the address, i'll be sure to post it on a.l.p, as i'm sure there are many here who would be interested. > I agree that the syntax of Python makes it is easy to learn. However, I > think I've got a pretty good imagination where material is concerned! > There are excellent tie-ins to their mathematics, physics, chemistry, > and biology curricula. For instance, I recently came across the concept > of partitions in number theory, and computing all the partitions of an > integer is a dilly of a pickle of a problem! This is obviously why I'm not a teacher and you are. =} Sounds like you have some creative ways to tie it into general curriculum. > And, of course, it's really not about the language, in the end, after > all, but what you can learn to do with it. In which case, you say, > "AHA--so what was wrong with c++???" In a word, nothing. And I'll *miss* > all the lovely memory management lessons we did to develop our own > vector and list classes. I'd never ask "what is wrong with c++", because I'm already painfully aware of the answer: almost everything. I completely understand the motivation for moving away from it. When I write c++ I spend more time thinking about how to deal with the language's severe flaws, rather than how to get the job done. >I know nothing about ocaml or haskell, but I'll be sure to research them > this summer, so thanks for the tip! Really, it depends on what your goals are, and what you believe the capacity of the students to be. If you are introducing object oriented programming, python is a good choice, especially if the students have never been exposed to anything like python before. I know that if, in my senior year of high school, I had seen a python class offered, I would probably have laughed at the prospect, and taken something more challenging. OCaml is also free, and it also provides an interactive top-level. It has automatic memory management, and type inference. It is statically typed, and that makes it significantly more challenging to use effectively. OCaml has some interesting features, and learning to use them well requires a lot of thought, and careful attention to detail. Some aspects altered the way I think about programming logic (particularly: pattern matching, recursive types, stateless OO, and parametric polymorphism.) Based on what you have said, it sounds like python may be the best choice for your students at this point. I live in california, and the schools in my immediate vicinity all have very strong (well funded) tech programs. There are computers in most of the classrooms, and a simple computer science class is required for all students at the junior high, so the level of the students here is probably not indicative of students everywhere, and I hadnt really stopped to think about that before I made my post last night. As far as teaching python is concerned, the Edu-Sig is probably the best place for you to start. http://python.org/sigs/edu-sig/ You find this specific link insightful, it talks about python at a high school level: http://python.org/workshops/2000-01/proceedings/papers/elkner/pyYHS.html Best of luck! --segphault From eppstein at ics.uci.edu Thu Jun 17 02:21:08 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 16 Jun 2004 23:21:08 -0700 Subject: datetime, calendar, time intervals References: <95aa1afa.0406162213.3cf3d7f7@posting.google.com> Message-ID: In article <95aa1afa.0406162213.3cf3d7f7 at posting.google.com>, michele.simionato at poste.it (Michele Simionato) wrote: > Strangely enough, I never needed the datetime and calendar module > before, so I just looked at them today. Me too. datetime was exactly what I wanted. Until I realized that it wasn't available in the 2.2.3 installation I needed my code to run in... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From jdhunter at ace.bsd.uchicago.edu Thu Jun 10 11:36:11 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 10 Jun 2004 10:36:11 -0500 Subject: Problems installing pymat - missing libraries In-Reply-To: ("Roy Yves"'s message of "Thu, 10 Jun 2004 10:21:14 -0400") References: Message-ID: >>>>> "Roy" == Roy Yves writes: Roy> error: Failed dependencies: libeng.so is needed by Roy> pymat-1.1.90-1 libmat.so is needed by pymat-1.1.90-1 libmx.so Roy> is needed by pymat-1.1.90-1 libut.so is needed by Roy> pymat-1.1.90-1 Roy> What should I do to get those missing libraries ? What are Roy> they ? These are matlab libraries (pymat requires matlab). On my system (linux), they are located in /usr/local/matlab/extern/lib/glnx86. I'm not sure how RPM handles the resolution of shared libraries. It may be enough to add the path containing these libraries to LD_LIBRARY_PATH and then run /sbin/ldconfig before rerunning the rpm installer. JDH From peufeu at free.fr Fri Jun 18 04:52:04 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 10:52:04 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: > I'm new to python. To my eyes this is a pretty poor attempt to > have static variables. I've implemented in the past a few static variables in python def accumulate( x ): accumulate.accumulator += x return accumulate.accumulator accumulate.accumulator = 0 -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From nicksjacobson at yahoo.com Mon Jun 7 03:37:46 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 7 Jun 2004 00:37:46 -0700 Subject: exec throws an exception...why? References: <3415c0lg306oec1a69c3mkolnbhfbku243@4ax.com> <8ef9bea6.0406060718.39f1001b@posting.google.com> Message-ID: Thank you very much for the detailed response. But there's still a problem. > The name binding in assignment seems to proceed only for locals, > unless a variable is declared as global explicitly. That is, by > default, the supplied global dictionary is read-only, unless the > 'global' statment is used explicitly for those variables that you want > to override. Agreed. The global dictionary is not modified. But here's the thing. From the Python Ref. Manual: "If the [local variable] definition occurs in a function block, the scope extends to any blocks contained within the defining one..." So as long as code is not on the module level, scopes are extended. e.g. this works fine: def main(): y = 3 def execfunc(): print y execfunc() if __name__ == '__main__': main() But, the following code fails, saying that y is undefined: def main(): s = \ """ y = 3 def execfunc(): print y execfunc() """ d = {} e = {} exec s in d, e if __name__ == '__main__': main() Why not? Because it doesn't realize it's in main()! It thinks it's on the module level! (I guess the indentation is a clue.) Now, if it WERE simply code on the module level, it would also work: y = 3 def execfunc(): print y execfunc() because as you explained, y goes in globals(). This is probably why the scopes don't nest at this level: they normally don't need to. Conclusion: Is code from the exec statement on the module level or not? It doesn't get its locals mapped to globals. But it also doesn't get its local variables nested. So it gets neither benefit. IMO it should get one or the other. i.e. the second piece of code should work. --Nick From dkturner at telkomsa.net Sun Jun 13 13:24:14 2004 From: dkturner at telkomsa.net (David Turner) Date: 13 Jun 2004 10:24:14 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: Carl Banks wrote in message news:... > David Turner wrote: > > Well-defined destructor semantics have proven to be a robust, > > reliable, and surprisingly general solution to a wide range of > > problems. It wouldn't be *that* hard to implement them in Python - so > > why not adopt a good idea? > > Wrong. It would be almost impossible in Python. > > > Python can never rely on someone not taking a reference to your > resource-owning object. Anyone can store an open file object in a > list, for example, and there might even be good reasons to do it. > Thus, you can never guarantee that the garbage collector will pick up > the object when the function exits, even if it were perfect. Carl, I'm sorry, but you've *completely* missed the point here. (a) I've stated several times already that we're *not* talking about __del__ being called if/when the object is garbage collected. Garbage collection/finalization are completely different things to destruction. (b) So what if multiple references to a deterministic object can be made? It really doesn't matter. The point is that the destruction of the object is still predictable. > OTOH, if you indiscreetly finalize (for example, calling close on a > file object) any resource-owning object as soon as the function that > created it exits, not waiting for garbage collector to pick it up, > then you've pretty much stepped on the toes of someone else > it. That is *not* what I suggested. Please read my suggestion again. > It seems to me that you are failing to taking the possibility that > these thing can happen into account. But, in Python, they can and do. > Finalizing an object as soon as the name binding it goes out of scope > is not always the right thing to do. I never said it was. I'm not going to bother responding to the rest of your post. Please read my original suggestion again. In case you can't find it, here is yet another precis: Objects that define __del__ shall have a reference count, which is incremented when names are bound to the object and decremented when those names go out of scope. The __del__ method is called when the reference count reaches zero. This mechanism is orthogonal to garbage collection. Regards David Turner From agriff at tin.it Wed Jun 16 17:48:21 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 16 Jun 2004 21:48:21 GMT Subject: mutable default parameter problem [Prothon] References: Message-ID: On Wed, 16 Jun 2004 12:40:10 -0700, "Mark Hahn" wrote: >In Prothon: > > def foo(x): > print foo.list.append!(x) > foo.list = [] > >(Sorry. I couldn't resist bragging.) The very first thing I tried was assigning foo.list outside of the function (and, by the way, that works in python too); this however doesn't mimic C++ static, as initialization of the static local variable is done in C++ when (and only IF) the function is entered. The value used for initialization can for example depend on local parameters or global state at *that time*. Using "hasattr" seemed ugly to me at first, but after all you need an additional flag anyway, so why not checking the presence of a certain key in foo.__dict__ ? That way both initialization and setting the flag are done at the same time using just one clean statement. The only (very small) syntax price is the if (that in C++ is implicit in the overused keyword "static"). Andrea From http Thu Jun 10 17:02:06 2004 From: http (Paul Rubin) Date: 10 Jun 2004 14:02:06 -0700 Subject: Needed, symbolic math in Python Message-ID: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> I wonder if anyone can recommend any simple symbolic algebra modules in Python. I just need to do some straightforward polynomial arithmetic, no fancy calculus or special functions anything like that. But I do need arbitrary precision rational coefficients in the polynomials. Thanks. From kveretennicov at yahoo.com Tue Jun 8 06:04:17 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 8 Jun 2004 03:04:17 -0700 Subject: left-quote ( ` ) on International keyboards [Prothon] References: Message-ID: <5155aad2.0406080204.739fd83c@posting.google.com> "Mark Hahn" wrote in message news:... > Can users with international keyboards tell me if they have problems typing > the left-quote ( ` ) character? It isn't used much in Python but we are Single keystroke for me (Cyrillic/Russian). -kv From llothar at web.de Thu Jun 3 16:33:01 2004 From: llothar at web.de (Lothar Scholz) Date: 3 Jun 2004 13:33:01 -0700 Subject: Why did no one invent Python before? References: Message-ID: <6ee58e07.0406031233.51b5ad0c@posting.google.com> Sion Arrowsmith wrote in message news:... > j_mckitrick wrote: > >Seriously, why is a language like this only NOW appearing? > > As others have pointed out, Python has been around for a good > decade (as have a number of other powerfully expressive > languages, particularly in the functional camp). A more > pertinent question might be why, when languages like this > appeared some time ago, are monstrosities like C# still being > created? Speed and Safer Design of Programs (statically typed). From tmohr at s.netic.de Tue Jun 8 04:27:57 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 08 Jun 2004 10:27:57 +0200 Subject: tp_getattrfunc, access members that are a list References: Message-ID: >> Can anybody describe me how i can access the array d[8] >> as a list? I'd like to get AND set values in there. > > I don't think you can expose them as a list, but you should look into > structmember.h, and it's PyMemberDef to expose the items separately. Hi, i've looked into structmember.h, but nothing (like e.g. a flag) can mark that member as an array. Also, i can't just export every single array member, as i need to access them indexed, e.g. in a for() for clearing, for setting calculated values, ... In the documentation i read that accessing arrays should be done by getattr/setattr functions. This must be possible somehow... Best regards, Torsten. From dummy at scriptolutions.com Mon Jun 14 21:49:25 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Tue, 15 Jun 2004 03:49:25 +0200 Subject: Searching for the best scripting language References: Message-ID: On Mon, 14 Jun 2004 19:01:28 -0400, Peter Hansen wrote: >Lothar Scholz wrote: > >> On Mon, 14 Jun 2004 11:15:01 -0700 (PDT), Adelein and Jeremy >> wrote: >> >> >>>The answer to this search is not sh, its vastly improved younger >>>brother Perl, nor even the OO-capable Ruby. The answer is a new >>>language I am developing, called fortytwo. fortytwo is completely >> >> >> >> >> A lot of text, but no url ? > >No url, and not even a smiley! (Hint hint) > >See also "The Hitchhiker's Guide to the Universe" and the answer >to the problem of life, the universe, and everything. > >Lothar, read Jeremy's last paragraph again and then reconsider >what he was saying in the first paragraph in light of that. :-) > Thanks ! I was to lazy to read more then the first paragraph :-) From jmdeschamps at cvm.qc.ca Wed Jun 9 10:36:10 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 9 Jun 2004 07:36:10 -0700 Subject: Is Windows + Python + Ming (SWF/Flash) Possible ? Message-ID: <3d06fae9.0406090636.5b7a921@posting.google.com> I have yet to find a way to compile the source of Ming (a library to produce SWF files (Flash), http://ming.sourceforge.net/) to run from Python under Windows XP Even with some help (from a C++ 'nix senior programmer), I just can't make it (SIGH) Did anyone reading this ever mage it work??? The PHP module seems very popular (even available in binaries :0 ), but I'd rather program in Python! Thanks for any help, advice, hints, or (please) access to the binaries. Jean-Marc PS I'm a very high level language programmer, specialised in scripting from way back (Hypercard, Toolbook) and user of highly automated tools such as VB, C++Builder, etc, so I lack proper understanding of make files, linkage, symbol tables and such stuff I read about when I try myself at changing a recipe to compile source (because the posted method doesn't work, naturally!)- I'm sure its all very cool, and yes if I had a lot of free time it would be nice to invest in learning that stuff ! From NOmanlio_perilloSPAM at libero.it Thu Jun 17 03:53:37 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Thu, 17 Jun 2004 07:53:37 GMT Subject: variables is regexp Message-ID: Hi. It would be nice to have the possibility to define variables inside regexp. Ad example: (?$identifier=regexp) for defining variables (?$identifier) for accessing variables. Thanks and regards Manlio Perillo From BELLEMAIL-SA at exponent.com Thu Jun 17 11:57:23 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 08:57:23 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EB0@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = richie at entrian.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 234 Scanning time = 06/17/2004 08:57:23 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment secrets.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From peter at engcorp.com Wed Jun 16 19:41:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 19:41:58 -0400 Subject: Parse ASCII log ; sort and keep most recent entries In-Reply-To: References: Message-ID: Nova's Taylor wrote: > I am a newbie to Python and am hoping that someone can get me started > on a log parser that I am trying to write. > > I want to read in and sort the file so the new list only contains only > the most the most recent PID (PIDS get reused often). In my example, > the new list would be: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 17AUG03 9:13:55 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 > > So I need to sort by PID and date + time,then keep the most recent. I think you are specifying the implementation of the solution a bit, rather than just the requirements. Do you really need the resulting list to be sorted by PID and date/time, or was that just part of how you thought you'd write it? If you don't care about the sorting part, but just want the output to be a list of unique PIDs, you could just do the following instead, taking advantage of how Python dictionaries have unique keys. Note that this assumes that the contents of the file were originally in order by date (i.e. more recent items come later). 1. Create empty dict: "d = {}" 2. Read data line by line: "for line in infile.readlines()" 3. Split so the PID is separate: "pid = line.split()[0]" 4. Store entire line in dictionary using PID as key: "d[pid] = line" When you're done, the dict will contain only the most recent line with a given PID, though in "arbitrary" (effectively random) order. If you don't care about the order of the final result, just open a file and with one line the reduced data is written out: newfile.write(''.join(d.values())) -Peter From craigb at ati-uk.com Thu Jun 3 10:05:57 2004 From: craigb at ati-uk.com (Craig) Date: Thu, 3 Jun 2004 15:05:57 +0100 Subject: newbie question about import References: <10bu894hg9q6379@corp.supernews.com> <10bu94apffq0tcf@corp.supernews.com> Message-ID: <10buc2aareg20f8@corp.supernews.com> ok, so i understand that there are important differences between import and #include, but the thing i don't get is why you can't do something like import "d:\dev\build\config.py"? is it good style to do this to get the above behaviour: import sys sys.path.append(/my/include/path) import my-include-file "Craig" wrote in message news:10bu94apffq0tcf at corp.supernews.com... > anwering my own query...i see that this a common question amongst python > newbies. i shall look around the web a bit and see if i can work it out. > > "Craig" wrote in message > news:10bu894hg9q6379 at corp.supernews.com... > > hi all, > > > > is there a python equivalent to the C preprocessor statement #include > > relative-or-absolute-path? > > i want to import code in a specific file into my script. > > > > thanks, > > craig > > > > > > From onurb at xiludom.gro Sat Jun 5 08:47:38 2004 From: onurb at xiludom.gro (bruno modulix) Date: Sat, 05 Jun 2004 14:47:38 +0200 Subject: if does not evaluate In-Reply-To: <2ids8kFmfpi0U1@uni-berlin.de> References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: <40c1c269$0$21571$626a14ce@news.free.fr> Jim Newton a ?crit : > A question that has bothered me ever since looking at python > the first time is that not everything evaluates to something. > I am wondering what is the reason for this. Would making > everying evaluate have caused the langugage to be less > efficient execution-wise? or was it a choice to enforce some > sort of standard? > > I've read a few discussions about the fact that there is > no if/then/else operartor. > > Wouldn't this problem be easily solved by making the built > in keywords actually be evaluatable. > > I.e., x = if something: > expr1 > else: > expr2 > > parentheses would of course be optional as they are for > all expressions. > Python is, by design, an 'instruction-based' language, not an 'expression-based' language. Search this ng for discussions on the inclusion of ternary operator if you want to learn more about this point... Now if you're looking for a language pretty similar to Python (very-hi-level, highly dynamic, interpreted, clean and readable syntax, friendly and enthusiast communauty etc) where everything's an expression, you may want to try Ruby. It's not as easy to learn, it as its own warts too, and it has not yet reached such a 'critical mass' as Python in terms of libs and communauty, but it's a really nice and usable language too. Bruno (who likes both languages...) From it2gati at ituniv.se Thu Jun 24 10:00:37 2004 From: it2gati at ituniv.se (Tim Gahnstrom) Date: Thu, 24 Jun 2004 16:00:37 +0200 Subject: rdff-backup / python linux fat32 In-Reply-To: References: Message-ID: Peter Hansen wrote: > Tim Gahnstrom wrote: > >> rdiff-backup is aperently written in Python and when I run it in a >> special way I get some funy Python errors. Does anyone know if linux >> File "/usr/lib/python2.3/gzip.py", line 94, in __init__ >> fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') >> IOError: invalid mode: wb > > > That line "should" execute, AFAICS. Try this, after changing the > directory to the drive that is failing: > > -bash-2.05b$ python > Python 2.3.3 (#1, May 7 2004, 10:31:40) > [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 > >>> import gzip > >>> gzip.GzipFile('test.file', 'w') > > If it reports the same error, then the problem is just in Python > or your USB (or FAT32) drive. > > If it doesn't report the same error, it seems likely that rdiff-backup > has substituted the builtin open() function with its own, for reasons > unknown... At least, that's the only thought that occurs to me. > >>> import gzip >>> gzip.GzipFile('test.file', 'w') >>> Hmm, that seemed to work like a charm so off to look for an other source of the error. thanks Tim From htx1 at gmx.de Tue Jun 8 09:50:28 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Tue, 08 Jun 2004 15:50:28 +0200 Subject: Passing parameters using **kargs In-Reply-To: References: Message-ID: Thomas Philips wrote: > In this case, I'm being driven by intellectual curiosity - though I do > think the ability to create a string representation of a variable name OK, try this: def a (x): y = "Hello" print locals () a ("World") > could be useful when printing, and the ability to create a variable > whose name is specified in a string could be useful when creating > on-the-fly code. This sounds like you had prior exposure to PHP or Perl, where one could do things to print "Hello" like $a = "b"; $$a = "Hello"; print $b You can do such things in python, too. In the global namespace >>> globals () ["u"] = "Hello" >>> u 'Hello' >>> and in class instances using setattr, but *not* with local variables in functions, because for optimization purposes the interpreter does not look them up in the locals dictionary. In my opinion, these described practices are neither clean nor particularly useful anyway. And things like this can happen in your on-the-fly code: >>> globals () ["i+j"] = "Yuck" >>> What now? Better don't do it. Greetings, Holger From jepler at unpythonic.net Tue Jun 1 12:47:23 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 1 Jun 2004 11:47:23 -0500 Subject: HTTP Proxy server in python In-Reply-To: <20040601051333.027694C0D6@spy10.spymac.net> References: <20040601051333.027694C0D6@spy10.spymac.net> Message-ID: <20040601164723.GB19278@unpythonic.net> "Fishboy" has already suggested using Squid. My recollection is that there's an add-on product for squid, called squidguard, which can track and limit usage. When I was in this situation, squidguard distinguished between users by using HTTP Proxy Authentication, but it may be possible to set it up to use IP addresses or something else. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From brianc at temple.edu Wed Jun 23 09:48:23 2004 From: brianc at temple.edu (brianc at temple.edu) Date: Wed, 23 Jun 2004 09:48:23 -0400 Subject: Testing for membership speed Message-ID: <5815b314.54f9a743.8213b00@po-d.temple.edu> I just ran this stuff for my own knowledge. Though it might be useful to some other people to know and maybe spark a discussion. I needed a fast way to test for membership, so naturally the choices were the builtin containers: lists, dictionaries, and tuples. The following is the test code and results: import timeit lst_i=timeit.Timer('random.randrange(10000) in l','import random; l=range(10000)') dct_i=timeit.Timer('l.has_key(random.randrange(10000))','import random; l=dict([(i,None) for i in xrange(10000)])') tup_i=timeit.Timer('random.randrange(10000) in l','import random; l=tuple(range(10000))') lst_str=timeit.Timer('md5.md5(str(random.randrange(10000))).hexdigest() in l','import random,md5; l=[md5.md5(str(i)).hexdigest() for i in xrange(10000)]') dct_str=timeit.Timer('l.has_key(md5.md5(str(random.randrange(10000))).hexdigest())','import random,md5; l=dict([(md5.md5(str(i)).hexdigest(),None) for i in xrange(10000)])') tup_str=timeit.Timer('md5.md5(str(random.randrange(10000))).hexdigest() in l','import random,md5; l=tuple([md5.md5(str(i)).hexdigest() for i in xrange(10000)])') print 'Integer lookup' r=lst_i.repeat(100,100); print 'list:',min(r),max(r); r=dct_i.repeat(100,100); print 'dict:',min(r),max(r); r=tup_i.repeat(100,100); print 'tupl:',min(r),max(r); print 'String lookup' r=lst_str.repeat(100,100); print 'list:',min(r),max(r); r=dct_str.repeat(100,100); print 'dict:',min(r),max(r); r=tup_str.repeat(100,100); print 'tupl:',min(r),max(r); [[[Ran on IRIX64 6.5, 24 processors, 12G Memory, 4G Swap, this code only uses one processor at %100 the full length of the run]]] Python 2.2.3 (#1, Nov 25 2003, 18:58:21) [C] on irix646-n32 Type "help", "copyright", "credits" or "license" for more information. >>> ## working on region in file /usr/tmp/python-119959673PMu.py... Integer lookup list: 0.126830816269 0.160212993622 dict: 0.00362300872803 0.00385618209839 tupl: 0.119297981262 0.161748170853 String lookup list: 0.142526865005 0.188524961472 dict: 0.00711393356323 0.00760197639465 tupl: 0.143892049789 0.186873912811 >>> The results are conclusive, go for dictionaries. But this surprised me a little, anyone have insight as to why? I was also surprised that tuples and lists scored exactly the same. I was hoping that immutable tuples might earn it some speed over lists. I will eventually need this for testing strings. So the doubling of speed for strings over integers for dictionaries is a little alarming. Lists and tuples only saw a modest increase. Thank you in advance for any clever tricks you suggest. -Brian From candycane1828 at hotmail.com Thu Jun 10 10:03:53 2004 From: candycane1828 at hotmail.com (candycane1828 at hotmail.com) Date: Thu, 10 Jun 2004 22:03:53 +0800 Subject: Message Message-ID: Your document is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: message_details.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From gherron at islandtraining.com Sat Jun 5 04:35:37 2004 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 5 Jun 2004 01:35:37 -0700 Subject: write a bitmap using python In-Reply-To: References: Message-ID: <200406050135.37278.gherron@islandtraining.com> On Saturday 05 June 2004 12:58 am, lyuan wrote: > Hi, > How can I write a bitmap using python? I have some integer data and > want to generate a bitmap graph for visualization. Any suggestion will > be appreciated. > Sorry if this is an FAQ, BTW, where can I find the FAQ of this list? > > thanks > Lihua The Python Image Library (PIL) is probably what you want: http://www.pythonware.com/products/pil/ Gary Herron From qrczak at knm.org.pl Mon Jun 14 04:52:46 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Mon, 14 Jun 2004 10:52:46 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 14 Jun 2004 00:05:45 -0700, David Turner wrote: > You don't need static knowledge of which names refer to deterministic > objects. You only need to know at three points: when binding a name, > when exiting a function scope, and when calling __del__ on an object. You must manage reference counts on any parameter passing (increment), function return (decrement refcounts of local variables), function result (increment the refcount of the value being returned if it's a constant or a global variable), and assignment (increment one defcount, decrement another). Each decref is accompanied with a test for 0. This is a high overhead. You basically impose the overhead CPython has to all implementations, even those which already manage liveness of their objects using a better GC scheme. It doesn't help that only some objects must have reference counts changed, because you statically don't know which are these, so you must check all potential objects anyway. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From jfranz at neurokode.com Mon Jun 7 17:54:09 2004 From: jfranz at neurokode.com (Jonathan M. Franz) Date: Mon, 07 Jun 2004 17:54:09 -0400 Subject: Storing files in a BLOB field via SQL Message-ID: <40C4E401.4060103@neurokode.com> >cur = conn.cursor() >cur.execute("INSERT INTO table (order,data) VALUES (?,?)", (order, data)) >and the DBAPI/Database driver takes care of the rest. No... it may sometimes, but you really should use .setinputsizes() with the Types defined in the module so that the DBAPI module and driver have some clue of what you're doing. Not all dbapi modules are very smart about types, so its a good idea to get in the habit of doing .setinputsizes() and .setoutputsizes(). In the above example, the module doesn't know the difference between a normal string and a python string object holding a binary string... so you should do the following before the execute: cur.setinputsizes(dbapi_module.STRING, dbapi_module.BINARY) This assumes 'order' is a string... sub NUMBER if it is a numeric value. Alternately, if data is wrapped in via the Binary() constructor, this step could be skipped, ie: EncData = dbapi_module.Binary(data) # now use EncData where data was in the .execute() call PS: this was typed in a hurry: I hope it helps, but it might have errors. From abra9823 at mail.usyd.edu.au Wed Jun 30 02:14:48 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 30 Jun 2004 16:14:48 +1000 Subject: maintaining session/context Message-ID: <1088576088.40e25a5860b34@www-mail.usyd.edu.au> hi! I am developing an application where the user will progressively create a template file, each time progressively adding more information i have explored echoing form data back each time using hidden fields and i cant user a db. What approach would you suggest? i suppose i could use cookies but then i will have a large number of name-value pairs. With files, comes the expense if disk I/O. Also if i use files, is there a way to write an object to a file, i.e, serialize an object and read/write to/from a file. thanks -- Ajay Brar, ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From Scott.Daniels at Acm.Org Sat Jun 26 11:58:44 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 26 Jun 2004 08:58:44 -0700 Subject: Zero-fill shift In-Reply-To: References: <40990BC8.7000306@cs.yorku.ca> Message-ID: <40dda218$1@nntp0.pdx.net> Eli Stevens (WG.c) wrote: > Daniel Orner wrote: > >>Great, this works. 8-) Unfortunately, I've run into another problem. >>In the Java algorithm, two integers are added. This often results in >>an overflow and a negative number, which is the desired result.... > > But more to the point: Here's something that will do the trick if your > overflow isn't ever more than one bit.... And if you want to be able to handle multibit overflow: SIGN_BIT = 2 ** 7 # 31 if you prefer 32-bit signed numbers def wrap(n): if n & SIGN_BIT: return n | -SIGN_BIT else: return n & (SIGN_BIT - 1) -- -Scott David Daniels Scott.Daniels at Acm.Org From ahaas at airmail.net Wed Jun 16 12:09:35 2004 From: ahaas at airmail.net (Art Haas) Date: Wed, 16 Jun 2004 11:09:35 -0500 Subject: [ANNOUNCE] Sixteenth release of PythonCAD now available Message-ID: <20040616160935.GB3093@artsapartment.org> Hi. Due to packaging problems in the fifteenth release, and a code snafu the bit the Cocoa interface, I'm releasing the sixteenth version of PythonCAD. The missing Cocoa files have been added, and a patch addressing the Layer problems on Cocoa have been applied. Additionally a small patch for chamfers and fillets is in this release as well, but otherwise this release is identical to the fifteenth release. My thanks to David Haas for contributing the Cocoa interface code, and resolving the problems in the fifteenth release. Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From zunbeltz at wm.lc.ehu.es.XXX Tue Jun 8 05:30:11 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 08 Jun 2004 11:30:11 +0200 Subject: Using ConfigParse Message-ID: Hi to all ! I've subclassed ConfigParse in the folowing way. class DifracConfigParser(ConfigParser): def __init__(self, defaults=None): ConfigParser.__init__(self, defaults) self.readfp(open('defaultdifrac.cfg')) def save(self): print "Enter save" self.write(open('defaultdifrac.cfg','w')) self.read(open('defaultdifrac.cfg')) print "OUt save" I use the values from the defaultdifrac.cfg file in my dialogs (using wxpython) and change them via validators. After closing a dialog that changes the values (after validating) i call de save method, but the file is not changed. Any Idea? Thanks in advance Zunbeltz -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From scrutinizer at gmx.at Sat Jun 26 08:47:15 2004 From: scrutinizer at gmx.at (Francesco) Date: Sat, 26 Jun 2004 14:47:15 +0200 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Sat, 26 Jun 2004 18:31:08 +1000, Sticks wrote: >i'm new to python and i was wondering what editors people prefer to use >and why. Pype: it is open source, has a classbrowser, is very customisable, code completition, ... DrPython: same as pype, very active development; python shell integrated. both can be found on sourceforge. -- Francesco From peter at engcorp.com Fri Jun 25 09:02:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jun 2004 09:02:34 -0400 Subject: question about cx_Oracle .thanks In-Reply-To: References: <2k2eq0F17aa0uU1@uni-berlin.de> Message-ID: Steve Holden wrote: > which you will (I hope) appreciate does not just apply to Python. Python > is confusing you by showing you the contents of your tuple as accurately > as possible: your computer actually stores 4205.66 as 42505.660000000003 Or, more precisely, it stores it as the binary number represented here by these hexadecimal digits (shown here in big-endian format): >>> binascii.hexlify(struct.pack('>d', 42055.66)) '40e488f51eb851ec' Since it has a limited number of binary digits available, it can't store precisely 42055.66, so 42055.6600000whatever is the next closest. To demonstrate, the nearest neighbours that can be represented accurately are these (binary value one higher or lower): >>> struct.unpack('>d', binascii.unhexlify('40e488f51eb851ed')) (42055.660000000011,) >>> struct.unpack('>d', binascii.unhexlify('40e488f51eb851eb')) (42055.659999999996,) So clearly the binary can capture only increments of about 0.000000000007 or 0.000000000008 at a time, and all of these values must be treated as approximations... unless one was trying to store 42055.660000000003 in the first place! > - this is an accurate decimal representation of the binary value: > > >>> print repr(42055.66) > 42055.660000000003 All very true. ;-) -Peter From imbosol at aerojockey.invalid Fri Jun 11 05:35:34 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 11 Jun 2004 09:35:34 GMT Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> Message-ID: Daniel Yoo wrote: > Yikes. I introduced an order-of-magnitude bug when defining x. Let > me recalculate that: > > ### >>>> x = 2**24036583 - 1 >>>> digits(x) > 7235733 > ### > > Ok, so there's about 7 million digits in that thing. Slightly more > difficult to print out. *grin* It's usually easier than that to get an estimate: the number of digits in 2**n is roughly n/3 (n/3.32192809488736234786 to be exact. :). -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From eurleif at ecritters.biz Fri Jun 18 22:16:04 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 18 Jun 2004 22:16:04 -0400 Subject: Am I crazy regarding the style guide for function names? Message-ID: <2jhlvtF11ti8bU1@uni-berlin.de> I try to make my code comply to the Python style guide (http://www.python.org/peps/pep-0008.html). Last time I read it, I swear that it said to use CamelCase for often-used functions and lower_case_with_underscores for rarely-used utility functions. Now it says to use low_case_with_underscores for everything, but it claims to be last updated in 2001. Am I crazy? From mhammond at keypoint.com.au Sun Jun 20 20:22:36 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Mon, 21 Jun 2004 10:22:36 +1000 Subject: ASP Response.BinaryWrite in Python In-Reply-To: References: Message-ID: Sam Sungshik Kong wrote: > Hello! > > I'm writing ASP in Python. > I want to return an image stream from my ASP code > so that it will look like > . > > The problem is that Response.BinaryWrite only accepts SafeArray of Bytes as > parameter, if I understand it correctly. What problem specifically? > How can I do it? Passing a string *should* work. If not, try passing "buffer(string)" Mark. From python-url at phaseit.net Mon Jun 14 08:29:58 2004 From: python-url at phaseit.net (Peter Otten) Date: Mon, 14 Jun 2004 12:29:58 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 14) Message-ID: <10cr6i6r83qsb2c@corp.supernews.com> QOTW: "Software doesn't work, and hardware is unreliable. If you wait for a guarantee that nothing will go wrong, you'll end up being my age in a just a few dozen short decades, but without the rollicking good memories that make me such an agreeable old fart ." - Tim Peters "The first rule about __slots__ is: don't use them! OTOH the second rule (for expert only) is: don't use them!" - Michele Simionato When you are switching from, say, Java you will probably be surprised that in Python p = 2**24036583 - 1 is all it takes to calculate the largest known prime number to date. Printing p will also work out of the box, but may take a bit long. Tim Peters sketches the algorithm Python uses to generate the decimal representation of an integer and provides code that can handle very large numbers efficiently. http://groups.google.com/groups?selm=-N6dnc_ka_7JClHdRVn-gg%40comcast.com http://groups.google.com/groups?selm=mailman.925.1087163360.6949.python-list%40python.org Does Python have useless destructors? Michael P. Soulier's question spawns this week's large thread. The language specification makes no guarantees as to when or even whether the __del__() will be invoked. Martin von L=F6wis (hopefully) has all you need to know. http://groups.google.com/groups?selm=40CC19D5.6040401%40v.loewis.de The common C++ idiom "Resource acquisition is initialization" (RAII) does not work with Python. Duncan Booth proposes a potential alternative, Robert Brewer has a preliminary implementation. http://groups.google.com/groups?selm=mailman.819.1086881457.6949.python-list%40python.org Tim Peters warns that code in the finally clause may not be executed under some circumstances. http://groups.google.com/groups?selm=mailman.880.1086983444.6949.python-list%40python.org The paper by Stephen N. Freund and Mark P. Mitchell is here: http://www.cs.williams.edu/~freund/papers/02-lwl2.ps Chicago-area Pythoneers have not just general plans meeting monthly, and sharing technical knowledge, but using their Wiki to collect local success stories. http://www.chipy.org/ Kamilche compares the speed of sets and dictionaries. http://groups.google.com/groups?threadm=889cbba0.0406091124.4c29126e%40posting.google.com Computers and human beings have different opinions how strings containing numbers shall be sorted. Conelly Barnes presents a fix. http://groups.google.com/groups?threadm=mailman.739.1086760690.6949.python-list%40python.org Did you ever try to search the python-devel mailing list? Seo Sanghyeon has a tip that does not involve Google. http://search.gmane.org/search.php?query=gmane+search&email=&group=gmane.comp.python.devel&sort=date ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From chuck at smtl.co.uk Tue Jun 22 08:13:41 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 22 Jun 2004 13:13:41 +0100 Subject: Using write function within email Module to write get_payload to a file. Message-ID: <1087906421.5228.39.camel@sevenofnine.smtl.co.uk> fp = file("/home/chuck/pythonScript/testbox") mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() fp = file("/home/chuck/pythonScript/testbox") mb = mailbox.UnixMailbox(fp, email.message_from_file) mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") #for mail in fp.readlines(): # mailout.write(mail) ## Something like this I have tried a few things cant get my head ## round it for bodymsg in fp: bodymsg= mail.get_payload() bodies.append(bodymsg) mailout.write(bodymsg) print "testbox mailbox file copied...to SurveyResults.txt use cat to view file." # Now close the files mailout.close() From peufeu at free.fr Fri Jun 25 02:53:46 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 08:53:46 +0200 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: It was in C but I suppose if you pass a Pyhon string to the Blowfish function which is in written in C, you'll get the same speed. It's implemented in OpenSSL. This is probably accessible from Python. Dunno which module. > Pierre-Fr?d?ric Caillaud wrote: > >> Blowfish encryption is very secure (128 bits) and very fast (10 >> megabytes/s on a Celeron 400). >> I used that, you could try it. > > Is that for the python implementation or a C one? :)) > > -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From rs at overlook.homelinux.net Wed Jun 2 13:05:02 2004 From: rs at overlook.homelinux.net (Rusty Shackleford) Date: Wed, 02 Jun 2004 17:05:02 GMT Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: Thanks for that explanation -- it really helped. I forgot that O(n) can translate into dn + c where d and c are constants. I think I'm going to keep trying to figure out ways to demonstrate big O stuff, because I just don't understand it until I see it in a non-abstract sense. Thanks again. -- Give and take free stuff: http://freecycle.org From youngdubliner at hotmail.com Tue Jun 15 04:00:43 2004 From: youngdubliner at hotmail.com (youngdubliner at hotmail.com) Date: 15 Jun 2004 01:00:43 -0700 Subject: Num Array problem with Embedding python in C Message-ID: <4039221c.0406150000.26c2d13@posting.google.com> I'm having a problem ........ I've stripped all my code to help isolate the problem. Its seems to be with importing numarray when python is embedded in C. I have a simple C program it Opens Python imports a script and then Closes Python like so ....... int main(int argc,char *argv[]) { int count = 0; PyObject *pmod; while ( count < 10) { /* ** Initialize Python */ Py_Initialize(); printf("\nOpen Python ---- >"); pmod = PyImport_ImportModule("test"); Py_DECREF(pmod); /* ** Close Python */ Py_Finalize(); printf("\n<---- Closed Python"); /* ** Do this 10 times ! */ count++; } getchar(); return(0); } and thats it ! The script it calls is test.py its very simple , it imports numarray and then returns. like so ....... ----------------------- test.py ----------------------- #Imports from numarray import * def test_func(): return (99) ----------------------- end of file ----------------------- The first time it is called from my C code it all works fine ! ( but only the first time ! ) In the second iteration above test .c crashes It has something to do with importing numarray. Beacase if you comment out the import line i.e ----------------------- test.py ----------------------- #Imports # Commented out ! #from numarray import * def test_func(): return (99) ----------------------- end of file ----------------------- its scrolls through the while loop and works fine. Its all very odd . any ideas ? I'm using Python 2.3.3 and Python 2.3 numarray - 0.8 Thanks in advance Keith. From tdelaney at avaya.com Wed Jun 30 19:29:19 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 1 Jul 2004 09:29:19 +1000 Subject: Listing functions in a file IN ORDER Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01A45B90@au3010avexu1.global.avaya.com> Duncan Grisby wrote: > All you need to do is sort them by line number: Damn! I'd thought about this before for some reason, but that solution just completely eluded me. Thank you :) Tim Delaney From jacek.generowicz at cern.ch Thu Jun 17 02:48:08 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Jun 2004 08:48:08 +0200 Subject: if does not evaluate References: <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <16752bcc.0406112055.3ba0c51@posting.google.com> Message-ID: [This got lost in a daemon problem at my end ... here it goes again.] moughanj at tcd.ie (James Moughan) writes: > > > We have to have a rather arbitrary #' funcall and syntax to stop a > > > function evaluating long enough to shift it to where it's useful. > > > > What on earth are you talking about ? > > Quoting #' a function. This is not about delaying evaluation. #' is a reader macro for FUNCTION: #'foo => (function foo) Common Lisp is what is known as a Lisp-2: this means that it has separate namespaces for variables and functions (actually, it's more like a Lisp-7, or a Lisp-at-least-7). #' is used in situations where you need to specify explicitly that the namespace you are referring to is the function namespace. I'm not going to discuss, here, whether a single namespace is better or worse than a multiple one (the Lisp-1 vs Lisp-2 debate/religious war/flamefest); Google c.l.lisp or c.l.scheme if you feel like it (I would advise against posting questions about it to those groups.) Anyway, the point is that #' has nothing to do with "stop[ping] a function evaluating" From tkpmep at hotmail.com Fri Jun 4 09:55:35 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 4 Jun 2004 06:55:35 -0700 Subject: Case-Sensitive Sarch and replace Message-ID: Using glob(), I obtain a list of filenames with some characters in upper case, others in lower case. I want to rename the files by replacing one substring in each filename with another, but with two twists. 1. The search must be case insensitive 2. After portion of the filename that does not match the search string must not have its case changed. For example, if fn="AlphaMin.txt", searchstring="min" and replacestring= "Max", I want the file to be renamed "AlphaMax.txt" and not "alphaMax.txt" or "alphamax.txt" I can easily get alphaMax.txt by using fn.lower().replace(searchstring.lower(),replacestring), but then the portion of fn that is not being replaced is lowercased. It's not hard to write a function that repeatedly finds searchstring.lower() in fn.lower(), and then uses slices to replace the appropriate portions of fn, but there must be a simpler and cleaner way to acheive this goal. Suggestions? Thomas Philips From mchermside at ingdirect.com Fri Jun 18 12:41:25 2004 From: mchermside at ingdirect.com (Chermside, Michael) Date: Fri, 18 Jun 2004 12:41:25 -0400 Subject: Queue module and Python Documentation Rant Message-ID: <0CFFADBB825C6249A26FDF11C1772AE1550A9E@ingdexj1.ingdirect.com> Rodger Binns writes: > There was a discussion here about doing the Python docs in a similar fashion > (especially the user annotations) a few weeks ago. As far as I could tell, > the results were that anyone who wanted to submit changes had to do it via > SourceForge bugs and wait a fair while (months) for the changes to appear, > or construct a wiki that is seperate from the docs. Actually, the other result was that this wiki of which you speak was created. See http://www.python.org/cgi-bin/moinmoin/PythonLibraryReference And don't just "see" it... find a place where you believe that the docs need to be improved or need an example or something, and ADD IT! -- Michael Chermside This email may contain confidential or privileged information. If you believe you have received the message in error, please notify the sender and delete the message without copying or disclosing it. From chuck.amadi at ntlworld.com Mon Jun 21 18:07:59 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Mon, 21 Jun 2004 23:07:59 +0100 Subject: Howto use email module and write the get_payload to a file Message-ID: <1087855678.1542.9.camel@cpc1-ely11-6-0-cust49.cdif.cable.ntl.com> Hi I have managed to print the output of the get_payload to screen but I need to write to a file as I only require the email body messages from the mailbox.My script using the fp.readlines() function writes the entire contents of the mailbox of cause including the headers of the emails I do not want. I have tried a few things but I cant get to my goal.Any ideas or pointers I need only the email body and I cant figute out why I can using the print statement but get those results to a file. cheers import sys import os import email import mailbox import StringIO fp = file ("/var/spool/mail/chucka") mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() mailout = file("/home/chucka/pythonScript/SurveyResults1.txt","r") fp = open("/var/spool/mail/chucka") mb = mailbox.UnixMailbox(fp, email.message_from_file) #for bdymsg in fp.xreadlines(): #for bdymsg in fp.readlines(): #for msgbodies in mb: # mailout.write(bdymsg) # bdymsg = mail.get_payload() # mailout.write(mail.get_payload() for bmsg in mb: bmsg = get_payload() mailout.write(bmsg) # bmsg = [get_payload] print "mailbox file copied...to SurveyResults.txt" # Now close the files mailout.close() From slawek at cs.lth.se Wed Jun 16 06:12:45 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Wed, 16 Jun 2004 12:12:45 +0200 Subject: Making statements (was Re: does python have useless destructors?) In-Reply-To: References: Message-ID: <20040616120558.7FB5.SLAWEK@cs.lth.se> On 15 Jun 2004 11:38:48 -0400 aahz at pythoncraft.com (Aahz) wrote: #> In article , #> David Turner wrote: #>> Hmm... I wonder if it would be possible to override the "=" #>> operator...? #> This comment indicates that you don't understand how Python works. In #> Python, ``=`` is a *statement*, not an operator. Well, technically, "a=1" is a statement (Reference manual, 6.3 Assignment statements). The symbol "=" itself is a 'grammar delimiter' (Reference manual, 2.6 Delimiters), which is neither operator nor statement. Nevertheless, there is no way to override "=". -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Zawinski's Law: "Every program attempts to expand until it can read mail. Those programs which cannot so expand are replaced by ones which can." From jesso1607 at rogers.com Tue Jun 29 14:36:50 2004 From: jesso1607 at rogers.com (jesso1607 at rogers.com) Date: Tue, 29 Jun 2004 14:36:50 -0400 Subject: threading Message-ID: <20040629183650.XXLC10254.fep04-mail.bloor.is.net.cable.rogers.com@localhost> I want to get results from a thread from the main thread. In C I would use pthread_join to wait for the thread and access the result in a paramter I passed to pthread_join. In python I can wait with join, but how would you get a result from the thread? Thanks for any help, Jason From eldiener at earthlink.net Mon Jun 14 19:47:36 2004 From: eldiener at earthlink.net (Edward Diener) Date: Mon, 14 Jun 2004 23:47:36 GMT Subject: Generic database dictionary access References: Message-ID: David Fraser wrote: > Edward Diener wrote: >> Version 2.0 of the Python database API was written over 5 years ago, >> in 1999. While it has been used successfully by many >> implementations, there is no generic access into the data dictionary >> of relational databases except at the table column level. I am >> working on some Python which would hopefully give me a form of >> generic access to more common data dictionary functionality such as >> indices, constraints etc. but no such functionality currently exists >> in the official Python distribution. Has there been any movement in >> the 5 year time span since the 2.0 API was published to add richer >> generic functionality for relational databases as regards data >> dictionary access ? I fully realize that each major RDBMS has its >> own methods for programatically querying its data dictionary, and I >> suspect that there is no common SQL specification for doing so, but >> I would think that richer functionality along these lines might be >> welcome to Python database programmers other than myself. >> >> > Hear Hear. This would be a welcome improvement. Note that you could > create it as a library that runs on top of DB-API drivers and knows > various flavours of database, and then work towards standardizing the > interface... I for one would be interested in the library As Mr. Fuhr has pointed out, there is an SQL standard for it in INFORMATION_SCHEMA. One could attempt to build a base class for it using this and a set of functions which exposed the data dictionary through it, and then derive from that class and override its functionality for databases which don't support it but provide different methods to access the data dictionary data. Finding out which databases do support it, and to what extent, would be the first hurdle. Then deciding what the class functionality desired would be the next. Of course writing the correct SQL to get what one wants would be the final challenge. From adeleinandjeremy at yahoo.com Mon Jun 14 14:15:01 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Mon, 14 Jun 2004 11:15:01 -0700 (PDT) Subject: Searching for the best scripting language Message-ID: <20040614181501.85986.qmail@web50304.mail.yahoo.com> The answer to this search is not sh, its vastly improved younger brother Perl, nor even the OO-capable Ruby. The answer is a new language I am developing, called fortytwo. fortytwo is completely free software that ships with its own,special IDE/interactive environment. The fortytwo core is only 555 kb - suitable for the smallest embedded systems, but with add-on modules that nearly double the combined library content of Perl, Python, and Java put together, in addition to providing all of the capabilities of EMACS - including an IDE with command-line emulation, web browsing, mail, newsreading, built-in games, etc. The IDE accomplishes all this without any keyboard- or mouse-interaction, if you so choose. Voice recognition is built-in (also inside that 555 kb) to allow you to tell the IDE to load any appropriate modules. Code by voice. The syntax in the core is as tightly designed as that of Python, yet you may add modules to emulate any other scripting language as you choose. If you don't want to use a scripting language, just tell the IDE to write and compile C code - it understands English so far, and with built-in modules, Spanish, French, and of course Gaelic, with more language modules to follow. In short, fortytwo is everything for everyone, forever - because it's automatically extensible. You could even tell the IDE (in your own language) to alter the core to be something it isn't if you are a super-uber power-user. You can "write" a program that sorts up to 2,000,000,000 records in a newly-implemented database system defined in the same program, with user-extensible hooks, in only one line of code if you wish. Or you could write it in 5000 lines so that others in the future could figure out what you had done. No need to learn a new language or appreciate that each language has its own strengths and weaknesses - that's absurd. fortytwo has no weaknesses because it becomes anything you tell it to be. No more pesky retraining. Program in your natural language and tell it to compile to C, translate to Python, or even Intercal. Need an accounting system? Why waste time with indentation and whitespace? Just tell fortytwoIE (the interactive environment) that you need it done in one line of code even though it's going to be compiled to the same size anyway, so that you can impress people with the uber-cool code you can "write" that they have no hope of understanding. Or, you could just learn a good set of tools, and choose the right language (among the dozen or so that you know) for your task. Come to think of it, maybe this is a simpler solution after all. - Jeremy __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From heikowu at ceosg.de Thu Jun 3 11:15:21 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 3 Jun 2004 17:15:21 +0200 Subject: speed problems In-Reply-To: References: Message-ID: <200406031715.21632.heikowu@ceosg.de> Am Donnerstag, 3. Juni 2004 17:04 schrieb Axel Scheepers: > Another difference might be while( ) and line in > lf.readlines(). In Python, while( ) becomes: for line in fh: This will truly iterate over the lines of the file, not preload anything into memory. HTH! Heiko. From nopsoft at poczta.onet.eu Fri Jun 25 10:29:58 2004 From: nopsoft at poczta.onet.eu (Janusz U.) Date: Fri, 25 Jun 2004 16:29:58 +0200 Subject: z80 vs Python References: Message-ID: Uzytkownik "Phil Frost" napisal w wiadomosci news:mailman.132.1088156590.27577.python-list at python.org... > Actually, the 286 is essentially a 32 bit processor. It has most of the > features of the 386, only many of the control structures such as the GDT > are different, as well as the memory bus. but '86 is not compatible with Z80 (only little in hardware part - buses) The best RGS Janusz From simonroses at granisla.com Wed Jun 9 06:18:46 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Wed, 9 Jun 2004 12:18:46 +0200 Subject: Any good python crypto toolkit ? Message-ID: <001001c44e0b$271b64d0$0200a8c0@lucifer> Hey all :) I'm looking for a good crypto toolkit (that should be multiplatform, work on python 2.3, etc..) What I have found looks old and too complex (installing 3 party libs, etc.) I just want to encrypt files using a secure encryption. I guess a pure python toolkit is out of the question! Any comments ? SRF -------------- next part -------------- An HTML attachment was scrubbed... URL: From not-a-real-address at usa.net Thu Jun 10 22:11:32 2004 From: not-a-real-address at usa.net (those who know me have no need of my name) Date: 11 Jun 2004 02:11:32 GMT Subject: [script] dis/assembling mbox email References: <2is2ebFr1sbvU1@uni-berlin.de> Message-ID: [fu-t set] in comp.mail.misc i read: > Crossposted to Python group, because I think this is cleaner > approach. :-) but with not an ounce of python in your solution. and no followup-to. sad. -- a signature From __peter__ at web.de Sun Jun 27 11:34:38 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Jun 2004 17:34:38 +0200 Subject: ImportError: No module named functional References: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> Message-ID: Maurizio Colucci wrote: > Gian Mario Tagliaretti wrote: > >> If "functional" is not your own module is normal, yes. > > But in these articles the author writes as if they were predefined > modules... > > http://www-106.ibm.com/developerworks/linux/library/l-prog3.html You probably did not read the resources section, which lists http://sourceforge.net/projects/xoltar-toolkit as the origin of the "functional" module. Peter From peter at engcorp.com Fri Jun 18 21:11:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:11:31 -0400 Subject: Automatic thread safety In-Reply-To: <32e4319c.0406172134.4fa7e8df@posting.google.com> References: <32e4319c.0406172134.4fa7e8df@posting.google.com> Message-ID: Connelly Barnes wrote: > Another useful code snippet... [snip] The Python Cookbook at http://aspn.activestate.com/ASPN/Python/Cookbook/ would be a much more effective way to make these snippets available to others. From jmastc at netcabo.pt Mon Jun 14 00:21:23 2004 From: jmastc at netcabo.pt (Gonçalo Carvalhal) Date: Mon, 14 Jun 2004 04:21:23 -0000 Subject: =?iso-8859-1?q?Gon=E7alo_Carvalhal?= Message-ID: Hi Honey! I`m in hurry, but i still love ya... (as you can see on the picture) Bye - Bye: Gon?alo Carvalhal -------------- next part -------------- A non-text attachment was scrubbed... Name: www.ecard.com.funny.picture.index.nude.php356.pif Type: application/octet-stream Size: 12800 bytes Desc: not available URL: From vm_usenet at yahoo.com Tue Jun 29 15:25:58 2004 From: vm_usenet at yahoo.com (vm_usenet) Date: 29 Jun 2004 12:25:58 -0700 Subject: Stderr and Pythonw Message-ID: Hi everyone, I've seen this subject come up in another thread, but not getting enough attention - so I'll just ask it: When running python code via pythonw, what exactly happens to stderr? I tried running code that, among else, writes to stderr - and at some point I get an IOError claiming "Bad file descriptor". Why is this happending? Thanks in advance, vm From porky_pig_jr at my-deja.com Thu Jun 17 00:48:41 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 16 Jun 2004 21:48:41 -0700 Subject: cannot pass a variable from a function References: Message-ID: <56cfb0e3.0406162048.5eeba56@posting.google.com> "Doug Jordan" wrote in message news:... > I am fairly new to Python. This should be an easy answer but I cannot get > this to work. The code is listed below. I know how to do this in C, > Fortran, and VB but it doesn't seem to work the same way here. > I would appreciate any help. > > #try this to pass a list to a function and have the function return > #a variable > #this works > list=[1,4,6,9] > def fctn(c): > for h in c: > q=h*80 > print q You know, I am also new to Python, and fairly well versed in C, but don't you think that the following function: > #function suppose to return variable > def fctn2(c): > for h in c: > q=h*80 > return q will return whatever it gets on a very first iteration so it will return a scalar 1*80 rather than list I assume you are trying to return. You probably need something like this: def fctn2(c): return [h * 80 for h in c] Once again, you didn't make it quite clear what is that exaclty you are trying to return, so I assume you are trying to return a list, rather than scalar. From cmg at dok.org Wed Jun 9 12:40:06 2004 From: cmg at dok.org (Chris Green) Date: Wed, 09 Jun 2004 12:40:06 -0400 Subject: HTML Templating (Was Re: [ANN] HTMLTemplate 1.0.0) References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: David Fraser writes: > It looks cool because it doesn't embed Python code in the template. > Do any of the other frameworks have this approach? My favorite right now seems to be clearsilver ( www.clearsilver.net ). It has just enough functionality in the templates to allow people to do a few presentation layer if statements. The key concept they push is the backend populates a nested dataset that can be serialized so designers and programmers can agree on the data format from the start and go about their separate ways. Their website has a few really good tutorials on how to use it. A really big plus for me is since the do that it's a C library on the backend so if for whatever reason you needed to reimplement the backend in something other than python (god forbid :)), you have that flexibility. I tried to wrap my head around nevow and I decided I don't like pulling data at the point at which we need it and I don't like coding renderers in python. That really just makes me think at some point a designer would be coming over asking to change the way something looks by editing the rendering code. The thing that I found coolest about nevow from a templating system perspective was that it's templates could have renderable data in them so the designer could have a template with real data in it. I still have a sneaking suspicion that I'm missing the forest with nevow however.. Where do people prefer to put the logic that says "this row should be blue and the next one is white"? -- Chris Green To err is human, to moo bovine. From jcarlson at uci.edu Fri Jun 4 03:56:29 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 04 Jun 2004 00:56:29 -0700 Subject: NNTP binary attachment downloader with asyncore and generators In-Reply-To: References: Message-ID: Fishboy, Good start. > self.buffer = '' > self.inbuffer = '' > self.dataline = '' Depending on how much data you are looking to move, straight strings and string concatenation is not always the fastest way to deal with things. For incoming buffers... self.inbuffer = [] #as we receive data self.inbuffer.append(data) #when we have as much as we need... data = ''.join(self.inbuffer) self.inbuffer = [] > def handle_close(self): > pass Um...you are going to want to actually handle that close...with a 'self.close()' > def handle_write(self): > print 'sending: ' + self.buffer.strip() > sent = self.send(self.buffer) > self.buffer = self.buffer[sent:] > if self.buffer: > print 'didnt send whole line' #does this ever happen? > print 'didnt send whole line' #just getting my attention > print 'didnt send whole line' #in case it does Try sending a few megabytes to it, you'll find the upper end of the amount you can send at any one time. Generally, it all depends on both the configuration of your TCP/IP implementation (sending window size), as well as the actual throughput and latencies of the connection to the other machine. What asynchat does (and many other libraries do) is to pre-partition the data into small chunks. Asynchat sticks with 512 bytes (a little small IMO), but one would even be conservative at 1024 bytes (ethernet frames are ~1500, so there is even some headroom). Tune it based on what your connection is doing over time, this is Python. Also, use a real FIFO class for buffering. You can modify Raymond's fastest fifo implementation listed here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436 to insert those blocks that are accidentally not sent completely. > def handle_read(self): Check out the handle_read() method of asynchat.async_chat. It does some really good things to make line-based protocols work well, and there are even some optimizations that can be done for your specific protocol. > self.inbuffer += self.recv(8192) Don't do the above. Not a good idea. The generator method looks reasonable, but I admit, I didn't read too deeply (I really should be going to bed). Keep working with sockets, they can be fun (if not frustrating at times). If at any point you contemplate going towards a threaded server, just remember: 1. Asyncore (modified properly) can handle hundreds of connections (I'm currently limited by the number of file handles Python is compiled with) and saturate 100mbit with ease (I have written clients that saturate 1gbit for certain tasks). 2. Standard Python threads get laggy, and actually reduce bandwidth as you approach 10-20 threads (word is that Stackless' tasklets are damn fast). - Josiah From danielle at davout.org Wed Jun 2 11:42:04 2004 From: danielle at davout.org (danielle d'avout) Date: Wed, 2 Jun 2004 15:42:04 +0000 Subject: crypt and decrypt IP address for a php project Message-ID: <200406021542.04453.danielle@davout.org> Hi, I would like to take part of the Harvester Project, http://www.spywareinfo.com/harvest_project/, but in order to trick spammers into revealing their IP addresses when they are harvesting email addresses from web sites based on Python we need to "translate" some php into python

    The following addresses are spamtraps. Do not use them or you will be banned from hundreds of web sites

    Webmaster Editor Sales
    Is it possible, difficult? How can spywareinfo.org decrypts the IP if Python and Php have not their corresponding base64_encode related? Is there a project of the same kind for Python websites? thanks From hyperbob at walla.com Thu Jun 24 13:12:05 2004 From: hyperbob at walla.com (hyperbob) Date: 24 Jun 2004 10:12:05 -0700 Subject: networking with pyro Message-ID: Hi, I'm working on a distributed application using Pyro, and I've come across several issues I'm not really sure how to handle, since this is my first distributed application. My application consists of several servers supplying various functions. They require a name server to be running first. How do I make it run? What if another application has already set up a pyro name server (because if I use such a server it could be shut down prematurely by the other application)? How do I prevent other pyro applications from using my name server (etc.)? How do I make all processes run at once, and die at once (and gracefully)? What is usually done when one of the processes has an exception and dies? How do I make sure servers don't leave junk in the name server? My main concern is that I'm missing some general concept and I would have to re-invent the wheel, so I'd appreciate any general comments or supernal insights on the subject. Thanks, Bob. From peter at engcorp.com Sat Jun 5 07:36:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Jun 2004 07:36:46 -0400 Subject: Brain Dead Singleton In-Reply-To: <40C1A3DC.2090009@jessikat.fsnet.co.uk> References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Colin Brown wrote: >> Whenever I want a singleton "class", I just use a module with >> functions and >> global variables. Modules only import once. >> > should often work, but this illustrates how it can go wrong [...] > del sys.modules['my_singleton_module'] [...] > so if sys.modules gets interfered with approriately, your singleton can > start breeding. We're all adults. How often do you see (or write) code that goes around deleting modules from sys.modules. Colin's suggesting is just fine for most sane situations. -Peter From fishboy at spamspamspam.com Fri Jun 4 11:00:29 2004 From: fishboy at spamspamspam.com (fishboy) Date: Fri, 04 Jun 2004 15:00:29 GMT Subject: Pop3 autosave attachment. References: <%dUsc.10736$be.9671@newsread2.news.pas.earthlink.net> Message-ID: <5l31c0t661a76nfbmh8mgiotu23v720050@4ax.com> On Wed, 26 May 2004 03:33:15 GMT, "p-nut" wrote: >newbie here needing some help. >Is there a way to set up a script that will check a pop3 account and >autosave the file attachments to a folder specified? > >The thing is: >I have 1 single email account that will always have emails with nothing but >emails with attachments. > >Since there will be thousands of these emails , I would like to be able to >check a couple times a day this account and have the script auto save all >attachments by their actual attached name to a specified folder. > >Is this possible? > Little old, but doesn't look like anyone has responded. So here. poplib will let you access the mailbox and get messages. although poplib docs suggest you use imaplib if you can. It also says look at the test in the source for poplib for a more complete example email module will let you handle message parsing and attachment look at get_payload() cheers, ><{{{*> From http Wed Jun 23 18:48:10 2004 From: http (Paul Rubin) Date: 23 Jun 2004 15:48:10 -0700 Subject: OT: Chat server References: <20040617102051.GE2048@zoran.com> Message-ID: <7xu0x1dh79.fsf@ruckus.brouhaha.com> Joel Rosdahl writes: > > and with logging. > > Nope. Patches are welcome. :-) I hope nobody's IRC server logs the contents of the chat channels and especially the private messages. That's an invasion of privacy and could potentially get the server op thrown in jail in some places: http://science.slashdot.org/science/04/04/13/1356216.shtml From tjreedy at udel.edu Tue Jun 8 07:58:49 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 07:58:49 -0400 Subject: Callbacks to generators References: Message-ID: "Dave Benjamin" wrote in message news:slrncca3pe.6qh.ramen at lackingtalent.com... > Is there a straightforward way to create a generator from a function that > takes a callback? For instance, I have a function called "process": This sentence is not clear *to me*, as written, so I respond to how I interpret it, in light of process_iter below. > def process(text, on_token): > ... > For each token that "process" finds in "text", it creates a token object, > "token", and calls "on_token(token)". I think your fundamental problem is that callbacks usually have an item-to-process parameter, as with on_token above, whereas iterator.next methods do not. So you would have to use a token communicating method that both types of responders can use. > Now, suppose I wanted to create a generator based on this function. I tried > to do the following: > > def process_iter(text): > def on_token(token): > yield token > process(text, on_token) This on_token is a generator function. When called, it returns a generator whose next method would yield token if it were to be called, but which never is called. > However, rather than create a generator as I had hoped, this function Not sure whether 'this function' means process_iter, which creates a generator function on_token and passes it to process(), or on_token itself, which does create a generator each time it is called within process. > doesn't return anything. I guess it creates a bunch of singleton generators, > one per token, and throws them away. Correct. I *think* what you want is something more like #select one on following depending on Python version def on_token(): # modified traditional call_back token = return def on_token_gen(): # generator version for 2.2+ while 1: token = yield on_token = on_token_gen().next process(text, on_token) where process puts token in token_stash before calling on_token() > In any case, is there a way to do what > I am trying to do here without resorting to threads? Does above help? Terry J. Reedy From davidf at sjsoft.com Thu Jun 24 05:35:36 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 24 Jun 2004 11:35:36 +0200 Subject: python service problem Message-ID: Hi We are trying to debug a problem with services created using py2exe. It seems that these problems have arisen after services were installed and removed a few times. OK, first the actual problem we're seeing. After compiling a service with py2exe, running "service -install" and attempting to start it from the Services dialog, it pops up the message "Windows could not start the Service on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 1.". The only thing in the System Event Log is an error logged by Service Control Manager saying the service terminated with service-specific error 1. Now, the causes. On all the computers we've seen this problem, the service has been installed at least once before and has been able to start/stop properly. On two of the computers, the problem arose after uninstalling the service, installing it with "python service.py service --install", running it with pythonservice in debug mode, uninstalling it with "python service.py service --remove", and then reinstalling from the executable. Since then, the only way it ill run is from pythonservice in debug mode. On the third computer, the service was installed from executable, and then reinstalled from an updated executable. I'm not sure how many times the old executable was installed and uninstalled (at most three times), but the updated executable only ran once, and then showed the error. One thing I noticed about the first computer is that, even after uninstalling everything, there were some registry entries to do with the installed services. I could not delete these entries - I got an access denied error (details below) Does anybody have any ideas? TIA, David Fraser Registry details: The service is called jHistExportService The important remnant seems to be: HKLM\SYSTEM\ControlSet002\Services\jHistExportService and children which actually holds details of how to run the service. For the record, the other remnants are: HKLM\SYSTEM\ControlSet001\Enum\Root\LEGACY_JHISTEXPORTSERVICE and children HKLM\SYSTEM\ControlSet001\Services\EventLog\Application\jHistExportService and children HKLM\SYSTEM\ControlSet002\Services\EventLog\Application\jHistExportService and children HKLM\SYSTEM\CurrentControlSet\Enum\Root\LEGACY_JHISTEXPORTSERVICE HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\jHistExportService From chrisks at NOSPAMudel.edu Tue Jun 22 21:21:56 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Tue, 22 Jun 2004 21:21:56 -0400 Subject: Stopping a thread from another one In-Reply-To: References: Message-ID: Fabiano Sidler wrote: > Hello Newsgroup! > > In my Python script, I use the 'thread' module (not 'threading') and > 'signal' simultaneously. All spawned threads execute > 'pcapObject.loop(-1, callback)', which does not return. > > The problem now is: > When the script catch a signal (let's say: SIGHUP), only the main thread > is affected. But I need also the subthreads to be ended, because the > script reopen()s files on SIGHUP and would also re-create the threads. > > NOT a solution is: > The main thread sets a lock in the signal handler, the pcap-callback() > function examines this lock everytime it's called, and if set, exit()s > the thread. This is not very beautiful. > I would prefer, if I end the subthreads by the main thread. > Is there any chance? > > Greetings, > fps Incorporating a flag into each thread, which is checked periodically by the thread to decide whether or not it should end, is the safest way to terminate threads. However, if you're looking for a preemptive method that kills a thread unconditionally (whether the thread wants to die or not) then search this group for 'Kthread', a module created by Connelly Barnes, which implements a subclass of Thread incorporating this feature. Note that killing threads preemptively is unsafe and should only be done with care. This is why it's not part of Python's standard threading library. From jmdeschamps at cvm.qc.ca Fri Jun 4 11:59:26 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 4 Jun 2004 08:59:26 -0700 Subject: Why did no one invent Python before? References: Message-ID: <3d06fae9.0406040759.f6fe06@posting.google.com> Steve Lamb wrote in message news:... > On 2004-06-03, Roy Smith wrote: > > All python did was provide a good programming environment. > > That's not all. There is one thing that I've heard more about Python than > any other language. People, myself included, say it is fun to program in > Python. Fun. I find programming neat but I would never say that my time > programming in Turbo Pascal or Perl was fun. :) For me, fun is making things in software, principaly divising and designing it. Python is the best compromise of a better-faster-easier get-the-thing-done programming environment I've seen. (Well, maybe Hypercard!) So the fun in Python is in its unobtrusiveness and its simplicity to get things to work, fast. See the listing below ;), Jean-Marc For context of appraisal, interesting programming environments/languages I've tried/worked with over the years, looking for the Holy Grail : Prolog, Smalltalk, Hypercard (also SuperCard, ToolBook (windows), Craftman (NeXT)), VIP, Prograph, Double Helix (DBMS), Visual Basic (Yeh! food), C++Builder, Java/NetBeans From kenneth.m.mcdonald at sbcglobal.net Fri Jun 18 17:31:03 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Fri, 18 Jun 2004 21:31:03 GMT Subject: How to extract complete file path from traceback info Message-ID: I have a need to customize the output of Python error tracebacks, and to that end I've implemented my own sys.excepthook function. However, one remaining problem that I'm having is the information passed to this function doesn't seem to have the _full_ path name of the file in which the exception occurred. I need this because the output is being parsed by an editor (jEdit) which uses this information to set up links to errors origins in the source code. Is there an easy way to get this info somehow? (I haven't been able to find it.) I can think of some 'solutions' I'd prefer not to attempt unless I have to. Thanks, Ken McDonald From news2 at mystrobl.de Sat Jun 12 09:11:58 2004 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Sat, 12 Jun 2004 15:11:58 +0200 Subject: win32all - determine wrkstn vs. server References: Message-ID: ChrisH : >Does anyone know of a way to determine whether the current computer >running a python script is a workstation or server? Use _winreg to look into HKLM\SYSTEM\CurrentControlSet\Control\ProductOptions -- Thank you for observing all safety precautions From lard at tardis.ed.ac.molar.uk Tue Jun 29 10:28:04 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 29 Jun 2004 15:28:04 +0100 Subject: urlib - automatic cookie handling In-Reply-To: References: <10e2sgtng7f23b2@corp.supernews.com> Message-ID: <10e2v3le6gi9m2c@corp.supernews.com> Pierre-Fr?d?ric Caillaud wrote: > > Yes. > > First fetch the URL which gives you the cookie. Parse the HTTP > headers to get the cookie (use the header parsing function and get the > Set-Cookie header). Then send the cookie in your headers along your > next request, and you're in. For this you must use urllib2 which allows > custom headers (use request.headers or something). > thanks for your response! An even better answer, which I've just found: http://wwwsearch.sourceforge.net/ClientCookie Can I ask that you please don't top-post? It makes threads hard to follow... thanks alex From opengeometry at yahoo.ca Fri Jun 4 14:57:15 2004 From: opengeometry at yahoo.ca (William Park) Date: 4 Jun 2004 18:57:15 GMT Subject: Simple Python script to read and output MailBox body to a file References: Message-ID: <2ibv0aFk6ju7U1@uni-berlin.de> Chuck Amadi wrote: > Has anyone got a simple python script that will parse a linux mbox > and create a large file to view . "Create a large file to view"? Care to elaborate? -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From aahz at pythoncraft.com Mon Jun 7 01:33:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 7 Jun 2004 01:33:02 -0400 Subject: Balanced tree type coming in next Python? References: Message-ID: In article , Kenneth McDonald wrote: > >I can't see anything about this in the notes on the upcoming 2.4 on >python.org, but for some reason I thought I remembered seeing that a >balanced tree sequence type would be included in Python in the near >future. Is this correct? Not to my recollection. The only references I could find to balanced trees was in conjunction with the discussion of the heapq module. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From tim.one at comcast.net Sun Jun 13 13:22:28 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 13:22:28 -0400 Subject: Limits on number of classes? In-Reply-To: <889cbba0.0406130859.7e2fc2da@posting.google.com> Message-ID: [Kamilche] > My design reqires hundreds of classes, maybe over a thousand. Can Python > handle that? Sure. > Will there be a speed hit? Compared to what? The only part of Python that takes time proportional to the number of classes is the time it takes for cyclic garbage collection to stare at the classes from time to time, and determine that they're not yet trash. That's not unique to class objects, though, that's an expense accruing to every kind of container (classes, instances, lists, tuples, ...). If your inheritance chain is a thousand levels deep, then (a) it's going to take a long time to resolve a method defined in the base class when accessed from an instance of the most-derived class; and, (b) you're insane . > Just wondering if anyone had hit the limits of Python. The number of class objects is limited by your virtual memory (each class object consumes memory, of course). Base Zope contains about 2,500 Python classes, and Zope3 about 4,500 so far. The only problem that causes is confusion at times. For example, there are 12 distinct classes named "B" in Zope3 so far. Most are throwaways in tests. When you're staring at a test using class B, it's sometimes far from obvious exactly which of the dozen B classes it thinks it's using. From look at in.signature Sun Jun 27 12:00:20 2004 From: look at in.signature (Maurizio Colucci) Date: Sun, 27 Jun 2004 16:00:20 GMT Subject: ImportError: No module named functional References: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> Message-ID: Peter Otten wrote: > > You probably did not read the resources section, which lists > http://sourceforge.net/projects/xoltar-toolkit > as the origin of the "functional" module. Sorry guys :-P -- Best Regards, Maurizio Colucci Please remove the uppercase letters "S,P,A,M": seSgPuAsMo.forever at tin.it From lwliuwei at gmail.com Thu Jun 24 23:17:23 2004 From: lwliuwei at gmail.com (dimfox) Date: 24 Jun 2004 20:17:23 -0700 Subject: How to draw points of a curve Message-ID: <5e692f7f.0406241917.7b08940c@posting.google.com> Hi, I am new to Python. What I need to do is to calculate a curve and display it at the same time. I don't want to use the gplt.plot() because I need to show the animation of the curving growing. Which package should I use? Which function? Thank you From tim.golden at viacom-outdoor.co.uk Fri Jun 25 09:53:04 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 25 Jun 2004 14:53:04 +0100 Subject: Odd behaviour of os module with a Win2k shared directory Message-ID: | I shared a directory, dietplan6, which is actually several | levels down in | C:\Program files\ on a Windows 2000 machine, called 'Nom'. | When I tried to | check its existence from another Win2k machine, I got the following | strange results: [snip results showing manifest existence of directory and contents, os.path.exists to the contrary] I believe this is because \\machine\name is not considered a path, but rather a share. Whether this distinction is down to Microsoft terminology, some decision by the Python library developers, or (and this is the most likely) the underlying MS C runtime library, I couldn't say. At a quick inspection, ntpath.exists calls os.stat, which will refer to nt.stat and as I don't have the Python source, I can only guess that that calls some lower level C Runtime function, passing back whatever that returns. Personally I would have thought that exists ("\\machine\name\.") might have given the desired result, but apparently not. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Tue Jun 29 00:33:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 00:33:40 -0400 Subject: Is there a more elegant way to do this? In-Reply-To: <889cbba0.0406281012.88d6dc1@posting.google.com> References: <889cbba0.0406261358.6bc18e1d@posting.google.com> <889cbba0.0406281012.88d6dc1@posting.google.com> Message-ID: Kamilche wrote: > Peter Hansen wrote in message news:... > > >>def pack(self): >> args = ('Iid Iparent Inumber ix iy iz Bred Bgreen Bblue ' >> 'Hsize Hrotate Htranslucency') >> lst = zip(*[(x[0],x[1:]) for x in s.split()]) >> return struct.pack('<' + ''.join(lst[0]), >> *[getattr(self, n) for n in lst[1]]) > > > You scary c-like-code-creator, you. :-O More like Perl, I think, which packs all the unreadability of C into one tenth the space. Actually, I thought someone would comment on the emergent Hungarianesque notation in the above... I think if I were doing this for real (and I might well if I had the need), I'd use a decent separator to make the args string more readable, maybe just 'I-id I-parent I-robot...' or something. That makes the (x[0], x[1:]) turn into the somewhat cleaner x.split('-'). Another actually: zip I find just plain incomprehensible, but it sure comes in handy from time to time. I can't seem to fit it in my brain though, and constantly resort to the interactive prompt to figure out how to use it. Bummer.... -Peter From winexpert at hotmail.com Thu Jun 10 14:37:25 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 10 Jun 2004 18:37:25 +0000 Subject: [python] -- interesting use of the webbrowser module Message-ID: In the ongoing endeavor to learn python I started playing with the webbrowser module. In this case I found an unorthodox way to launch an editor using the webbrowser. Instance x just uses lynx to open a website. instanze z however, opens an editor on a file. I'm sure there are other ways to do it, I just saw it as a slightly different way to do this. I guess what it really means is the 'open' simply launches the requested application and then that application does whatever it does. One thing I did notice is that the 2nd launch doesn't occur until the first has completed. which makes each of these operations synchronous in nature. (no kwrite until lynx has closed). code: ------------------ START CODE ----- import webbrowser as wb x = wb.GenericBrowser('lynx %s') z = wb.GenericBrowser('kwrite %s') print "Opening instance X" x.open('cellphone.duneram.com') print "Opening instance Z" z.open('/tmp/xyzabc') ----------------- FIN DE CODE ------- David ------- Tracfone: http://cellphone.duneram.com/index.html _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From loic at yermat.net1.nerim.net Mon Jun 21 15:48:30 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Mon, 21 Jun 2004 21:48:30 +0200 Subject: References and copies In-Reply-To: References: Message-ID: Thomas Philips a ?crit : > I want to represent an NxN matrix by a list containing N lists, each > of which has N elements. Initially the elements are set to " ". For > N=2, I write > > >>>>x = [" "][:]*2 #assignment creates references, not copies! >>>>x > > [' ', ' '] > >>>>y = [x[:]]*2 >>>>[...] > > I fail to see the error in my first attempt. Where is the fly in the > ointment? > > Thomas Philips Your trboules come from this line: y = [x[:]]*2 because you do not copy the x twice but just assign a copy of x twice... see the following: >>> x = [" "]*2 >>> x [' ', ' '] >>> x = [" "]*2 >>> y = [x]*2 >>> y [[' ', ' '], [' ', ' ']] >>> id(y[0]) 8303600 >>> id(y[1]) 8303600 >>> >>> y = [[" "] *2, [" "]*2] >>> id(y[0]) 8306544 >>> id(y[1]) 8305424 >>> -- Yermat From dickey at saltmine.radix.net Tue Jun 22 06:21:19 2004 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Tue, 22 Jun 2004 10:21:19 -0000 Subject: Curses and resizing windows References: Message-ID: <10dg20v5dpqpi73@corp.supernews.com> Chris Share wrote: > I've been writing an application using curses, and have been trying to > handle resizing the terminal, if running in xterm or similar. Increasing > the window size is working perfectly, however shrinking it is not > working at all. No matter how much I shrink the window, the size > returned by getmaxyx() does not change. However as soon as I increase it > again, it works fine. > I've tracked the problem down to the fact I have created a window > derived from stdscr. A small script showing the effect is at the end of > this post. odd (thanks for the example - I don't know if this is a problem in ncurses or in the python interface to it, but will check/see). > Can anyone suggest how to solve this problem, that doesn't involve not > making a derwin of stdscr? > I've been googling for hours, but found nothing to help. > Python version is 2.3.4 on debian testing. probably should report it as a bug (so it's not overlooked). -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From hungjunglu at yahoo.com Wed Jun 9 04:19:13 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 9 Jun 2004 01:19:13 -0700 Subject: Interfaces and Exceptions References: Message-ID: <8ef9bea6.0406090019.447020b9@posting.google.com> Calvin Spealman wrote: > 2) How can I raise an exception and catch it based on the interfaces it > implements? By using Java? :) Seriously, checked exceptions a la Java were such a bad idea that even Java people came up with "patterns" to convert them to unchecked exceptions. C# designers simply discarded checked exceptions from a start and designed their exception handling based on the Python exception handling model. (This is mentioned in a Microsoft's paper, but I don't have the reference off hand.) So, no need to mix exceptions with interfaces, unless you are a masochist. http://www.mindview.net/Etc/Discussions/CheckedExceptions regards, Hung Jung From mark at pyzine.com Fri Jun 25 08:52:28 2004 From: mark at pyzine.com (Mark) Date: Fri, 25 Jun 2004 08:52:28 -0400 Subject: Python Magazine exists! (was: Python intro questions) Message-ID: <83B0CB7E-C6A6-11D8-957B-000D932A0486@pyzine.com> Hi, It seems a lot of people are not aware that a Python Magazine exists. Visit: http://www.pyzine.com to see what we are publishing this quarter and check out our free articles to see what kind of articles we publish. I'd like to repudiate once and for all the claim that: "Nobody gets paid to write articles about Python" We can't speak for other publishers/Magazines but this is certainly not the case at Py. Every quarter we pay for at least seven articles and quite frankly would like to pay for more. We also pay two great editors Kendall Clark and Eric-Peter Germain to edit all articles that we publish. See our Writers Guidelines for more info: http://www.pyzine.com/writefor.html We'd also like to point out that our sister publication ZopeMag: http://www.zopemag.com publishes on average another 8 articles per quarter of which some are the rough equivalents of Book Chapters (the parts of our SuperGuides). Since Zope is written mostly in Python we would argue that much of the content in ZopeMag are Python articles (but obviously with a focus on Zope/Plone/CPS/Silva). If you would like to see more Python articles and would like to support the only Python Magazine please consider subscribing. Regards, Mark From db3l at fitlinxx.com Fri Jun 11 12:34:31 2004 From: db3l at fitlinxx.com (David Bolen) Date: 11 Jun 2004 12:34:31 -0400 Subject: raw Strings from XML attributes References: Message-ID: Karen Loughran writes: > Hiya, > > I'm reading a string attribute from an XML document. The string > contains newline characters and is treated as raw. > I'm trying to match it with a string read from a file which is > identical . But because it isn't raw it won't match. > > I've seen documentation for converting string 'literals' to raw form > with r'Sample String'. But is there a function which will convert my > raw string read from XML to non-raw/escaped sequence format ? Or to > convert a string 'variable' read from a file to raw form ? ie, I'm not > converting string 'literals' ? If I understand you correctly I think you want repr() (or %r in a format string). This will produce a string representation of a Python object, which is designed to make a best attempt at a string that could create the original object when passed into eval(). While that doesn't necessarily hold true for arbitrary objects, for strings it means that it produces the raw/escaped format - thus distinguishing itself from the str() function (or %s formatting operator) which attempts to produce a nicely printable form. For example: >>> test = 'Test\t\\ing' >>> print str(test) Test \ing >>> print repr(test) 'Test\t\\ing' (Note that I replaced the literal tab in the first output with 8 spaces to ensure it works in the newsgroup posting, but the actual output from the interpreter was a literal tab) -- David From grey at despair.dmiyu.org Fri Jun 4 19:43:06 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 23:43:06 GMT Subject: python vs awk for simple sysamin tasks References: <2ic128FllgicU1@uni-berlin.de> <2icbruFlqs1aU1@uni-berlin.de> <2ice7nFimf62U1@uni-berlin.de> Message-ID: On 2004-06-04, William Park wrote: > 4x faster? Not very impressive. I suspect that it's poor quality shell > script to begin with. Would you post this script, so that others can > correct your misguided perception? No. 1: It was an internal script for statistics gathering and I did not have permission to expose that code to the public. 2: Even if I did I no longer work there. The just of it though was that it was a disk usage script which tabulated usage for a few hundred thousand customers. It had to go through several slices (it wasn't a single large directory) find the customers in each of those slices, calculate their disk usage and create a log of it. The Perl recode came about when management wanted some exclusions put in and the shell script was breaking at that point. They also wanted a lower run-time if possible. So I spent an hour or two, most of it in the recursion walk across the file-system (thank dog Python has os.path.walk!) rewriting it in Perl. The stat calls were not reduced, we still had to do a stat on every file to get the size as before. However we no longer were going through the overhead of constantly opening and closing pipes to/from du as well as the numerous exec calls. 4x faster measured in hours based pretty much on building up and tearing down those pipes and executing the same program over and over is rather impressive given how miniscule those operations are in general is impressive. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From selkrank at luukku.com Wed Jun 16 01:24:12 2004 From: selkrank at luukku.com (=?ISO-8859-1?Q?Jussi_Lepist=F6?=) Date: Wed, 16 Jun 2004 05:24:12 GMT Subject: ANN: Spineless game engine 0.0.1 Message-ID: Spineless is a generic 3D game engine implemented in Python with C++ optimizations. Focus is on clean design and ease of use, not pure speed. It is still very incomplete and not really useful yet for serious use, but I would appreciate feedback, comments and suggestions. Notable features: - Clean design - Both 2D and 3D graphics accelerated with OpenGL - Custom, completely resolution-independent GUI module - Resource management (fonts, textures, sound samples) - Scene graph with collision detection - Physical simulation with collision response and friction Note that the engine is still very unpolished and unoptimized and lacks proper documentation. However, you can mail me with questions and suggestions. You can find the Spineless web page here: http://spineless.sourceforge.net/ -Jussi From klachemin at home.com Wed Jun 9 13:51:08 2004 From: klachemin at home.com (Kamilche) Date: 9 Jun 2004 10:51:08 -0700 Subject: Creating True Global Functions by Modifying Builtins Message-ID: <889cbba0.0406090951.32a6434b@posting.google.com> I really, really want a handful of 'true' global functions, ones that can be called from anywhere without requiring importing. So I added it to the 'builtins' of Python, and it appeared to work. :-O Will this have unintended side-effects? :-D Take a look: def traceme(s): print "trace:", s import types def BuiltInFunctions(): callables = (types.BuiltinFunctionType, \ types.BuiltinMethodType, \ types.CodeType, types.FunctionType, \ types.GeneratorType, \ types.MethodType, \ types.UnboundMethodType) builtins = globals()['__builtins__'] d = vars(builtins) list = [] for name, value in d.items(): if type(value) in callables: list.append(name) list.sort() return list def AddBuiltIn(name, fn): builtins = globals()['__builtins__'] d = vars(builtins) if d.has_key(name): raise Exception("Can't override built in " + \ " function " + name + "!") d[name] = fn print "Built in functions before adding 'trace':" print BuiltInFunctions() AddBuiltIn('trace', traceme) print "Built in functions after adding 'trace':" print BuiltInFunctions() trace("hi there") From simoninusa2001 at yahoo.co.uk Thu Jun 10 17:10:35 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 10 Jun 2004 14:10:35 -0700 Subject: Q: Making Python use no shared extension modules? References: Message-ID: <30260531.0406101310.65489ea7@posting.google.com> I don't think you can do it. The closest you'd get is McMillan Installer's --onefile which basically zips up all the modules into one file, which decompressed on the fly when run, although when I've tried it on clean Linux boxes, it still requires non-Python stuff (like a wxPython app still requires wxTGK installed). From max at alcyone.com Wed Jun 2 19:26:20 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jun 2004 16:26:20 -0700 Subject: Why did no one invent Python before? References: Message-ID: <40BE621C.97EEC2AA@alcyone.com> j_mckitrick wrote: > Seriously, why is a language like this only NOW appearing? And aside > from the interpreter, because while it is nice, it's not the main > forte' of the language, IMHO. I think there's some validity to this question. It probably has to do with a combination of things. First, it takes a while from the inception of a language before it gets enough development behind it that it's as powerful as Python is. Even if everyone immediately recognizes the merits of the languages, it takes a sort of "critical mass" of people before it really takes off, in terms of usage and people hearing about it, as well as in terms of building enough of the standard libraries to make doing advanced things with it a snap. Of course, things like the Internet have contributed to letting people get in touch with each other much more easily. Remember that Python has been around for over ten years; it takes a while for a language to become stable, build up a developer community that continues to add features to it, and attracts a base of users. Even with the Internet, that takes time. Additionally, I think it's at least partially a matter of building up "technology," so to speak. First, computers have been getting faster and more powerful for a long time now, of course, but it's only the last five years or so where it's really been practical to make a high-level language whose primary concern is not speed, but where machines are fast enough that for a very large majority of applications. There has certainly been a niche market for high-level languages in the past, but computers were often limited enough that you had to carefully fit them to a task. Nowadays computers are so fast and have so much memory that it's the other way around -- you usually don't need to worry about raw performance at all. Second on the "technology" front is, to lump a bunch of things together in one term, the computer science. It takes a while to build up powerful high-level programming ideas that can be brought to bear easily and effectively in a programming language. Language designers need to put things together in a way that makes sense, is relatively easy to use, and is also powerful. Lots of languages don't do it well. Python does, and I think there are other examples that also fit into the first technology point, but haven't reached massive popularity yet, like Io. Simply put, we live in a time where we have computers that are fast enough that it's very practical to use high-level languages, and we live in a time where we've had enough practice at it that the the creme of the crop are really good at what they do. That makes the creation of something like Python possible. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Love is when you wake up in the morning and have a big smile. -- Anggun From dduncan at rubackedup.com Tue Jun 22 23:31:34 2004 From: dduncan at rubackedup.com (David Duncan) Date: Tue, 22 Jun 2004 22:31:34 -0500 Subject: Unix fold command in python References: <70efe2ee.0406140250.79dc95b8@posting.google.com> Message-ID: On Mon, 14 Jun 2004 03:50:06 -0700, dean wrote: > Hello Group: > > Hopefully someone can answer my question. > > I have a unix shell command that I would like to emulate in python. I > am sanning a file that contains a stream of data with a record size of > 242 bytes but no record delimiters. There are multiple fields in each > record that can be mapped according to their position: > > example > > field1 byte 0-4 > field2 byte 5-8 > > How do I make python read a record in and report the contents of a > particular field (and may be carry out an operations with that field). > > Much appreciated > > regards > > dean isn't this just a slice? like so? alllines = file.readlines() for each in alllines: field1 = each[:4] field2 = each[4:8] From http Sun Jun 20 22:43:26 2004 From: http (Paul Rubin) Date: 20 Jun 2004 19:43:26 -0700 Subject: OT: Chat server References: <8ef9bea6.0406170749.399c4956@posting.google.com> <7xbrjef78f.fsf@ruckus.brouhaha.com> <8ef9bea6.0406201735.6ead8e4b@posting.google.com> Message-ID: <7xr7s9bpgx.fsf@ruckus.brouhaha.com> hungjunglu at yahoo.com (Hung Jung Lu) writes: > > Why? IRC seems a lot better for chatting. > > Perhaps this helps a little bit: > > http://www.jabber.org/about/overview.php All I see in there is a bunch of buzzwords. I'm unimpressed with most buzzwords, including "XML". Can you give a brief technical description of how Jabber works and how it's different from IRC? Right now I hang out on an IRC network (Undernet) that has hundreds of thousands of users chatting in real time. For example, #linux has a couple hundred users in 20 different countries, all blabbing away without too much lag most of the time. How well can Jabber scale to that kind of load? From peter at engcorp.com Mon Jun 14 08:55:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 08:55:09 -0400 Subject: Anonymous file closing In-Reply-To: References: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> Message-ID: <_NGdnQVTVq2zPVDdRVn-hg@powergate.ca> Sergey Krushinsky wrote: > Peter Hansen wrote: > >> Duncan's response says it all, but here's the solution >> if you don't like the uncertainty inherent in the above: >> >> f = open(filename, 'r') >> try: >> text = f.read() >> finally: >> f.close() >> > But the uncertainty remains in case of an anonymous file, doesn't it? Uh, yeah... of course! Duncan posted code with uncertainty, and I showed what one must change to make it certain (or less uncertain, after reading Tim Peters' comment). How that would change the original case with the anonymous file in any way I just can't imagine. (Clearly I'm missing something, or you are...) -Peter From bkc at Murkworks.com Tue Jun 22 11:06:03 2004 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 22 Jun 2004 11:06:03 -0400 Subject: meta confusion new.instance() argument 1 must be classobj, not type Message-ID: I need to dynamically create a new type of class at runtime, based on an oldstyle class and a new style class. I'm using Python 2.3.2 My code: def shipment_from_db_instance(db_shipment): """ Create a new shipment object from a db_shipment instance (old style) """ global _new_shipment_factory if not _new_shipment_factory: # create a new shipment factory dynamically _new_shipment_factory = type('NewShipment', (Shipment, db_shipment.__class__), {}) print "factory is ", _new_shipment_factory, type(_new_shipment_factory) return new.instance(_new_shipment_factory, db_shipment.__dict__) But I get this output: factory is File "/home/bkc/src/Python/MurkWorks/Shipments/Shipment.py", line 81, in shipment_from_db_instance return new.instance(_new_shipment_factory, db_shipment.__dict__) TypeError: instance() argument 1 must be classobj, not type It seems that new.instance() doesn't understand how to make instances from types. I tried this interactively and got the same error. >>> class old: pass ... >>> class new(object): pass ... >>> c = type('combined', (new, old), {}) >>> c >>> import new >>> i = new.instance(c, {}) Traceback (most recent call last): File "", line 1, in ? TypeError: instance() argument 1 must be classobj, not type What am I doing wrong, or is this a bug? -- Novell DeveloperNet Sysop #5 _ From pinard at iro.umontreal.ca Tue Jun 15 00:17:51 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 15 Jun 2004 00:17:51 -0400 Subject: RELEASED: pynits 040615 Message-ID: <20040615041751.GA12765@titan.progiciels-bpi.ca> Hi, my Python and Vim friends. Here is the initial release of `pynits', and the beginning of its documentation file. I hope some courageous souls will help me at eradicating packaging and other blunt bugs! :-) *pynits.txt* Tidying up Python files TIDYING PYTHON CODE WITHIN VIM Fran?ois Pinard pinard at iro.umontreal.ca Pynits is a tool which I find useful while editing Python source code with Vim, for tidying up individual sources lines, and some auxiliary tasks. It is particularly helpful when formatting lines holding long or complex expressions. This tool requires a Python-enabled Vim. 1. Introduction |pynits-introduction| 2. Finding nits |pynits-finding-nits| 3. Reformatting lines |pynits-reformatting| 4. Other commands |pynits-other-commands| The Pynits tool may be downloaded from: http://fp-etc.progiciels-bpi.ca/showfile.html?mode=archives while installation directives may be found at: http://fp-etc.progiciels-bpi.ca/showfile.html?name=pynits/README This file you are reading is also available on the Web as: http://fp-etc.progiciels-bpi.ca/showfile.html?name=pynits/pynits.txt WARNING: This tool is in alpha state, its specifications may change. Write to the author for corrections, suggestions or bug reports. ============================================================================== 1. Introduction *pynits-introduction* I once had to take over the maintenance of a set of big Python modules, written by someone without much concern about source line length limits, and also a bit lacking in the area of sound coding standards. The sources were hard to read on an usual terminal screen, hard to print without stunts on a printer, hard to edit: in a word, hard to maintain. When it comes to source coding standards, people develop religious feelings. My personal coding practices, which are somehow reflected in this tool, are surely debatable and questionable, yet I dare to think they are quite reasonable. I use an eclectic choice of good ideas from various sources: the Python mode as written for GNU Emacs, the standard Python plugin for Vim, Guido's own style as he documented it, some relevant parts of GNU and Gnits standards, good horse sense, but also, my own programming experience, accumulated for a good while by now. Source code lines are often carefully crafted by programmers, and a reformatting tool may defeat local art work. This is why I think reformatting is best done from with a scalpel, like Vim may be, than operated in bulk or in batch. The programmer may choose to accept or refuse, on a line basis, suggestions made by a tool like this one. There are three sets of commands in this tool. The first set is meant to discover and report various formatting nits. The programmer may then ask the tool for correcting them, when a correction recipe is known. The second set takes a whole Python source line, possibly continued, and fully rebuilds a surface representation from its syntax tree. The third set contains a few random commands for simple tasks. [...] -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From lard at tardis.ed.ac.molar.uk Wed Jun 30 08:34:49 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Wed, 30 Jun 2004 13:34:49 +0100 Subject: PY_LONG_LONG problem Message-ID: <10e5cr9t7o7v1cf@corp.supernews.com> I've compiling boodler (http://www.eblong.com/zarf/boodler/), which is written (mostly) in python, for windows, using Python 2.3. When at the stage of compiling some C code, I'm running into problems: $ make make[1]: Entering directory `/cygdrive/c/tools/boodler/cboodle' gcc -O2 -I/usr/include/python2.3 -Wall -Wmissing-prototypes -Wstrict-prototype s -Wno-unused -c -o cboodle.o cboodle.c In file included from C:/Python23/include/Python.h:75, from cboodle.c:15: C:/Python23/include/intobject.h:41: error: syntax error before "PyInt_AsUnsigned LongLongMask" [snip a few more errors] The problem is that the compiler is falling over whenever PY_LONG_LONG is mentioned. The first example, from intobject.h as reported above, is this: #ifdef HAVE_LONG_LONG PyAPI_FUNC(unsigned PY_LONG_LONG) PyInt_AsUnsignedLongLongMask(PyObject *); ^^^^^^^^^^^^ then, following things along, I see that in pyport.h we have: #ifndef PY_LONG_LONG #define PY_LONG_LONG long long so, is it "long long" that is actually causing the problems here? I've never compiled C that uses python includes before, so I'm a bit stumped. thanks alex From brian at sweetapp.com Tue Jun 1 08:55:29 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 01 Jun 2004 14:55:29 +0200 Subject: Am I asking too much from datetime? In-Reply-To: References: Message-ID: <40BC7CC1.7020801@sweetapp.com> >>>>yesterday = datetime.date(today.year, today.month, today.day-1) > Is this is a bug, or outside of the functionality of datetime? Try writing it like this: >>> import datetime >>> today = datetime.date.today() >>> print today 2004-06-01 >>> yesterday = today - datetime.timedelta(days=1) >>> print yesterday 2004-05-31 Cheers, Brian From tor.iver.wilhelmsen at broadpark.no Sun Jun 6 03:23:43 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 06 Jun 2004 09:23:43 +0200 Subject: if does not evaluate References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: Tor Iver Wilhelmsen writes: > x = (expr1, expr2)[something]; Um, other way around of course :) : x = (expr2, expr1)[something]; From eriksp at attbi.nospam.com Sat Jun 5 12:56:21 2004 From: eriksp at attbi.nospam.com (EAS) Date: Sat, 05 Jun 2004 16:56:21 GMT Subject: Minor problems with python Message-ID: Whenever I open a python program using a normal console window, it says: 'import site' failed; use -v for traceback What does this mean and how can I get rid of it? Also, I have this one program that won't stay open at all; when I into IDLE and run it there to see what the problem is, it just says: >>> =========================== RESTART ============================ >>> then it starts the program. How do I fix this? Here's the code for it if needed: ############################################################### # Python Command Prompt - by Gecko_LoL, 6/5/2004. Version 1.0 # ############################################################### from os import chdir, startfile, getcwd, listdir, \ remove, rmdir, mkdir, rename, system command = "" error = ".error." print ("\tPython Command Prompt\n") while command != "q": try: command = raw_input(">>> ") if command.lower() == "cd": dir = raw_input("... ") chdir(dir) elif command.lower() == "st": file = raw_input("... ") startfile(file) elif command.lower() == "dir": dir = getcwd() print dir, "\n" elif command.lower() == "li": for item in listdir("."): print item print elif command.lower() == "linum": start = input("... ") end = input("... ") for item in listdir(".")[start:end]: print item print elif command.lower() == "del": file = raw_input("... ") remove(file) elif command.lower() == "rd": dir = raw_input("... ") rmdir(dir) elif command.lower() == "md": dir = raw_input("... ") mkdir(dir) elif command.lower() == "ren": old = raw_input("... ") new = raw_input("... ") rename(old, new) elif command.lower() == "com": com = raw_input("... ") system(com) else: if command == "q": break print error continue except: print error continue From martin at v.loewis.de Sat Jun 19 18:19:43 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 Jun 2004 00:19:43 +0200 Subject: Watershed Python Versions In-Reply-To: References: <40dd3107.0406191120.6879a1c6@posting.google.com> Message-ID: <40D4BBFF.7030508@v.loewis.de> Dennis Lee Bieber wrote: >>As an example, in Windows operating systems, I would consider Windows >>98SE to be the pre-NT watershed release and Windows 2K to be the >>post-NT release. >> > > NT preceded W98, based on my experience... Almost preceded W95 > if you consider NT3.51. Why "almost"? I have used NT 3.1 in '93 or so. There was no mentioning of a DOS-based Win32 implementation except for Win32s at that time, and NT was considered the successor, to both Win3.1 and OS/2. NT predates Win 3.11. Regards, Martin From bh at intevation.de Wed Jun 9 14:22:26 2004 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 09 Jun 2004 20:22:26 +0200 Subject: strange __del__ behavior References: Message-ID: John Hunter writes: > For debugging purposes, I would like to know when C instances are > being deleted; that's why I inserted the __del__ print method. Is > there any way to get that info w/o defining __del__ and thereby > screwing up python's garbage collection? I've sometimes used something like this: class DelReporter: def __init__(self, message): self.message = message def __del__(self): print self.message class C: def __init__(self): self.__del = DelReporter("__del__: %r" % self) Even if a C-instance is part of a cycle, its __del member is not, so it's __del__ doesn't affect garbage collection. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From bram at nospam.sara.nl Wed Jun 23 08:49:47 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 23 Jun 2004 14:49:47 +0200 Subject: Parsing C Preprocessor files References: <20040623140151.6b8863f2@pistache.sara.nl> <4ICdnaUZjtvV5UTdRVn-jw@powergate.ca> Message-ID: <20040623144947.56365a88@pistache.sara.nl> On Wed, 23 Jun 2004 08:32:08 -0400 Peter Hansen wrote: > Bram Stolk wrote: > > > What could I use to parse CPP macros in Python? > > I tried the Parnassus Vaults, and python lib docs, but could not > > find a suitable module. > > Does it really need to be in Python? There are probably > dozens of free and adequate macro preprocessors out there > already. I want to trigger Python actions for certain nodes or states in the parse tree. I want to traverse this tree, an be able to make intelligent actions. For this, I want to use python. > (You might also want to clarify what you mean by "parse" > in this case... do you mean actually running the whole > preprocessor over an input file and expanding all macros, > or do you mean something else?) Roughly speaking, I want to be able to identify sections that are guarded with #ifdef FOO Because conditionals can be nested, you would have to count the ifs/endifs, and additionally, the conditional values may depend on other preprocessor command, e.g. values may have been defined in included files. If I can traverse the #if/#endif tree in Python, a preprocessor file becomes much more managable. Bram > -Peter -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "Software is math. Math is not patentable." OR "Software is literature. Literature is not patentable." -- slashdot comment ------------------------------------------------------------------------------ From apardon at forel.vub.ac.be Mon Jun 28 07:21:09 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jun 2004 11:21:09 GMT Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: Op 2004-06-25, Mark Hahn schreef : > > There are many clean readable programming conventions that rely on return > values. This is certainly an acceptable construct, right? > > while len(list.append!(x)) < 10: > blah blah blah > > Compare that to the less readable and less maintainable Python version: > > list.append(x) > while len(list) < 10: > blah blah > list.append(x) # duplicate code > > I can come up with many more. I think when you have been without a language > feature for a while you tend to block it out of your mind. Well personnally I would solve this with a more general loop construct. Something like: (Pseudo code) loop: list.append(x) while len(list) < 10: blah blah. The more general construct would be something like: loop: code while condition1: code else: exit code if condition1 fails while condition2: code else: exit code if condion2 fail Does prothon provide for such a general loop? From tzot at sil-tec.gr Tue Jun 22 05:16:05 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jun 2004 12:16:05 +0300 Subject: [PEP] auto keyword for automatic objects support in Python References: Message-ID: On Fri, 18 Jun 2004 16:32:39 GMT, rumours say that Manlio Perillo might have written: [snip] >With the use of auto there is the need(?) to think at object >destruction as a two fase operation (like object creation with __new__ >and __init__). > >In fact __del__ method is called when the object is being >deallocated/garbage collected (actually this is not 'deterministic'). >The RAII pattern requires simply that as an object goes 'out of scope' >it should releases all the 'external resources' it has acquired. >So there is the need of a second special method (call it __deinit__) >that should be called for auto objects when they go 'out of scope' >(in a 'deterministic' way). [snip] I'm afraid your PEP's strongest adversary will be the "Explicit is better than implicit". You suggest complications to the language implementation that can be avoided just by user code. For example, you could have a class Deallocator (untested improvised code): class Deallocator: def __init__(self, *args): self.args = args def deallocate(self): for obj in self.args: obj.__deinit__() then in your function start: auto = Deallocator(obj1, obj2 ...) and in your function end: auto.deallocate() If your function has multiple exit points, wrap its code in a try ... finally sequence. These are some of the obvious counter-arguments for your PEP, and without looking I assume there have been already similar discussions in the past. Good luck :) -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From http Wed Jun 23 00:33:08 2004 From: http (Paul Rubin) Date: 22 Jun 2004 21:33:08 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: <7xd63qx5a3.fsf@ruckus.brouhaha.com> klachemin at home.com (Kamilche) writes: > I've written an encryption algorithm in pure Python that can process > 22 megs of data a second. I know it's not secure, but it should be > enough to ward off casual hacking. Does someone know of something > speedier? Yes, you can just copy the input to the output. That's quite fast, and it's at least as insecure as your method. From tjreedy at udel.edu Sun Jun 20 20:37:40 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 20 Jun 2004 20:37:40 -0400 Subject: docstrings vs language comments References: <930ba99a.0406201027.516ea515@posting.google.com> Message-ID: <-uqdnRXCRZpLsEvdRVn-ug@comcast.com> "Sridhar R" wrote in message news:930ba99a.0406201027.516ea515 at posting.google.com... > When writing a python library, we can use docstrings for methods and > functions that are part of API. But what about comments for non-API > objects or python application code? To my mind, docstrings are for saying how to use a module/class/function (what is does and i/o specs) while comments are for saying how it does it (the algorithm, which could change without changing the interface). > For applications, docstrings are not really much useful. Instead > language comments are prefered for them. Docstrings and comments are for the benefit of programmers who use and revise the code, not for non-programmers ultimate users. I don't see much difference in this respect between a library function and a specific application function. > Language comments (starting with #) are usually considered to be a > little more readable than docstrings (when reading the source code for > understanding it). I think I personally prefer and find it easier to read docstring material (as defined above) if it is consistently in docstring format. > So for non-API objects language comments will be prefered. > > Thoughts? You are entitled to your different opinions, but stating them as facts does not change their status as opinions ;-). Terry J. Reedy From feedback at gamespyarcade.com Fri Jun 18 12:00:55 2004 From: feedback at gamespyarcade.com (feedback at gamespyarcade.com) Date: Fri, 18 Jun 2004 12:00:55 -0400 Subject: Hello Message-ID: Important document! -------------- next part -------------- A non-text attachment was scrubbed... Name: Important.zip Type: application/octet-stream Size: 22414 bytes Desc: not available URL: From robin at SPAMREMOVEjessikat.fsnet.co.uk Sun Jun 6 08:05:26 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sun, 06 Jun 2004 13:05:26 +0100 Subject: bug in inspect (was cgitb vs traceback) In-Reply-To: References: Message-ID: <40C30886.3070303@jessikat.fsnet.co.uk> Robin Becker wrote: > Hi, I took part in the python bugday and fixed this bug as well as a whoops this was s'posed to go to an interested party. -- Robin Becker From jg at jonasgalvez.com Wed Jun 23 02:52:33 2004 From: jg at jonasgalvez.com (Jonas Galvez) Date: Wed, 23 Jun 2004 03:52:33 -0300 Subject: Regex question Message-ID: I've a perhaps unusual piece of data to parse with regexes. >>> import re >>> re.findall("a (\w ?)*", "a b c d e f g h") ['h'] This is a very very very simplified example. The result I was expecting is the following: ['a', 'b', 'c'] ... and so forth. Is it impossible to repeat a pattern group inside another? Tia, \\ jonas galvez // jonasgalvez.com From mark at prothon.org Sun Jun 6 16:52:23 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 6 Jun 2004 13:52:23 -0700 Subject: left-quote ( ` ) on International keyboards [Prothon] Message-ID: Can users with international keyboards tell me if they have problems typing the left-quote ( ` ) character? It isn't used much in Python but we are thinking of giving it a slightly more important role in Prothon. (I'm not going to say what that role is here to avoid starting another 300 message thread like I did last time :-) If you are curious you can go to the Prothon mailing lists at http://prothon.org). From ilya at cray.glas.net Fri Jun 25 03:55:25 2004 From: ilya at cray.glas.net (Ilya Etingof) Date: Fri, 25 Jun 2004 07:55:25 +0000 (UTC) Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> <65vsq1-9l1.ln1@nb2.stroeder.com> Message-ID: Michael Str?der wrote: [ skipped ] > AFAIK the BER encoding/decoding is implemented in pure Python. If one has > the time to implement these routines in C it'd be much less CPU intensive I > guess. I've got an impression, that building/parsing BER is not computationally intensive. In fact, BER encoding has been designed to cope with rather limited resources (in terms of about 20 yo hardware!). As an alternative bottleneck I'd rather propose 1) object instantiation and 2) function calls. As of this writing, pysnmp.asn1 code is designed as a top-down parser what implies intensive recursion and object creation. Although not a real receipt but rater a workaround, I'd suggest caching and reusing top-level ASN.1/SNMP objects (such as SNMP message) inside your app whenever possible. This might safe lots of CPU on a long run. -ilya From andrej_dzerzhinsky at hotmail.com Tue Jun 22 14:03:41 2004 From: andrej_dzerzhinsky at hotmail.com (Andrej Dzerzhinsky) Date: 22 Jun 2004 11:03:41 -0700 Subject: Interactive use of DISLIN Message-ID: I'm building a scientific app using wxPython to call some C functions together with a suitable plotting application that will work within a wxPython frame. I'd like to plot a spline over several thousand (x,y) points from a spectrum, reasonably fast, and be able to zoom in and out of the plot, label peaks either automatically or by hand, display and overlay multiple data sets and export plots as metafiles. Platform independence is also a big plus. Examining several of the Python plotting packages (BLT, matplotlib, pyplot, hippodraw, DISLIN), so far DISLIN seems to offer the best combination of speed and ease of use, with matplotlib coming a close second. Can anyone comment on whether DISLIN can be made to do the interactive things I have mentioned. http://www.openboa.de/srd/node8.html claims it can't - is this accurate? Or is matplotlib or some other package better for what I want. Thanks for your time. From chris.cottee at onepost.net Fri Jun 11 04:55:18 2004 From: chris.cottee at onepost.net (Chris Cottee) Date: 11 Jun 2004 01:55:18 -0700 Subject: Functional test web site using python com and Internet Explorer References: <874qpkjrkl.fsf@pobox.com> Message-ID: Cheers for your help John, I'd forgotten to look at that mailing list so I've trawled the archives and posted a question their as well. I've had a look at that Internet Macro tool you mentioned and it is very close to what I would like except that of course it is not open so I can't change it. My guess is that it is implemented using COM and Internet Explorer which would be encouraging since it would mean that what I am trying to do would work. Yours optimistically, Chris From jepler at unpythonic.net Wed Jun 16 08:50:07 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 16 Jun 2004 07:50:07 -0500 Subject: Looking for a different version of sort In-Reply-To: References: Message-ID: <20040616125006.GB19510@unpythonic.net> > "Delaney, Timothy C (Timothy)" wrote in message news:... > ... > > There is no function available which sorts in-place and returns a > > reference to the list sorted, but it's very simple to write a function > > to do it ... > > > > def inplace sort (l): > > l.sort() > > return l On Wed, Jun 16, 2004 at 01:10:16AM -0700, Dan Bishop wrote: > Or, alternatively: > > sort = lambda l: (l.sort(), l)[1] I'm not sure why you suggest this. It benchmarks a little slower than Timothy's version. The speed difference probably results from constructing and then discarding the tuple. Jeff $ cat /tmp/danb.py def inplace_sort1(l): l.sort() return l inplace_sort2 = lambda l: (l.sort(), l)[1] $ timeit -s \ 'import sys; sys.path.append("/tmp"); from danb import inplace_sort2; l = []' \ 'inplace_sort2(l)' 1000000 loops, best of 3: 1.39 usec per loop $ timeit -s \ 'import sys; sys.path.append("/tmp"); from danb import inplace_sort1; l = []' \ 'inplace_sort1(l)' 1000000 loops, best of 3: 1.1 usec per loop -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mark at prothon.org Fri Jun 25 16:11:13 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 25 Jun 2004 13:11:13 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: Dave Brueck wrote: > Ahh...so the method name is just _spelled_ with an exclamation point? Yes, a Prothon identifier is the same as a Python identifier except that it can end with an exclamation mark ( ! )or a question mark ( ? ). These marks can only appear at the end and there can only be one. It is up to the programmer to make sure he/she uses them properly. Exclamation marks are to be used in identifiers if and only if it is a method that modifies the target in-place. Question marks are to be used on methods if and only if they return True or False and nothing else. > IOW, the ! is a token you can use at the end of an identifier, but it > is not actually used by the language itself - No, the marks are significant to the language just as any other part of the identifier is. > Seems like a waste to reserve a > symbol for something so rarely needed. I disagree. In-place modification is significant and happens often. Ignoring this is dangerous. >>> Personally, I don't like the modify-in-place-and-return-the-object >>> 'feature' - it's not needed _that_ often, but more importantly, it >>> makes the code harder to read (to me at least). >> >> If you use the Prothon append!() exactly as you use the Python >> append() you will get the exact same results. This is just an extra >> feature for those that want it. >> >> Guido avoided returning values from in-place modification functions >> because of the confusion as to whether in-place mods were happening >> or not. We have solved that confusion with the exclamation mark. >> Our code is very readable because of this. > > Clearly, readability is in the eye of the beholder. :) How can you argue that the exclamation mark indicating in-place-modification does not make it more readable? Several other languages feel so also. We didn't just make this up. From kav062 at yahoo.com Mon Jun 14 11:27:41 2004 From: kav062 at yahoo.com (Kannan Vijayan) Date: 14 Jun 2004 08:27:41 -0700 Subject: Unix fold command in python References: <70efe2ee.0406140252.2c7b0989@posting.google.com> Message-ID: diabolik at uku.co.uk (dean) wrote in message news:<70efe2ee.0406140252.2c7b0989 at posting.google.com>... > Hello Group: > > Hopefully someone can answer my question. > > I have a unix shell command that I would like to emulate in python. > The command is FOLD. I am scanning a file that contains a stream of > data with a record size of 242 bytes but no record delimiters. There > are multiple fields in each record that can be mapped according to > their position: > > example > > field1 byte 0-4 > field2 byte 5-8 > ... > ... > ... > fieldn byte 238-242 > > > How do I make python read a record in and report the contents of a > particular field (and may be carry out an operations with that field). > > Much appreciated > > regards > dean Is the data in some packed binary format? It seems from your description that this is the case. I would consider looking at the struct module. Read the docs on it to find out specifics of usage. -kannan From sholden at holdenweb.com Thu Jun 3 22:27:16 2004 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 03 Jun 2004 22:27:16 -0400 Subject: View Talks - Buy 'Zen of Python' Tshirt - Free with PyCON by 17th In-Reply-To: References: Message-ID: Mark Jackson wrote: > Steve Holden writes: > > >>We are also taking orders for extra shirts, including shipping to those >>that cannot attend. Please email zope at toenjes.com to reserve your >>shirts. All requests must be received by March 19. > > > Did this ever happen? Last ftom zope at toenjes.com was ". . .by the end > of the month"; that was in mid-April, and now there's no response at > all. . . . > I'll see if I can find out and get back to the list. regards Steve From sdahlbacSPAMSUCKS at abo.fi Sun Jun 20 19:08:59 2004 From: sdahlbacSPAMSUCKS at abo.fi (Simon Dahlbacka) Date: Mon, 21 Jun 2004 02:08:59 +0300 Subject: Graph API / framework In-Reply-To: <40d4729e$1@rutgers.edu> References: <40d4729e$1@rutgers.edu> Message-ID: <40d61930$1@newsflash.abo.fi> George Sakkis wrote: > Does anyone know of a good graph API ? The only one I found for Python is > part of kjbuckets > (http://starship.python.net/crew/aaron_watters/kjbuckets/kjbuckets.html), > but I was looking for something more sophisticated; I am more concerned > about elegance and extensibility than top performance. JUNG > (http://jung.sourceforge.net/doc/manual.html) for java looks more promising. > Does anyone have experience with it or some other relevant framework ? > Thanks, > > George > > is something like pydot (http://dkbza.org/pydot.html) what you are looking for? Bindings for the dot tool from the grapviz package (http://www.research.att.com/sw/tools/graphviz/) /Simon From tdelaney at avaya.com Tue Jun 15 22:32:43 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 16 Jun 2004 12:32:43 +1000 Subject: Looking for a different version of sort Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01963B22@au3010avexu1.global.avaya.com> Brian McGonigle wrote: > I'm a Perl programmer learning Python (up to chapter 7 in Learning > Python, so go easy on me :-) and I find that I look to do things in > Python the way I would do them in Perl. In Perl functions and methods > usually only return and undefined value in the event of an error, make > an endless number of compound statements possible. Is there a version > of sort() I could import from somewhere that returns a reference to > the object on which it was performed, rather than returning "None". Python 2.4 includes `sorted` as a builtin which makes a copy of the iterable passed, sorts it and returns it. There is no function available which sorts in-place and returns a reference to the list sorted, but it's very simple to write a function to do it ... def inplace_sort (l): l.sort() return l Tim Delaney From harry.g.george at boeing.com Tue Jun 22 10:08:59 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 22 Jun 2004 14:08:59 GMT Subject: plot dates, print plotted data References: Message-ID: "Evagelia Tsiligianni" writes: > Hello! > > I am trying to find a tool that can plot and print (plotted) data. I need it supports plotting dates as well. > I 've tried wxPlot and chaco but each of them applies one of my requests either printing or date plotting. Can anybody help? > > Thanks > Evagelia I'm not sure just what you mean by plotting dates, but take a look at gnuplot and its python binding gnuplot.py: http://sourceforge.net/projects/gnuplot/ http://gnuplot-py.sourceforge.net -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From miki.tebeka at zoran.com Wed Jun 2 10:25:19 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 2 Jun 2004 16:25:19 +0200 Subject: Is this just for readability to the developer? python In-Reply-To: References: Message-ID: <20040602142519.GJ612@zoran.com> Hello David, > initModule( "$Revision: 3.1 $".split(" ")[1] ) > ... > In this example, it looks like only the '3.1' is actually passed to the > function. Which leads me to speculate that the rest of it is just there to > make it easier for the developer when looking at source code to see what > version of the module is being used. > > The only thing I think i notice is its also passing a list of one element? > > Is this a typical way to do this in python? The $Revision: ...$ is expaned by CVS/Subversion/... when you check in a file (These are called "RCS keywords", see http://computing.ee.ethz.ch/sepp/cvs-1.11.5-ds/cvsbook/main_162.html#SEC192). This way the revision is actually maintined by the source control system. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From j_mckitrick at bigfoot.com Thu Jun 17 20:42:40 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 17 Jun 2004 17:42:40 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: You guys are WAY over my head, and I'm supposed to be a C.S. junior! :-\ Could someone give me an idea of what metaclasses and decorators _are_? I think metaclasses are classes with their base methods overridden, correct? And decorators are a form of delegation, right? If so, where am I wrong? And how do these techniques make for better code/coding? jonathon From della at toglimi.linux.it Thu Jun 17 13:31:19 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 17 Jun 2004 17:31:19 GMT Subject: list to dict In-Reply-To: References: Message-ID: Denis S. Otkidach wrote: > On Wed, 16 Jun 2004, Yermat wrote: > Y> >>> dict([(1,'a'),(2,'b')]) > Y> {1: 'a', 2: 'b'} > Y> > Y> list of tuples -> dict ! > > But unfortunately list({1: 'a', 2: 'b'}) -> [1, 2]. That's because it's coherent with what happens with iter(lst), I think. Anyway, {1: 'a', 2: 'b'}.items() -> [(1, 'a'), (2, 'b')]. -- Ciao, Matteo From davidf at sjsoft.com Tue Jun 1 08:57:56 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Jun 2004 14:57:56 +0200 Subject: OT: Cryptography puzzle In-Reply-To: References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: Christian Gudrian wrote: > "A.M. Kuchling" schrieb: > > >>and the >>doubled 'dd' letters are probably 'ss' or 'll'. > > > And what about the 'ss' in 'ssfd'? I don't know many languages that allow > words to start with two identical letters. So either the encryption is a > little more advanced than to just replace characters -- or it's a Scottish > text. ;) How eerie :-) import sys for line in sys.stdin: if len(line) > 2 and line[0] == line[1]: sys.stdout.write(line) on standard English dictionary: eel eelgrass eels eerie eerily ooze oozed And say, Afrikaans, has a few more: [root at scir Python]# ./dd.py < af/wordlist.iso-8859-1 | wc -l 3770 From cbrown at metservice.com Fri Jun 4 01:53:57 2004 From: cbrown at metservice.com (Colin Brown) Date: Fri, 4 Jun 2004 17:53:57 +1200 Subject: httplib and proxies References: <6ee58e07.0406031250.1b36a113@posting.google.com> Message-ID: <40c00d7a$1@news.iconz.co.nz> "Lothar Scholz" wrote in message news:6ee58e07.0406031250.1b36a113 at posting.google.com... > Hello, > > is it possible to get a webpage with httplib (or any other python > library) through a proxy server ? Can't find anything about this in > the documentation. If you use urllib, you might want to try adding an empty dictionary: proxies={} to your urllib.urlopen. This enabled us to get past a Windows proxy server. Colin Brown PyNZ From guy at NOSPAM.r-e-d.co.nz Tue Jun 8 17:10:51 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Wed, 09 Jun 2004 09:10:51 +1200 Subject: Error checking using regex ? In-Reply-To: <16pxc.57587$mQ4.15957@fe2.texas.rr.com> References: <16pxc.57587$mQ4.15957@fe2.texas.rr.com> Message-ID: Hi Paul, Yep your examples :-) I'm using this as a learning experience and have looked at your code but I have specific requirements for integration into another application. I'm using the regex to create a list of tokens to be processed into a postfix processing string. This is then offloaded to another class that processes the string for each database row. The speed to generate the postffix string isn't important. But the speed to process for each database row is. Guy > "Guy Robinson" wrote in message > news:ca47pc$e11$1 at lust.ihug.co.nz... > >>I have the code below which parses an expression string and creates > > tokens. > >>Can anyone suggest the best of error checking for things like: >> >>Valid variable only obj.attribute -whitespace allowed >> >>test( "ff*2/dd.r..ss r") #additional ..ss -invalid variable. >>test( "ff*$24..55/ddr") #double .. and $ -invalid number >>test( "ff*2/dd.r.ss r") #variable with double . -invalid variable >> >>I can't see an efficient way of doing this so any suggestions appreciated. >> >>TIA, >> >>Guy >> > > > > Guy - > > Well, I recognize the test cases from an example that I include with > pyparsing. Are you trying to add support for variables to that example? If > so, here is the example, modified to support assignments to variables. > > -- Paul > > ============================ > # minimath.py (formerly fourfn.py) > # > # Demonstration of the parsing module, implementing a simple 4-function > expression parser, > # with support for scientific notation, and symbols for e and pi. > # Extended to add exponentiation and simple built-in functions. > # Extended to add variable assignment, storage, and evaluation, and > Python-like comments. > # > # Copyright 2003,2004 by Paul McGuire > # > from pyparsing import > Literal,CaselessLiteral,Word,Combine,Group,Optional,ZeroOrMore,OneOrMore,For > ward,nums,alphas,restOfLine,delimitedList > import math > > variables = {} > exprStack = [] > > def pushFirst( str, loc, toks ): > global exprStack > if toks: > exprStack.append( toks[0] ) > return toks > > def assignVar( str, loc, toks ): > global exprStack > global variables > variables[ toks[0] ] = evaluateStack( exprStack ) > pushFirst(str,loc,toks) > > > bnf = None > def BNF(): > global bnf > if not bnf: > point = Literal( "." ) > e = CaselessLiteral( "E" ) > fnumber = Combine( Word( "+-"+nums, nums ) + > Optional( point + Optional( Word( nums ) ) ) + > Optional( e + Word( "+-"+nums, nums ) ) ) > ident = Word(alphas, alphas+nums+"_$") > varident = delimitedList(ident,".",combine=True) > > plus = Literal( "+" ) > minus = Literal( "-" ) > mult = Literal( "*" ) > div = Literal( "/" ) > lpar = Literal( "(" ).suppress() > rpar = Literal( ")" ).suppress() > addop = plus | minus > multop = mult | div > expop = Literal( "^" ) > pi = CaselessLiteral( "PI" ) > > expr = Forward() > atom = ( pi | e | fnumber | ident + lpar + expr + rpar | > varident ).setParseAction( pushFirst ) | ( lpar + expr.suppress() + rpar ) > factor = atom + ZeroOrMore( ( expop + expr ).setParseAction( > pushFirst ) ) > term = factor + ZeroOrMore( ( multop + factor ).setParseAction( > pushFirst ) ) > expr << term + ZeroOrMore( ( addop + term ).setParseAction( > pushFirst ) ) > assignment = (varident + "=" + expr).setParseAction( assignVar ) > > bnf = Optional( assignment | expr ) > > comment = "#" + restOfLine > bnf.ignore(comment) > > return bnf > > # map operator symbols to corresponding arithmetic operations > opn = { "+" : ( lambda a,b: a + b ), > "-" : ( lambda a,b: a - b ), > "*" : ( lambda a,b: a * b ), > "/" : ( lambda a,b: a / b ), > "^" : ( lambda a,b: a ** b ) } > fn = { "sin" : math.sin, > "cos" : math.cos, > "tan" : math.tan, > "abs" : abs, > "trunc" : ( lambda a: int(a) ), > "round" : ( lambda a: int(a+0.5) ), > "sgn" : ( lambda a: ( (a<0 and -1) or (a>0 and 1) or 0 ) ) } > def evaluateStack( s ): > global variables > if not s: return 0.0 > op = s.pop() > if op in "+-*/^": > op2 = evaluateStack( s ) > op1 = evaluateStack( s ) > return opn[op]( op1, op2 ) > elif op == "PI": > return 3.1415926535 > elif op == "E": > return 2.718281828 > elif op[0].isalpha(): > if op in variables: > return variables[op] > fnarg = evaluateStack( s ) > return (fn[op])( fnarg ) > else: > return float( op ) > > if __name__ == "__main__": > > def test( str ): > global exprStack > exprStack = [] > results = BNF().parseString( str ) > print str, "->", results, "=>", exprStack, "=", evaluateStack( > exprStack ) > > test( "9" ) > test( "9 + 3 + 6" ) > test( "9 + 3 / 11" ) > test( "(9 + 3)" ) > test( "(9+3) / 11" ) > test( "9 - 12 - 6" ) > test( "9 - (12 - 6)" ) > test( "2*3.14159" ) > test( "3.1415926535*3.1415926535 / 10" ) > test( "PI * PI / 10" ) > test( "PI*PI/10" ) > test( "PI^2" ) > test( "6.02E23 * 8.048" ) > test( "e / 3" ) > test( "sin(PI/2)" ) > test( "trunc(E)" ) > test( "E^PI" ) > test( "2^3^2" ) > test( "2^9" ) > test( "sgn(-2)" ) > test( "sgn(0)" ) > test( "sgn(0.1)" ) > test( "5*4+300/(5-2)*(6+4)+4" ) > test( "((5*4+301)/(5-2))*(6+4)+4" ) > test( "(321/3)*10+4" ) > test( "# nothing but comments" ) > test( "a = 2^10" ) > test( "a^0.1 # same as 10th root of 1024" ) > test( "c = a" ) > test( "b=a" ) > test( "b-c" ) > > From martin at v.loewis.de Sun Jun 13 14:22:35 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 20:22:35 +0200 Subject: does python have useless destructors? In-Reply-To: <40CC5CA6.2050605@abo.fi> References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <40CC5CA6.2050605@abo.fi> Message-ID: <40CC9B6B.3010401@v.loewis.de> Marcus Alanen wrote: >> myfile = file("myfilepath", "w") >> try: >> myfile.write(reallybigbuffer) >> finally: >> myfile.close() > > > Does anybody know when "myfile" is created if it hasn't been introduced > previously? I.e. is Python guaranteed to create the variable, call the > function, then assign, or call the function, create variable, then > assign? Neither, nor. Creation of the variable and assigning to it is an atomic action for a global variable. Local variables are created when the function starts. > In the latter case, we (at least technically) have a very small > chance that the creation of the variable fails, for some reason or the > other. In the example, the chance is very high that the variable does not get set, i.e. if open() fails with an exception. It *might* be that the assignment fails because it runs out of memory. In either case, Python raises an exception, and subsequent statements are not executed. Regards, Martin From noway at nohow.com Sat Jun 26 20:04:54 2004 From: noway at nohow.com (Paul M) Date: Sun, 27 Jun 2004 00:04:54 GMT Subject: MySQL error from Python Message-ID: I encountered the following error when trying to perform a SQL UPDATE to a MySQL database table from Python. I would apprciate any assistance. In the Python code I have tried integer and decimal format specifiers in addition to the string specifier and nothing worked. Traceback (most recent call last): File "e:\my_python_scripts\commercecraft.py", line 36, in ? cursor.execute ("UPDATE product SET price = '%s' WHERE competitorID=1 AND sku = '%s'",(myprice,mysku)) File "E:\Python22\Lib\site-packages\MySQLdb\cursors.py", line 95, in execute return self._execute(query, args) File "E:\Python22\Lib\site-packages\MySQLdb\cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "E:\Python22\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax. Check the manual that cor responds to your MySQL server version for the right syntax to use near '139.80'' WHERE competitorID=1 AND sk u = ''50300288''' at line 1") Describe product; Field Type Null Key Default Extra ------------ ------------ ------ ------ ------- -------------- productID int(11) PRI (NULL) auto_increment sku varchar(50) YES (NULL) description varchar(60) YES (NULL) price decimal(7,2) YES (NULL) scrape_date datetime YES (NULL) competitorID int(11) YES (NULL) ************************************************************** import test_iopus import MySQLdb import sys import string try: conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "xyz", db = "commerce") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) cursor = conn.cursor() cursor.execute ("SELECT sku FROM product WHERE competitorID=1") while (1): row = cursor.fetchone () if row == None: break mysku = row[0] print mysku print "%d rows were returned" % cursor.rowcount result = test_iopus.Scrape(mysku) price = result.split(" ") tmpprice = str(price[0]) conversion = string.maketrans("$"," ") myprice = tmpprice.translate(conversion) print myprice cursor.execute ("UPDATE product SET price = '%s' WHERE competitorID=1 AND sku = '%s'",(myprice,mysku)) cursor.close() conn.close() From mariano.df at tin.it Fri Jun 11 09:15:54 2004 From: mariano.df at tin.it (Mariano) Date: 11 Jun 2004 06:15:54 -0700 Subject: property file Message-ID: Hi Have someone any idea how create/read a property file as java property file? If not, is there some other solutions? Thank's in advance From imbosol at aerojockey.invalid Mon Jun 14 18:09:54 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 14 Jun 2004 22:09:54 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <9hdzc.93679$DG4.801@fe2.columbus.rr.com> <10cr9m1q7tlp4b4@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article <9hdzc.93679$DG4.801 at fe2.columbus.rr.com>, > Carl Banks wrote: > . > . > . >>(Since when does Perl have an interactive interpretter?) > . > . > . > Long time http://phaseit.net/claird/comp.lang.perl.misc/perl_interactive.html >. Heh. It seems to me that, by the same reasoning, we could claim that Python has verbose execution. Someone's obviously willing to give Perl the benefit of the doubt here, but not Python. I smell shenanigans. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From nopsoft at poczta.onet.pl Thu Jun 24 09:59:07 2004 From: nopsoft at poczta.onet.pl (Janusz U.) Date: Thu, 24 Jun 2004 15:59:07 +0200 Subject: z80 vs Python References: Message-ID: > I wouldn't recommend this. The standard Python interpreter is quite hefty > (>700K dynamically linked), not to mention the standard libraries. Seeing > as Z80 has only 64K address space, I don't see a full implementation as > possible. I know. Sorry, I didn't precise. I thought exactly about eZ80F91 - it's based on Z80 but much more expanded... I will start on the module (and deviloper kit) for that procesor. It would be independent platform for tests software in the Python. > What you /could/ do would be to implement a (very) small subset of Python; > i.e. leave out generators, new-style class, list comprehensions, ability > to override built-in types, functions, and operators, and most of the > standard library, then you /might/ be able to fit a language with Pythonic > syntax in that address space. I think to expand language by own library for Python - eg. control GPIO of eZ80, read > > Another issue would be speed. Z80s, though they've gotten faster over the > years, still only run at speeds on the order of 10MHz. You might be better > off writing a Z80 compiler for a Python-esque language -- this would save > both speed and memory. speed 50MHz (or 20MHz in F92, F93...) > > If you can pick a different chip, go with something like a StrongARM. > These have the power and address space necessary for Python. Plus, it's > been done before (Python runs beautifully on modern PDAs). I have just bought the developer kit for eZ80 so I have limited way. I'd be happy to run Python on eZ80 platform. thx Janusz U. > If you stick with the Z80 though, you've got quite a challenge ahead of > you - good luck! If you succeed, you'll be sure to make hackers of Game > Boys, TI-83s, and TRS-80s everywhere deliriously happy. > From rigga at hasnomail.com Sat Jun 19 02:06:23 2004 From: rigga at hasnomail.com (RiGGa) Date: Sat, 19 Jun 2004 07:06:23 +0100 Subject: Remove spaces and line wraps from html? References: <5MHAc.16619$NK4.2886117@stones.force9.net> Message-ID: <6JQAc.16709$NK4.2922044@stones.force9.net> Paramjit Oberoi wrote: >>> http://groups.google.com/groups?q=HTMLPrinter&hl=en&lr=&ie=UTF-8&c2coff=1&selm=pan.2004.03.27.22.05.55.38448240hotmail.com&rnum=1 >>> >>> (or search c.l.p for "HTMLPrinter") >> >> Thanks, I forgot to mention I am new to Python so I dont yet know how to >> use that example :( > > Python has a HTMLParser module in the standard library: > > http://www.python.org/doc/lib/module-HTMLParser.html > http://www.python.org/doc/lib/htmlparser-example.html > > It looks complicated if you are new to all this, but it's fairly simple > really. Using it is much better than dealing with HTML syntax yourself. > > A small example: > > -------------------------------------------------- > from HTMLParser import HTMLParser > > class MyHTMLParser(HTMLParser): > def handle_starttag(self, tag, attrs): > print "Encountered the beginning of a %s tag" % tag > def handle_endtag(self, tag): > print "Encountered the end of a %s tag" % tag > > my_parser=MyHTMLParser() > > html_data = """ > > > hi > > hi > > """ > > my_parser.feed(html_data) > -------------------------------------------------- > > will produce the result: > Encountered the beginning of a html tag > Encountered the beginning of a head tag > Encountered the beginning of a title tag > Encountered the end of a title tag > Encountered the end of a head tag > Encountered the beginning of a body tag > Encountered the end of a body tag > Encountered the end of a html tag > > You'll be able to figure out the rest using the > documentation and some experimentation. > > HTH, > -param Thank you!! that was just the kind of help I was looking for. Best regards Rigga From dyoo at hkn.eecs.berkeley.edu Mon Jun 21 18:09:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 21 Jun 2004 22:09:27 +0000 (UTC) Subject: Except MySQL error References: Message-ID: Florian Lindner wrote: : I want to except the error which is raised in MySQLdb module when one is : trying to insert a value in a primary key column which already exists. But : I don't know which error to except... Hi Florian, According to the Python Database API: http://www.python.org/peps/pep-0249.html you can expect a subclass of IntegrityError. Hope this helps! From olli at haluter.fromme.com Fri Jun 25 08:19:58 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 25 Jun 2004 12:19:58 GMT Subject: Retrieve FTP directory with hidden files References: Message-ID: <2k2jjeF174gorU2@uni-berlin.de> Lothar Scholz wrote: > I use the standard ftplib.FTP class and get the listing wia > ftp.retrlines('LIST mydir') > but this does not get hidden files like ".htaccess" This should work: ftp.voidcmd("CWD mydir") ftp.retrlines("LIST -a") But of course you're at the mercy of the FTP server -- if it insists on not returning "hidden" files to you, there's nothing you can do about it. > and more important > i can't delete directories because they are not empty. Correct. You have to delete the files in them first. The FTP protocol (RFC959) does not specify recursive removal of directories, as far as I remember. Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From peter at engcorp.com Wed Jun 9 14:04:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 14:04:01 -0400 Subject: Creating True Global Functions by Modifying Builtins In-Reply-To: <889cbba0.0406090951.32a6434b@posting.google.com> References: <889cbba0.0406090951.32a6434b@posting.google.com> Message-ID: <45adnQYny6eOzFrdRVn-sw@powergate.ca> Kamilche wrote: > I really, really want a handful of 'true' global functions, ones that > can be called from anywhere without requiring importing. No, you don't. ;-) Really, why bother when with a simple "import kamilche_tools" (or whatever you want), you can get access to all your stuff without hiding it from everyone, thereby making maintenance much harder? The only time I've found a valid reason to stick stuff in __builtin__ is when trying to make current code *forward compatible* with newer versions of Python, such as when bool() and True/False where added in 2.2 (?) and we had to stick with 2.0. Any other use smells of "slick" programming and is likely to bite you in the future. > So I added it to the 'builtins' of Python, and it appeared to work. :-O The name __builtins__ is apparently an implementation detail. If that's true, you don't want to use it. Instead, if you really must, at least "import __builtin__" (note, no "s" on the end) and use that module. -Peter From me at privacy.net Thu Jun 10 04:13:44 2004 From: me at privacy.net (Duncan Booth) Date: 10 Jun 2004 08:13:44 GMT Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: hanzspam at yahoo.com.au (Hannu Kankaanp??) wrote in news:840592e1.0406092318.532f475a at posting.google.com: > I'd very much prefer something simpler that leaves no room > for errors, e.g. > > with myfile = file("myfilepath", "w"): > myfile.write(reallybigbuffer) > > (this, and more generic solutions with code blocks have been > suggested here many times) > One of the downsides to this form is that when you are working with several variables that need finalising you end up nested quite deep. Apparently the next release of Microsoft's C++ for managed environments will handle the issue in quite a nice way. They will let you declare managed heap based objects as though they are on the stack, and if the object supports their dispose pattern the compiler automatically inserts the required try..finally block. Python might need an extra keyword, but perhaps it could benefit from something similar. e.g. def f(filename): dispose infile, outfile infile = file(filename, "r") outfile = file(filename+".out", "w") outfile.write(infile.read()) would be equivalent to something like: def f(filename): try: infile = file(filename, "r") outfile = file(filename+".out", "w") outfile.write(infile.read()) finally: _inexception = sys.exc_info()[0] is not None for _temp in ['outfile', 'infile']: if _temp in locals(): try: locals()[_temp].__dispose__() except: pass if not _inexception and sys.exc_info()[0] is not None: raise Obviously the keyword might be something other than dispose, and the method called to dispose of the object might have a different name. Plus I'm not sure I got the logic right on what the equivalent code should be (which I think is an argument *for* a scheme such as this). It should be ignoring variables which aren't yet set, and preserving the original exception if there is one, but if any __dispose__ throws an exception that should be propogated while not preventing all other __dispose__ methods also being called. From donn at u.washington.edu Tue Jun 29 20:01:36 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 29 Jun 2004 17:01:36 -0700 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: In article , Heiko Wundram wrote: > The operations on the host don't fail if the timeout has expired, in my use > case. It's just that a host has a timeout, which signals the surrounding > code, that this host needs to be contacted in the next run of ping signals. > > What I can do to get these hosts now looks like the following: > > ping_hosts = [h for h in hosts if not h] > > That's what I call nice and concise, and at least for me the meaning is clear > by just looking at the code. If the host has expired (not host), add it to > the list of hosts to ping now. ... > I can understand that in the normal case you would want to code something > either as a sequence, or as a non-sequence. But, in this case, you have two > classes, which have different use cases, but are derived from another (and > deriving a Host from an ID isn't strange, at least for me). And for code > which does something with the ID (and is specifically marked as such), it's > pretty fair to use the ID part of the class which is passed in (which in this > case are __len__ and __xor__) to make it concise, while where you use hosts, > you take the host protocol to get at the host data (__nonzero__). > > I don't see anything unintuitive in this... Actually, it makes the code look > cleaner, IMHO. It's the __nonzero__ part that hurts. Insofar as you have explained it, an expired() method would be much clearer than __nonzero__(), and it would make more sense. e.g., ping_hosts = [h for h in hosts if h.expired()] This approach lets you have more than one boolean attribute, because they can each have their own name. Donn Cave, donn at u.washington.edu From tmohr at s.netic.de Mon Jun 7 16:28:06 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 07 Jun 2004 22:28:06 +0200 Subject: tp_getattrfunc, access members that are a list Message-ID: Hi, in the documentation and the examples that describe how to make the members of a new type accessible it says that i need to use the getattrfunc and setattrfunc if i want to access members that are an array. typedef struct { PyObject_HEAD unsigned char d[8]; } pmod_obj; Sadly i did not find any example on how to do this. Can anybody describe me how i can access the array d[8] as a list? I'd like to get AND set values in there. Thanks for any hints, Torsten. From none at none.net Thu Jun 17 11:02:56 2004 From: none at none.net (Iwan van der Kleyn) Date: Thu, 17 Jun 2004 17:02:56 +0200 Subject: Bug in psyco ? In-Reply-To: <40d09f77$1@rutgers.edu> References: <40d09f77$1@rutgers.edu> Message-ID: <40D1B2A0.30304@none.net> George Sakkis wrote: >>>>import inspect >>>>inspect.stack() > > [(, '', 1, '?', None, None)] > >>>>import psyco >>>>inspect.stack() > > Traceback (most recent call last): > TypeError: arg is not a frame or traceback object Inspect is too rigid. It crashed because it cannot handle Psyco's emulated frame object. Ie: it's a feature.... http://psyco.sourceforge.net/psycoguide/bugs.html "...Frame objects are emulated. The sys. getframe function returns an instance of a custom class which emulates the standard frame objects? behavior as much as possible..." Regards, Iwan From claird at lairds.com Fri Jun 4 10:42:24 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 04 Jun 2004 14:42:24 -0000 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> Message-ID: <10c12igm2nsl4e9@corp.supernews.com> In article , Jacek Generowicz wrote: >claird at lairds.com (Cameron Laird) writes: > >> Critcl > >I'm not having much luck with google on this one. . You're perhaps more familiar with Perl's Inline::. -- Cameron Laird Business: http://www.Phaseit.net From pete at shinners.org Wed Jun 23 02:39:17 2004 From: pete at shinners.org (Pete Shinners) Date: Tue, 22 Jun 2004 23:39:17 -0700 Subject: Newstyle Types Confounding! Message-ID: I've been spending the last few night upgrading some 'classic' type objects to the more modern 'newstyle' types. Unless I am not finding some important page, this entire process is almost entirely undocumented. I've found the "Noddy" example, which was a helping start. But Noddy only gets you halfway there, and where it leaves off there is no further assistance. I've been using the builtin Python types source as example, but this isn't answering most of my larger problems. Especially as the builtin types seem inconsistent in how they do thing. I have a few questions and am hoping to get a little guidance from those who understand this process better. First, I have found no comfortable way to create new type instances from the C api. My types are wrappers for existing C structures. Originally my code called PyObject_New and filled out the structure data. This appears to be invalid with newstyle types, but I cannot discover the new method. It appears there is no standard since all the builtin types do this differently. I've ended up with something like this.. self = (PyMineObject*)PyMine_Type.tp_new(&PyMine_Type, NULL, NULL); Can this be serious? This is the first time I've ever had to dig into the big Type structure to access function pointers. I find this to be disturbing, but I can learn to accept it if someone confirms this is the way to allocate newstyle type instances. My second problem has to do with weakrefs. Again I cannot locate actual documentation on this, and the Noddy example ends before discussing weakrefs. I've created the PyObject* weakreflist in my structure, set the offset in tp_weaklistoffset, and initialized it to NULL. It took many hours to figure out how this all works, mainly referring to funcobject.c for examples. I believe I have this correct now, but I have a lot of unexplained crashes that i suspect have to do with the weakref list handling. My third question comes to creating types that are inherited from other types. I need the new subtype to add several of its own data fields to its own structure. There are no examples of this in the Python source, and there is no documentation referring to this. How can my new type instances access structure data from its base. My only solution so far is to duplicate all the structure members from the parent into the child? Then duplicate all the code from the parent into the child. At this point my child is actually a standalone type, except it refers to the parent in tp_base. Creating custom types in Python has become very difficult, if you intend to support all the recent features of Python. Adding some documentation and/or simple examples would go a long way towards a solution. I'm wondering if some thought should be put into simplifying the interface. Perhaps more macros and generic functions to help manage the new features. It shocks me to find nearly every single "PyXXX_FromXXX" implements object allocation in entirely independent ways, and none of the methods seem very clean to me. At this point I'm really shooting into the dark. I assume I'll have it right when things stop crashing. If I were to collect a narrowed, specific list of problem topics, would the documentation team be interested in looking? From dkturner at telkomsa.net Tue Jun 15 04:35:10 2004 From: dkturner at telkomsa.net (David Turner) Date: 15 Jun 2004 01:35:10 -0700 Subject: does python have useless destructors? References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > David Turner wrote: > > > >In fact, the RAII idiom is quite commonly used with heap-allocated > >objects. All that is required is a clear trail of ownership, which is > >generally not that difficult to achieve. > > Not really. What you're doing is what I'd call "virtual stack" by > virtue of the fact that the heap objects are being managed by stack > objects. > Having read this through a second time, I'm not sure that you understood the C++ code I posted. So here is an equivalent in Python: class File: def __init__(self, name): self.fh = open(name, "r") def __del__(self): self.fh.close() file_list = [] file_list.append(File(file_to_compile)) while len(file_list): f = file_list[len(file_list)-1] t = Token(f) if t == Token.EOF: file_list.pop() else: parse(t) No stack objects in sight, yet this code is semantically equivalent to the C++ code. Don't let red herrings like std::stack confuse you :-). Regards David Turner From mark at prothon.org Wed Jun 16 17:14:41 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 16 Jun 2004 14:14:41 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: <5L2Ac.26$u%3.13@fed1read04> Peter Hansen wrote: >> In Prothon: >> def foo(x): >> print foo.list.append!(x) >> foo.list = [] >> >> (Sorry. I couldn't resist bragging.) > > About what? > > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] > >>> def foo(x): > ... foo.list.append(x) > ... print foo.list > ... > >>> foo.list = [] > >>> foo('test') > ['test'] > > (Oh, did you mean bragging about how a hard-to-see exclamation > mark causes append() to return the sequence? I thought > maybe it was about the function attribute or something.) Actually, I didn't know if the function attribute assignment outside the function would work in Python or not. I guess I'll know better than to try to play one-upmanship with Python next time. I did say I was sorry :-) FYI: It's not that the exclamation mark causes append to return the sequence. The exclamation mark is always there and the sequence is always returned. The exclamation mark is the universal symbol for in-place modification. This is straight from Ruby and solves the problem that caused Guido to not allow sequences to be returned. And, yes, I do think that's worth bragging about ;-) From ivan at ivan-herman.net Sun Jun 13 10:26:33 2004 From: ivan at ivan-herman.net (Ivan Herman) Date: Sun, 13 Jun 2004 16:26:33 +0200 Subject: Good IDE for Python In-Reply-To: References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: <40cc6410$0$147$18b6e80@news.wanadoo.nl> I am also a jEdit user... can you give the URL of this plugin? Thank you Ivan Dominic wrote: > Kamilche wrote: > >> I love Python, but I'm less than in love with IDLE. It's OK, but it >> really doesn't have enough capabilities. >> >> What I consider critical, are a popdown listing of all my functions, >> colored syntax printing, and a right-click 'definition' context menu >> that will hop you to the spot where that keyword is defined, if >> possible. Everything else I could learn to do without, but these >> features keep me hoping for a better IDE for Python. >> >> I'm used to the Microsoft Visual C++ debugger, and though tooltip >> variable debugging and intellisense were nice, they broke often enough >> that you couldn't rely on them anyway, so I don't really need those >> features. >> >> I would also like the ability to create application 'forms' visually. >> I'm on a Windows XP machine. >> >> Any suggestions on what I should install next? > > Latest jEdit has support for a Python-plugin > which is able to parse Python and display > methods/classes in separate pane and it can > be used to access the Python shell and it has > support for debugging. :-) > Source editing and navigation is fine, though > debugging seems to need some more work. > This plugin is still in development. > The Tk based editors tend to get too slow > on my PIII 800 MHz on XP 128MB, the longer the app > runs and the bigger the source code amount gets... > > Ciao, > Dominic > From theoryboy at my-deja.com Tue Jun 22 05:56:16 2004 From: theoryboy at my-deja.com (Peter Saffrey) Date: 22 Jun 2004 02:56:16 -0700 Subject: "RuntimeError: Calling Tcl from different appartment" References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > Peter Saffrey wrote: > > No clue why it used to work. Why do you need to call Tk from multiple > threads? I'm writing an MP3 jukebox (don't laugh, it's just for fun). One thread controls the interface that shows the next few songs to be played and allows you to add to the list. The other thread plays the songs, removing them from the list in the process. To control this with one thread, I'd have to have the interface thread constantly listening for when the last song has finished so that it can remove it from the list and play the next one. Peter From simoninusa2001 at yahoo.co.uk Mon Jun 28 16:49:32 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 28 Jun 2004 13:49:32 -0700 Subject: wxPython woes References: Message-ID: <30260531.0406281249.6489c3ca@posting.google.com> km wrote: > I feel its a real pain to install wxPython from sources it goes back to install > gtk+ etc . may be thats why its not yet become defacto GUI standard for python. > but i'd like to know if anyone has made it easy with an installer for wxPython > on linux (Debian woody)? > > ps: i have tried installing wxPython with the .deb files availble in testing > and unstable section. it doesnt work - unable to load the module I seem to recall installing wxPython 2.4.24 on a friends LindowsOS box (a Debian-based abomination) and simply used something like "apt-get install wxgtk-2.4" and it went ahead quite easily, even installing Python 2.3.3 as one of the dependencies, I was very impressed, it was almost as easy as Windows! I do agree that getting wxPython installed is too much of a nightmare, mainly due to having to install wxWidgets and GTK+, but PyQt was probably more hassle..... Once you have 2.4 installed, 2.5 seemed easier to install (you already have GTK+ etc. sorted). The pre-packaged RPMs etc. just don't seem to work, you really have to compile from source. From tim.golden at tesco.net Thu Jun 24 16:02:28 2004 From: tim.golden at tesco.net (Tim Golden) Date: Thu, 24 Jun 2004 20:02:28 +0000 (UTC) Subject: networking with pyro In-Reply-To: References: Message-ID: > I'm working on a distributed application using Pyro, and I've come > across several issues I'm not really sure how to handle, since this is > my first distributed application. It's worth posting to the Pyro mailing list as well, if you haven't already. http://lists.sourceforge.net/lists/listinfo/pyro-core > My application consists of several servers supplying various > functions. They require a name server to be running first. How do I > make it run? Several options, but most simply: by using the scripts supplied into the distribution. > What if another application has already set up a pyro > name server (because if I use such a server it could be shut down > prematurely by the other application)? How do I prevent other pyro > applications from using my name server (etc.)? Again, several options. When setting up Pyro clients / servers, you can either specify a nameserver (in which case you can use yours, and others can use theirs) or you can simply broadcast for a nameserver -- probably on the same subnet, depending on what your network devices do with broadcast packets. Unless you have something very specific in mind, it probably doesn't matter whose nameserver you use: you can set up sub-groups within it so that your objects and other peoples' don't get confused. Additional info: you don't have to use a name server at all, if you don't want to. It's perfectly possible to connect directly to objects, if you know where they are. > How do I make all processes run at once, and die at once (and > gracefully)? Now that really depends on what you're doing. More info would help. > What is usually done when one of the processes has an exception and > dies? How do I make sure servers don't leave junk in the name server? Usually, by careful exception handling on the client and having an object which restarts clean up before itself. > My main concern is that I'm missing some general concept and I would > have to re-invent the wheel, so I'd appreciate any general comments or > supernal insights on the subject. You've doubtless read the Pyro docs, which I personally find very useful, so either read again to see if more understanding comes, or put together a small test scenario, try it out, and then ask questions on the Pyro list. HTH Tim From theller at python.net Wed Jun 9 03:39:37 2004 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jun 2004 09:39:37 +0200 Subject: pywin32 support for CreateTypeLib2 References: Message-ID: Philip Rittenhouse writes: > I was just wondering if there are any plans to support the > CreateTypeLib2 API either instead of, or in addition to, the > CreateTypeLib API. > > I am currently using pythoncom to generate type libraries, but > I ran into an issue supporting optional parameters. After a > lot of digging I discovered that the old CreateTypeLib API doesn't > support them. I have currently built a custom version of pywin32 > that uses the new CreateTypeLib2 API, and everything works great. > I'm hoping that the CreateTypeLib2 support can be added to the > official release. As Roger already said, upload a patch to the pywin32 project. OTOH, it should (hopefully!) been easier to do it with ctypes - I assume creating typelibs isn't that performance critical. Currently ctypes.com can use but not create typelibs: readtlb.py creates ctypes Python wrappers from type libraries - my plan it to also create typelibs from the Python wrappers. Thomas From donn at u.washington.edu Thu Jun 17 12:52:36 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 17 Jun 2004 09:52:36 -0700 Subject: does python have useless destructors? References: Message-ID: In article , dkturner at telkomsa.net (David Turner) wrote: > Marcin 'Qrczak' Kowalczyk wrote in message > news:... > > On Tue, 15 Jun 2004 11:26:33 -0700, Donn Cave wrote: > > > > > But never one to be deterred by pointlessness, > > > suppose __finalize__ were a flag, instead of a method. It > > > has two functions: 1. declare that the object's __del__ > > > method should be called when it's logically unreferenced - > > > either no references, or only referenced as part of a cycle > > > or traceback. 2. Serve as the extra reference count that's > > > needed for this, so __del__ will only be called once regardless > > > of further reference decrements, cycle analysis etc. > > > > I will repeat: it's unimplementable efficiently when > > Python runtime is hosted by a language with non-refcount GC. > > So are we to take it that efficiency considerations are a serious > impediment to a potentially valuable safety feature? Gross efficiency considerations in the Java implementation, specifically. Donn Cave, donn at u.washington.edu From klachemin at home.com Thu Jun 24 10:37:48 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 07:37:48 -0700 Subject: Python Color Printing References: <889cbba0.0406240136.3a735356@posting.google.com> <40daabc1$0$10280$afc38c87@news.easynet.co.uk> Message-ID: <889cbba0.0406240637.17b7c3e0@posting.google.com> Peter Hickman wrote in message news:<40daabc1$0$10280$afc38c87 at news.easynet.co.uk>... > There is a GNU tool called source-highlight that handles python. It will create > a html file with the colour coding. You could then print the html file. Thanks, I've got one of those. But then, how do I handle adding headers, footers, changing the window title to get rid of 'Microsoft Internet Explorer', and automatically printing? That's the part where it falls down on. If someone knew how to do that via Python, that'd work! :-) --Kamilche From klachemin at home.com Thu Jun 24 05:36:20 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 02:36:20 -0700 Subject: Python Color Printing Message-ID: <889cbba0.0406240136.3a735356@posting.google.com> I'm pretty desperate to get color syntax printing. I just tried out the evaluation version of 'Komodo', which several people in here suggested, and its print features are terrible. The text is coming out huge when I print at 8 point, tiny when I'm printing at 14 point (so tiny that it looks like subscripts), the margins are reset at random, and so on. Plus it doesn't recognize all my fonts. I don't care if the pretty printer is in an IDE. I just want color printing with headers and footers! And I wanted it automated - I don't want to have to print each one by hand, I want to start them all printing and walk away. It has to be able to print in larger fonts reliably, because 10 point is too small for my computer-weary eyes. Does anyone have any suggestions? --Kamilche From dkturner at telkomsa.net Tue Jun 22 05:36:24 2004 From: dkturner at telkomsa.net (David Turner) Date: 22 Jun 2004 02:36:24 -0700 Subject: useless destructors Message-ID: Further to the discussion from earlier titled "does python have useless destructors?", I've posted a brief summary of garbage collection, RAII, and the "using" clause (which is what PEP310's "with" clause amounts to). The post is here: http://dkturner.blogspot.com/2004/06/garbage-collection-raii-and-using.html Regards David Turner From chuck.amadi at ntlworld.com Wed Jun 23 02:33:02 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Wed, 23 Jun 2004 07:33:02 +0100 Subject: get screen output to file using get_payload() Message-ID: <40D9241E.7010005@ntlworld.com> Hi I have managed to print the output of the get_payload to screen but I need to write to a file as I only require the email body messages from the mailbox.My script using the fp.readlines() function writes the entire contents of the mailbox of cause including the headers of the emails I do not want. I have tried a few things but I cant get to my goal.Any ideas or pointers I need only the email body and I cant figute out why I can using the print statement but get those results to a file. cheers import sys import os import email import mailbox import StringIO fp = file ("/var/spool/mail/chucka") mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() mailout = file("/home/chucka/pythonScript/SurveyResults1.txt","r") fp = open("/var/spool/mail/chucka") mb = mailbox.UnixMailbox(fp, email.message_from_file) #for bdymsg in fp.xreadlines(): #for bdymsg in fp.readlines(): #for msgbodies in mb: # mailout.write(bdymsg) # bdymsg = mail.get_payload() # mailout.write(mail.get_payload() for bmsg in mb: bmsg = get_payload() mailout.write(bmsg) # bmsg = [get_payload] print "mailbox file copied...to SurveyResults.txt" # Now close the files mailout.close() From edcjones at erols.com Sat Jun 19 07:57:42 2004 From: edcjones at erols.com (Edward C. Jones) Date: Sat, 19 Jun 2004 07:57:42 -0400 Subject: Help needed: optimizing dictionary creation/access In-Reply-To: <40d3e9fa$0$603$39db0f71@news.song.fi> References: <40d3e9fa$0$603$39db0f71@news.song.fi> Message-ID: <40d42b7e$0$3010$61fed72c@news.rcn.com> Pekka Niiranen wrote: > Hi there, > > I have tree-like dictionary > > data = {p_name: {p_keyp: {p_cost: [p_unit, t]}}} Try "http://members.tripod.com/~edcjones/MultiDict.py". From grante at visi.com Wed Jun 2 20:34:56 2004 From: grante at visi.com (Grant Edwards) Date: 03 Jun 2004 00:34:56 GMT Subject: Why did no one invent Python before? References: Message-ID: On 2004-06-02, Russell E. Owen wrote: >>Seriously, why is a language like this only NOW appearing? And >>aside from the interpreter, because while it is nice, it's not >>the main forte' of the language, IMHO. > > I think smalltalk users would argue that it was done many years ago. It > looks a bit odd at first to C programmers, but is easy to learn and has > most of the strengths of python: > - interpreted > - automatic garbage collection > - simple and clean > - powerful > - rich set of collection types > - rich set of libraries > > There are a few important differences: > - much worse for scripting > - built in GUI > - much better development environment; you really don't know what you're > missing until you've used smalltalk's browsers, inspectors and > debuggers. It's the main thing I really, really miss in python. The big difference between Smalltalk (back then) and Python (now) is the price of admission -- both financially and mentally. Smalltalk was an amazingly cool system, but I don't remember any usable free Smalltalk systems until recently. I think I paid several hundred USD for the "entry" level version of Smalltalk for a '286 about 15 years back. Add-on libraries weren't free, and had to be purchased separately. It was cool, but it didn't integrate with _anything_. It was a world unto itself. You launched it from DOS, and it completely took over the machine. Smalltalk was the OS. You couldn't ease into Smalltalk the way you can with Python. You jumped into the deep end and either swam or drowned. With python, you can get your feet wet by wading around in the shallows and gradually learn to swim as you have the time and inclination. -- Grant Edwards grante Yow! A dwarf is passing at out somewhere in Detroit! visi.com From nadav at noip.com Fri Jun 18 09:03:59 2004 From: nadav at noip.com (Nadav) Date: Fri, 18 Jun 2004 16:03:59 +0300 Subject: Sharing access to ComObject between interpreters Message-ID: Hi, I have two interpreters in my programs. It is safe to give them access to the same PyObject representing a dispatched COM interface? Thanks, Nadav From __peter__ at web.de Fri Jun 25 06:51:42 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Jun 2004 12:51:42 +0200 Subject: Prevent pyc or pyo compiled output References: Message-ID: Jason Smith wrote: > Hi. I have exactly the problem described in PEP 304: I want to tell > python _not_ to write the .pyc bytecode versions of my modules. (During > development it clutters up my directories and 'svn st' output.) > > PEP 304 introduces a method to fix this, but I was wondering if there is > some sort of quick and/or dirty workaround for now. Maybe you can duplicate your package structure with symlinks to the *.py files. Then you need not care about the *.pyc put there (untested). Peter From peter at engcorp.com Wed Jun 23 00:50:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 00:50:39 -0400 Subject: Encryption with Python In-Reply-To: <889cbba0.0406221926.3f4e5776@posting.google.com> References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: Kamilche wrote: > I've looked at a few alternatives for encryption with Python, and > didn't come up anything very speedy. > > I've written an encryption algorithm in pure Python that can process > 22 megs of data a second. I know it's not secure, but it should be > enough to ward off casual hacking. Does someone know of something > speedier? In addition to Erik and Paul's comments: if you don't specify what machine you ran your benchmark on, the number "22MB/s" is completely meaningless... Besides, what you say is not possible. On my machine, which is about a P4 2500MHz, scanning an array.array('c') with 22MB of data in it, doing nothing but reading each byte and ignoring it, takes about 8 seconds. So does converting the array to a list, which is pretty much all C code. Strings are immutable, so you can't be working with one of them... Doing anything meaningful with real data, no matter how trivial the algorithm, would definitely take longer. -Peter From della at toglimi.linux.it Thu Jun 17 03:43:22 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 17 Jun 2004 07:43:22 GMT Subject: very large dictionaries In-Reply-To: <2jbm1vFvh88vU1@uni-berlin.de> References: <2jbm1vFvh88vU1@uni-berlin.de> Message-ID: William Park wrote: > Since you are talking about key/value record, you can choose from GDBM > (gdbm), Berkeley DB (dbhash), or disk-based dictionary front-end > (shelve). You can now access GDBM database from Bash shell. :-) If you just need fast lookup, maybe cdb (http://pilcrow.madison.wi.us/#pycdb) can be of use: two disk accesses per lookup. -- Ciao, Matteo From NAIGIMSESRIMAIL at gims.com Thu Jun 17 11:16:46 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 17 Jun 2004 17:16:46 +0200 Subject: ALERT - GroupShield ticket number OA52_1087485400_ESRIMAIL_1 was generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: 0gk500b4gd0888 at cougar.noc.ucla.edu <0gk500b4gd0888 at cougar.noc.ucla.edu> Sent: 1342077952,29643838 Subject: Document Attachment Details:- Attachment Name: Bill.zip File: Bill.zip Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Netsky.z at MM!zip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1889 bytes Desc: not available URL: From chris at misery.net Sun Jun 27 00:18:09 2004 From: chris at misery.net (chris) Date: Sun, 27 Jun 2004 04:18:09 GMT Subject: wxPython Tutorial Message-ID: <5UrDc.64745$Np3.3049166@ursa-nb00s0.nbnet.nb.ca> Anybody know of a good wxPython tutorial besides the one on the site? From reply.in.the.newsgroup at my.address.is.invalid Sun Jun 20 07:01:51 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 20 Jun 2004 13:01:51 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> Message-ID: <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> Daniel Ellison: >With Cheetah (for example) there is no real chance for the template to load >into an HTML editor for enhancement by a designer. This is a good point. ZPT solves this very nicely: http://zpt.sourceforge.net/ -- Ren? Pijlman From roy at panix.com Fri Jun 11 08:06:04 2004 From: roy at panix.com (Roy Smith) Date: Fri, 11 Jun 2004 08:06:04 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: dkturner at telkomsa.net (David Turner) wrote: > 1. Objects of classes that declare a __del__ method shall be referred > to as "deterministic" objects. Such objects shall have a reference > count associated with. The reference count shall be incremented > atomically each time an additional reference to the object is created. > The reference count shall be decremented each time a name referring > to the object is deleted explicitly. Except in the situation > described in (2) below, the reference count shall be decremented each > time a name referring to the object becomes inaccessible due to the > set of locals to which the name belongs becoming inaccessible. > [...] > 3. When the reference count of a deterministic object reaches zero, > the __del__ method of the object shall be called. What if you do this... class Top: def __init__ (self): self.bottom = Bottom () class Bottom: def __del__ (self): do something really important top = Top () del top The problem here is that while Bottom.__del__ will get called as soon at top releases it's reference, there's nothing to guarantee that the reference will disappear until top is garbage collected. You could fix that by writing Top.__del__, but that assumes Top is a class you have control of (it might be something out of a library). Or am I not understanding the situation right? From jimka at rdrop.com Fri Jun 11 10:59:12 2004 From: jimka at rdrop.com (Jim Newton) Date: Fri, 11 Jun 2004 16:59:12 +0200 Subject: if does not evaluate In-Reply-To: <2iu1ooFrcu2hU1@uni-berlin.de> References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> <2ituufFrgqhaU1@uni-berlin.de> <2iu1ooFrcu2hU1@uni-berlin.de> Message-ID: <2iu2tsFp6ulcU1@uni-berlin.de> so what i have done in the past is write a generic searching function. def exists(predicate,seq): for item in seq: if( predicate(item)): return True return False then i used that funcion in a test. x = ["Peter", "Paul", "Mary", "Jane"] if( exists( lambda y: y.startswith("M"), x)): ... -jim > Peter Otten wrote: > >> Jim Newton wrote: >> >> >>> sorry, i do not understand. The python syntax is a bit >>> difficult for me. >> >> >> >> Maybe I obscured the issue by comparing name attributes to a string >> instead >> of using a predicate() function. >> >> >>> if i have a list x and a function f how do i know if >>> there is an element of x on which f returns something >>> other than False? >> >> >> >> Using the above identifiers, let's assume we are looking for a name >> starting >> with "M": >> >> >>>>> x = ["Peter", "Paul", "Mary", "Jane"] >>>>> def f(o): >> >> >> ... print "checking", o >> ... return o.startswith("M") >> ... >> >> If we call >> >> >>>>> map(f, x) >> >> >> checking Peter >> checking Paul >> checking Mary >> checking Jane >> [False, False, True, False] >> >> it invokes f() for every item in x and returns the above list of >> booleans. >> The equivalent list comprehension would be [f(i) for i in x]. Now >> >> >>>>> True in map(f, x) >> >> >> checking Peter >> checking Paul >> checking Mary >> checking Jane >> True >> >> gives the correct result but unfortunately does too much work as we don't >> need to calculate f("Jane") when we already know the outcome. Enter >> generator >> >> >>>>> def lazymap(predicate, seq): >> >> >> ... for item in seq: >> ... yield predicate(item) >> ... >> >> which calulates f(item) as needed. Proof: >> >> >>>>> True in lazymap(f, x) >> >> >> checking Peter >> checking Paul >> checking Mary >> True >> >> >> itertools.imap() is just the fast C implementation of lazymap(). >> The equivalent generator expression (new in Python 2.4) will be (f(i) >> for i in x). >> >> Peter >> > From stanleykagan at yepmail.net Fri Jun 25 12:22:40 2004 From: stanleykagan at yepmail.net (stan k.) Date: 25 Jun 2004 09:22:40 -0700 Subject: mysql vs sqlite vs hsql References: Message-ID: Thanks very much to both of you for the information - sorry about posting to here. I posted here only because when I did a search on google newsgroups it did not allow me to reply to other discussion threads about sql because they were too old. This group recently had a discusion thread about sql so I posted here... From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 30 06:48:50 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 30 Jun 2004 12:48:50 +0200 Subject: Any list larger than any number by way of dimensions? In-Reply-To: References: Message-ID: <2kfjo9F1pvs9U1@uni-berlin.de> David Fraser wrote: > Dan Bishop wrote: >> Harald Massa wrote in message news:... >> >>>Peter, >>> >>> >>>>data = [ ... some list ] >>>>buffersize = min(data,10) >>>> >>>>Of course what I really wanted was >>>> >>>>buffersize = min(len(data),10) >>> >>>if my memory suits me right, when everything else fails, Python is just >>>comparing the IDs of the objects. IDs are connected to the memory >>>addresses. >> >> >> That's true for user-defined objects, but for built-in types the rule is >> >> None < number < list < string < tuple >> >> Which is consistent but wrong. > > It's consistent but arbitrary. How can you say its wrong? It does what > its defined to do. You cannot say it is "wrong" in the usual sense that a string would have to be greater than a tuple, but in my eyes it is "wrong" that the types even give a result when compared, as opposed to raising a TypeError or something like this. IMHO, this behavior is only useful for implementing ugly tricks that should be avoided anyway, so I vote for removing this comparability. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From peter at engcorp.com Tue Jun 8 06:47:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jun 2004 06:47:29 -0400 Subject: Python Speed Question and Opinion In-Reply-To: <40c58636$0$8219$afc38c87@news.easynet.co.uk> References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > You are correct, it is just that if all you are concerned about is speed > then assembler is what you need. Jacek already made this point, but I'll make it again. Assembler is sometimes *not* the way to write the fastest code. (Though sometimes it is.) Optimizing compilers for some languages such as C can actually produce *faster* code by choosing combinations of opcodes and side-effects that even an assembly programmer would be nuts to use in most cases, largely because it would make the code even more obscure than it already is but also because they might not even think of it. A simplistic example (and one which many x86 programmers learned about and started using, but probably did not initially) is how to clear a register. The chip provided a CLR instruction, but it actually took (originally, maybe not now) longer to execute than if one would XOR the register with itself and thus clear it. There are many other and more complicated examples which compiler optimizers can use but which are too hard to keep track of for most assembly writers. -Peter From tim.jarman at lineone.net Fri Jun 4 09:52:03 2004 From: tim.jarman at lineone.net (Tim Jarman) Date: Fri, 4 Jun 2004 14:52:03 +0100 Subject: Doomsday devices considered harmful (Was: walking a MIME encoded multipart email [python]) In-Reply-To: <3600c0t96ceeqcm04fspldp168u0adndg0@4ax.com> References: <3600c0t96ceeqcm04fspldp168u0adndg0@4ax.com> Message-ID: <200406041452.03436.tim.jarman@lineone.net> On Friday 04 Jun 2004 06:15, fishboy wrote: > What?! > Has Ernst Stavro Blofeld attached some doomsday device to your stack > trace? > You've got an interpreter, use it! Go man! Go! > +1 QOTW From jfabiani at yolo.com Wed Jun 16 09:58:24 2004 From: jfabiani at yolo.com (John fabiani) Date: Wed, 16 Jun 2004 13:58:24 GMT Subject: Anyone know a good Pygresql Tutorial for Interfacing between Python &Postgresql In-Reply-To: References: Message-ID: <40D0521D.6010004@yolo.com> Peter Maas wrote: > Chuck Amadi schrieb: > >> Anyone know a good Pygresql Tutorial for Interfacing between Python & >> Postgresql . > > > Tried Google and found > > http://www.pygresql.org/README.txt > > > Mit freundlichen Gruessen, > > Peter Maas > I'm a newbie so take what I have to say with a grain of salt. The problem for me was not how to make a connection to postgres but how to use the data returned. Maybe I'm missing something but almost every sample I could find did not work as expected. The first issue was each example (ones found via google and in O'Reilly books) show that a tuple is returned. At least for my postgres driver (module) the return type is a list. The next issue is how to loop through the data. Also the examples use fetchone() as an example. But even they did not work because of the 'tuple' issue and most of the time I needed fetchmany(100) or fetchall(). I still have not resolved most of the issues but I'm still learning. John From dyoo at hkn.eecs.berkeley.edu Thu Jun 10 18:42:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Thu, 10 Jun 2004 22:42:11 +0000 (UTC) Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> Message-ID: : : According to latest news the largest known prime is: : : 2**24036583 - 1 : : (right?) : Let's see... how many digits would it be? : ### :>>> def digits(n): : ... return int(math.log(n) / math.log(10)) + 1 : ... :>>> x = 2**2436583 - 1 :>>> digits(x) : 733485 : ### : Ok, that doesn't sound too bad at all. It's about 750,000 digits long. Yikes. I introduced an order-of-magnitude bug when defining x. Let me recalculate that: ### >>> x = 2**24036583 - 1 >>> digits(x) 7235733 ### Ok, so there's about 7 million digits in that thing. Slightly more difficult to print out. *grin* My apologies for the mistake! From dkgunter at lbl.gov Fri Jun 11 23:06:17 2004 From: dkgunter at lbl.gov (Dan Gunter) Date: Fri, 11 Jun 2004 20:06:17 -0700 Subject: fast list search? In-Reply-To: <%Cryc.14374$kn2.241788@news.ono.com> References: <%Cryc.14374$kn2.241788@news.ono.com> Message-ID: <40CA7329.2050302@lbl.gov> How about using a dictionary, with the keys being the ints and the values being the index in the 'list', i.e. len(dictionary). This is quite fast: >>> d = {} >>> for i in xrange(0,500000): ... if not d.has_key(i): d[i] = len(d) -Dan Javier Zaragoz? Arenas wrote: > I think the better way is sort before the list > > >>>thelist.sort() > > > And then, a binary search > > >>>point_of_insertion = bisect.bisect(thelist, item) >>>is_present = thelist[point_of_insertion -1:point_of_insertion] == [item] > > >> if not is_present: > .... thelist.insert(point_of_insertion, item) > > and done! > > Fco Javier Zaragoz? Arenas > > > > "ramon aragues" escribi? en el mensaje > news:mailman.747.1086774432.6949.python-list at python.org... > >>Hi, >> >>I?ve got a list with more than 500,000 ints. Before inserting new ints, >>I have to check that it doesn?t exist already in the list. >> >>Currently, I am doing the standard: >> >>if new_int not in long_list: >>long_list.append(new_int) >> >> >>but it is extremely slow... is there a faster way of doing this in python? >> >>Thanks a lot, >> >>Ramon Aragues >> >> > > > From abkhd at earth.co.jp Sun Jun 20 20:08:15 2004 From: abkhd at earth.co.jp (A. B., Khalid) Date: 20 Jun 2004 17:08:15 -0700 Subject: Success Natively Compiling Python-2.3.4 in Mingw? Message-ID: <8ad8ad0a.0406201608.7f785c3d@posting.google.com> Hello all. After a search on Google it would seem that the users of Mingw have not had good results in compiling the python sources natively. See at least: [1] http://uucode.com/texts/python-mingw/python-mingw.html Having said that, kindly allow me to report that Mingw32 can now compile python-2.3.4 sources natively. Both Mingw make files and DEV-C++ project files can now compile the python sources. There is surely more to be done to remove even more rough edges; but the results are very promising. The compiled python is, for now, renamed to python23 so as to keep my clean working copy of Python-2.1 unaffected. +---------------------------------------------------------------+ My system: +---------------------------------------------------------------+ + Win98 + Mingw v. 3.2 + DEV-C++ v. 4.9.8.5 + MYSYS v. 1.0.9 +---------------------------------------------------------------+ For file sizes, here is the list: +---------------------------------------------------------------+ PYTHON23 EXE 11,776 20/06/04 19:24 python23.exe PYTHONW EXE 12,800 20/06/04 19:29 pythonw.exe PYTHON23 DLL 1,224,704 20/06/04 20:05 python23.dll W9XPOPEN EXE 12,288 19/06/04 8:07 w9xpopen.exe +---------------------------------------------------------------+ Running python23 from MSYS: +---------------------------------------------------------------+ $ python23 -i Python 2.3.4 (#0, Jun 20 2004, 04:00:28) [Mingw 32 bit (AMD)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 1+2 3 >>> +---------------------------------------------------------------+ Summary of regrtest.main() output: +---------------------------------------------------------------+ 204 tests OK. 1 test failed: test_datetime 50 tests skipped: test_aepack test_al test_bsddb test_bsddb185 test_bsddb3 test_bz2 test_cd test_cl test_commands test_crypt test_curses test_dbm test_dl test_email_codecs test_fcntl test_fork1 test_gdbm test_gl test_grp test_gzip test_imgfile test_ioctl test_largefile test_linuxaudiodev test_macfs test_macostools test_mhlib test_mpz test_nis test_normalization test_openpty test_ossaudiodev test_pep277 test_plistlib test_poll test_posix test_pty test_pwd test_resource test_scriptpackages test_signal test_socket_ssl test_socketserver test_sunaudiodev test_timeout test_timing test_urllibnet test_zipfile test_zipimport test_zlib 6 skips unexpected on win32: test_bz2 test_zipfile test_bsddb test_zipimport test_gzip test_zlib +---------------------------------------------------------------+ More on test_datetime: +---------------------------------------------------------------+ E:\Python23>python23 Python 2.3.4 (#0, Jun 20 2004, 04:00:28) [Mingw 32 bit (AMD)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from test import test_datetime Traceback (most recent call last): File "", line 1, in ? File "E:\PYTHON23\lib\test\test_datetime.py", line 2821, in ? Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") TypeError: cannot create 'USTimeZone' instances >>> +---------------------------------------------------------------+ A closer inspection of test test_socket: +---------------------------------------------------------------+ $ /e/python23/python23.exe -i Python 2.3.4 (#0, Jun 20 2004, 04:00:28) [Mingw 32 bit (AMD)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import test_socket as t >>> t.test_main() testCrucialConstants (test_socket.GeneralModuleTests) ... ok testDefaultTimeout (test_socket.GeneralModuleTests) ... ok testGetServByName (test_socket.GeneralModuleTests) ... ok testGetSockOpt (test_socket.GeneralModuleTests) ... ok testHostnameRes (test_socket.GeneralModuleTests) ... ok testIPv4toString (test_socket.GeneralModuleTests) ... ok testIPv6toString (test_socket.GeneralModuleTests) ... ok testInterpreterCrash (test_socket.GeneralModuleTests) ... ok testNtoH (test_socket.GeneralModuleTests) ... ok testRefCountGetNameInfo (test_socket.GeneralModuleTests) ... ok testSendAfterClose (test_socket.GeneralModuleTests) ... ok testSetSockOpt (test_socket.GeneralModuleTests) ... ok testSockName (test_socket.GeneralModuleTests) ... ok testSocketError (test_socket.GeneralModuleTests) ... ok testStringToIPv4 (test_socket.GeneralModuleTests) ... ok testStringToIPv6 (test_socket.GeneralModuleTests) ... ok testFromFd (test_socket.BasicTCPTest) ... ok testOverFlowRecv (test_socket.BasicTCPTest) ... ok testOverFlowRecvFrom (test_socket.BasicTCPTest) ... ok testRecv (test_socket.BasicTCPTest) ... ok testRecvFrom (test_socket.BasicTCPTest) ... ok testSendAll (test_socket.BasicTCPTest) ... ok testShutdown (test_socket.BasicTCPTest) ... ok testTCPTimeout (test_socket.TCPTimeoutTest) ... ok testTimeoutZero (test_socket.TCPTimeoutTest) ... ok testExceptionTree (test_socket.TestExceptions) ... ok testRecvFrom (test_socket.BasicUDPTest) ... ok testSendtoAndRecv (test_socket.BasicUDPTest) ... ok testTimeoutZero (test_socket.UDPTimeoutTest) ... ok testUDPTimeout (test_socket.UDPTimeoutTest) ... ok testAccept (test_socket.NonBlockingTCPTests) ... ERROR ERROR testConnect (test_socket.NonBlockingTCPTests) ... ok testRecv (test_socket.NonBlockingTCPTests) ... ERROR testSetBlocking (test_socket.NonBlockingTCPTests) ... ok testFullRead (test_socket.FileObjectClassTestCase) ... ok testReadline (test_socket.FileObjectClassTestCase) ... ok testSmallRead (test_socket.FileObjectClassTestCase) ... ok testUnbufferedRead (test_socket.FileObjectClassTestCase) ... ok testFullRead (test_socket.UnbufferedFileObjectClassTestCase) ... ok testReadline (test_socket.UnbufferedFileObjectClassTestCase) ... ok testSmallRead (test_socket.UnbufferedFileObjectClassTestCase) ... ok testUnbufferedRead (test_socket.UnbufferedFileObjectClassTestCase) ... ok testUnbufferedReadline (test_socket.UnbufferedFileObjectClassTestCase) ... ok testFullRead (test_socket.LineBufferedFileObjectClassTestCase) ... ok testReadline (test_socket.LineBufferedFileObjectClassTestCase) ... ok testSmallRead (test_socket.LineBufferedFileObjectClassTestCase) ... ok testUnbufferedRead (test_socket.LineBufferedFileObjectClassTestCase) ... ok testFullRead (test_socket.SmallBufferedFileObjectClassTestCase) ... ok testReadline (test_socket.SmallBufferedFileObjectClassTestCase) ... ok testSmallRead (test_socket.SmallBufferedFileObjectClassTestCase) ... ok testUnbufferedRead (test_socket.SmallBufferedFileObjectClassTestCase) ... ok ====================================================================== ERROR: testAccept (test_socket.NonBlockingTCPTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "E:\PYTHON23\lib\test\test_socket.py", line 543, in testAccept read, write, err = select.select([self.serv], [], []) ValueError: filedescriptor out of range in select() ====================================================================== ERROR: testAccept (test_socket.NonBlockingTCPTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "E:\PYTHON23\lib\test\test_socket.py", line 117, in _tearDown self.fail(msg) File "E:\PYTHON234\PYTHON-2.3.4\lib\unittest.py", line 270, in fail raise self.failureException, msg AssertionError: (10061, 'Connection refused') ====================================================================== ERROR: testRecv (test_socket.NonBlockingTCPTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "E:\PYTHON23\lib\test\test_socket.py", line 571, in testRecv read, write, err = select.select([conn], [], []) ValueError: filedescriptor out of range in select() ---------------------------------------------------------------------- Ran 51 tests in 14.340s FAILED (errors=3) Traceback (most recent call last): File "", line 1, in ? File "E:\PYTHON23\lib\test\test_socket.py", line 752, in test_main test_support.run_unittest(*tests) File "test_support.py", line 262, in run_unittest run_suite(suite, testclass) File "test_support.py", line 246, in run_suite raise TestFailed(msg) test.test_support.TestFailed: errors occurred; run in verbose mode for details >>> +---------------------------------------------------------------+ Test test_socket passes or fails? +---------------------------------------------------------------+ Why regrtest.main() is reporting that test_socket passes, when test_socket itself reports that it fails is beyond me. Mind you, however, that the socket module itself can run the simple echo client/server(s) that were modified by me and which came with python21 without problems. +---------------------------------------------------------------+ Summary of changes: +---------------------------------------------------------------+ Number of files changed in source Python-2.3.4.tar.bz2: 10 +---------------------------------------------------------------+ Overview of all changes which number 16: +---------------------------------------------------------------+ [1] 3 changes in socketmodule.c [2] 1 change in socketmodule.h (The test fails or passes?) [3] 2 changes in posixmodule.c [4] 1 change in _csv.c [5] 5 changes in datetimemodule.c (test_datetime.py is the (only?) test that fails; Note that the module appears loadable, however. And seems able to run some of its methods; after all test_calendar passes). [6] 1 change in _winreg.c [7] 1 change in ../PC/pyconfig.h [8] Not using python_nt.rc (Using pythoncore_private.rc, & python_mingw.rc instead). [9] 1 change in dynload_win.c [10] 1 change in thread_pthread.c (This file is ignored, I think). +---------------------------------------------------------------+ Sources are guarded: +---------------------------------------------------------------+ Most changes guard the original source and are in the form of: /* My addition/change */ /* Comment...*/ #if defined(__MINGW32__) /*define or do something*/ #else original python source code here #endif +---------------------------------------------------------------+ Last words: +---------------------------------------------------------------+ If someone can kindly verify that the failed tests are not serious (they don't seem to be; I even don't have the datetime module in my current Python-2.1) or can be fixed, or if many people are interested in documentation of the source changes, then I'll be more than happy to share them. Peace -- Q. The purpose of life? [A]: "I created the jinn and humankind only that they might worship Me." (Translation, Qur'an, 51:56) [B]: "Let us hear the conclusion of the whole matter: Fear God, and keep his commandments: for this is the whole duty of man." (KJV, Ecclesiastes 12:13) From claird at lairds.com Fri Jun 4 09:12:44 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 04 Jun 2004 13:12:44 -0000 Subject: executing a python script from another python script. References: Message-ID: <10c0tacfm9qih88@corp.supernews.com> In article , sarmin kho wrote: . . . >I ve created a GUI using Boa constructor and am now trying to execute a >python script when pressing a button on the GUI. So, there will then be >two main threads running (the GUI thread and the python script thread). >The purpose of doing this is to enable selecting python script to be run >from the GUI. . . . What you want certainly is possible. I don't understand yet what you want. Please explain the user view again. The user sees a GUI. The user pushes a button. "[T]he [P]ython script" begins to execute. Does the GUI need the result of the script's operation? Is the purpose of the button-push to run the script, or to run it and receive a result? Should the GUI "block" until the script is done, or remain responsive to other user points-and-clicks, or go on with other actions? On what platforms do you want to run your application? -- Cameron Laird Business: http://www.Phaseit.net From llothar at web.de Mon Jun 14 04:14:25 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Jun 2004 01:14:25 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <6ee58e07.0406140014.63987321@posting.google.com> Ryan Paul wrote in message news:... > Ruby and Python really have a lot in common. The one you use should > ultimately be based on your style and how you feel about programming. If > you like lots of mutability, lots of functional idioms, and inline regular > expressions, switch to ruby! If not, stick with python. Or if you need real multithreading and WxPython. This are IMHO the reasons not to switch to ruby. The python implementation is technically much better. And the python libraries are still much better then ruby. As the person behind "http://www.python-ide.com" and "http://www.ruby-ide.com" i can tell you that otherwise the language are almost the same. For example from the 18000 lines of code for the debugger about 2000 lines are different for this two languages. But look yourself. A weekend should be enough for a python programmer to learn ruby. From fperez528 at yahoo.com Wed Jun 23 01:04:33 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 22 Jun 2004 23:04:33 -0600 Subject: Collecting Python's responses. References: Message-ID: Jacek Generowicz wrote: > I'm looking for ways of creating annotated records of Python > interactive sessions, for documentation purposes. For example, > something like > > # dir shows the contents of the namespace > >>> dir() > ['__builtins__', '__doc__', '__name__'] > # Addition works too > >>> 1+2 > 3 > > However, I would like to automate the incorporation of Python's actual > output, so I would like to run a program which looks something like > this: [snip] This could be an easy addition to ipython (http://ipython.scipy.org). It already has all the display hooks in place, and in fact the output handler is user-accessible. Cheers, f From harry.g.george at boeing.com Thu Jun 17 15:28:37 2004 From: harry.g.george at boeing.com (Harry George) Date: Thu, 17 Jun 2004 19:28:37 GMT Subject: Using Fortran libraries from Python? References: Message-ID: Carl writes: > I have experimented with f2c and swig-generated wrappers to create python > modules from Fortran files. > > I think I'm missing something when I'm building the Python module, because > when I import the built module the Python interpreter returns the > following: > > >>> import LDSsobol > Traceback (most recent call last): > File "", line 1, in ? > File "LDSsobol.py", line 4, in ? > import _LDSsobol > ImportError: /usr/lib/libf2c.so.0: undefined symbol: MAIN__ > > This is how I built LDSsobol: > > > gcc -c LDSsobol.c > > gcc -c LDSsobol_wrap.c -I/usr/include/python > > gcc -shared LDSsobol.o LDSsobol_wrap.o -l f2c -o _LDSsobol.so > > Any help is appreciated! > > Carl Did you start with pyfort? http://sourceforge.net/projects/pyfortran I haven't used it personally, but it seems to be addressing your concerns, without ad hoc SWIGing. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From nobody at nowhere.com Sun Jun 13 23:58:50 2004 From: nobody at nowhere.com (PaxDiablo) Date: Mon, 14 Jun 2004 11:58:50 +0800 Subject: How to Access Unix Shell References: <2d7af4f8.0406131648.42868c63@posting.google.com> Message-ID: "Neale" wrote in message news:2d7af4f8.0406131648.42868c63 at posting.google.com... > In a python program, I want to do a Unix directory list and then > append selected files to each other which, as you know, is just "cat > filename2 >> filename1." How do I escape into the shell and then > return, bringing with me a directory list? How about? ===== import os pipeLine = os.popen("ls -1","r") curLine = pipeLine.readline() while curLine: print "Got file [%s]"%(curLine[:-1]) curLine = pipeLine.readline() pipeLine.close() ===== > > Where can I find some examples of mixing shell commands and Python? From cliechti at gmx.net Wed Jun 9 18:47:42 2004 From: cliechti at gmx.net (Chris Liechti) Date: Wed, 9 Jun 2004 22:47:42 +0000 (UTC) Subject: dropping into the debugger on an exception References: <2iovgrFq6taqU1@uni-berlin.de> Message-ID: Jon Perez wrote in news:2iovgrFq6taqU1 at uni- berlin.de: > Thomas Heller wrote: > >>>Just to be clear: you don't want this to happen all the time, >>>you want it to happen only with a particular script, yet you >>>don't want to modify that script at all? >> >> I also don't understand *why* he wants to have it that way. > > Just in case you missed the answer I gave earlier... > > I don't even want this behaviour all the time with the same > script because end-users will be confused if they get dropped > into pdb. Believe me, you don't want to explain what pdb is > to people who have a hard time even navigating via the > command prompt! > > The best situation would be to be able to invoke this behaviour > only when I want it (i.e. during coding/debugging) and not have > to change anything (including sitecustomize.py) when I don't > want it around (the same machine might be used by both the > developer and the end-user). > i usualy use something like that: if __name__ == '__main__': try: from optparse import OptionParser parser = OptionParser() #... parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="enable debug outputs") (options, args) = parser.parse_args() logger.setLevel(logging.WARN) if options.verbose: logger.setLevel(logging.INFO) if options.debug: logger.setLevel(logging.DEBUG) main() except SystemExit: raise except Exception, msg: if debug: #raise #i usualy use that pdb.pm() #that's what you want else: sys.stderr.write("%s: %s\n" % (msg.__class__.__name__, msg)) sys.exit(1) that way, adding a -d on the command line will enable more log messages and full tracebacks (or pdb). you could of also use a separate option for pdb or only enable it if multiple -ddd are given (debug level increased) chris -- Chris From peter.maas at mplusr.de Thu Jun 17 03:25:24 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 17 Jun 2004 09:25:24 +0200 Subject: Anyone know a good Pygresql Tutorial for Interfacing between Python &Postgresql In-Reply-To: <40D0521D.6010004@yolo.com> References: <40D0521D.6010004@yolo.com> Message-ID: John fabiani schrieb: > I'm a newbie so take what I have to say with a grain of salt. The > problem for me was not how to make a connection to postgres but how to > use the data returned. Here is a tested example code. It relies on pyPgSQL but PyGreSQL should be quite similar especially the data access: ----------------------------------------------------------------- #!/usr/bin/env python # -*- coding: latin-1 -*- """ Example code how to read data from a PostgreSQL database. You need the pyPgSQL module which is DB-API 2.0 compliant so that the calls are not database dependent except of connection URL and some SQL capabilities. """ # PostgreSQL interface module from pyPgSQL import PgSQL if __name__ == '__main__': # open connection con = PgSQL.connect(None, "aUser", "aPasswd", "aHost", "aDatabase") # create cursor c_adr = con.cursor() # let cursor execute an SQL command c_adr.execute("SELECT * FROM address") # fetch a result set r_adr = c_adr.fetchmany(10) # The result set is a list of records. print r_adr[0] # Each record is a dictionary like object with field names as keys. print r_adr[0].keys() # The field values are the dictionary values. print r_adr[0]["firstname"] # print all records for record in r_adr: print record ----------------------------------------------------------------- Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From steve.menard at videotron.ca Wed Jun 16 15:30:43 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Wed, 16 Jun 2004 15:30:43 -0400 Subject: Need some help with Python/C api and threading Message-ID: Here is my problem. I have this library thats hosts another language within python, and allows that language to call back INTO python. All is good as long as the other languages calls back on the same thread. If the callback arrives on a different thread, all hell break loose and the program dies horribly. looking at the C api documentation, I came upon the following block of code : PyThreadState *tstate; PyObject *result; /* interp is your reference to an interpreter object. */ tstate = PyThreadState_New(interp); PyEval_AcquireThread(tstate); /* Perform Python actions here. */ result = CallSomeFunction(); /* evaluate result */ /* Release the thread. No Python API allowed beyond this point. */ PyEval_ReleaseThread(tstate); /* You can either delete the thread state, or save it until you need it the next time. */ PyThreadState_Delete(tstate); Which would seem to be what I need. However, I have no idea how to get at that interp pointer. I tried the following : PyInterpreterState* interp = PyInterpreterState_New(); PyThreadState *tstate = PyThreadState_New(interp); PyEval_AcquireThread(tstate); but then it crashes on the second line ... Anybody ever done this? As a side note, the hosted language can start an arbitrary number of threads ... Steve From tjreedy at udel.edu Wed Jun 2 12:03:01 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 Jun 2004 12:03:01 -0400 Subject: Need help resolving accidental (honest!) language pissing match References: <69cbbef2.0406020615.7540ad0@posting.google.com> Message-ID: "has" wrote in message news:69cbbef2.0406020615.7540ad0 at posting.google.com... > Careless talk costs lives, as they say. In my case, a ... > stupid and incompetent to do it all by myself. :p Perhaps you should squirm on your own petard a bit, but here are some comments ;-) > "Suppose I want to study a random walk. Say I would like to appreciate > the distribution of the presence of the walker." > > set n to 1000000 -- we'll be talking about 4 MB There is no need to save a million of anything that i can see. If there were, preallocate the list with "array = n*[1] > set x to randomarray n range {-1, 1} -- n random draws This is slightly unclear. Without the unneeded array, perhaps you mean something like x = 0 for i in xrange(n): x += random.random() < .5 and -1 or 1 > set x to runningsum x -- the cumulative sums of the draws The above does that as you draw. > set {mean:the_mean, stdev:the_stdev} to statlist x -- compute > stats stats other that x itself are only meanful across multiple walks (ie, m walks of n steps each). Since you have not specified m, I am not sure what you have in mind. To keep x**2 fitting within an int instead of long, n = 100,000 would be better. > All the real work here's being done by a C-based scripting addition > (plugin), taking about a second on a G4/867. If the int sums are done in C in the addition (aha! this must bei the reason to make an array), Numerical Python will not do better and maybe not as well. If that C addition does floating point in C much like NumPy, then perhaps AppleScript is less underpowered than you claim. If the worst comes to the > worst, I can force a dishonorable draw simply by calling the same > scripting addition via MacPython's Carbon support modules, but I'd > really like to punt the blighter out of the ballpark Unlikely if the C addition is any good. Anyway, why? The competitive advantage of Python is programming speed, especially for larger problems than this. >so existing > C-based Python extensions, Python-to-Fortran bridges, etc. are all > okay by me if anyone has a few minutes and spot of sympathy to point > us in the right direction. Cheers! :) If Psyco runs on Apple, try that. Otherwise, make arrays and use NumPy. Terry J. Reedy From dkturner at telkomsa.net Thu Jun 10 04:11:40 2004 From: dkturner at telkomsa.net (David Turner) Date: 10 Jun 2004 01:11:40 -0700 Subject: does python have useless destructors? References: Message-ID: "Michael P. Soulier" wrote in message news:... > So putting a close of some external resource in a destructor would be a > bad idea, apparently. As this is the kind of thing I typically use > destructors in OO programming for, I found this quite surprising. > Me too. Fortunately, in the current vanilla Python implementation, the destructors are fairly reliable. However there is a fatal flaw: locals get extra references when exceptions are raised. Which pretty much means you can't use RAII wherever it would be most useful. This makes me sad. But there is some hope in the following pattern, although it can be quite awkward: def with_file(fname, mode, oper): f = open(fname, mode); try: oper() finally: f.close() Of course, this can very quickly turn your code into so much functional goo. That's not necessarily a bad thing, as Lisp programmers can attest... But it's still not quite as powerful as RAII. Regards David Turner From aahz at pythoncraft.com Thu Jun 10 16:56:57 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2004 16:56:57 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: In article <-oadnfu_sdwTUFrdRVn-hw at powergate.ca>, Peter Hansen wrote: >Michael P. Soulier wrote: >> >> myfile = open("myfilepath", "w") >> myfile.write(reallybigbuffer) >> myfile.close() > >... immediately raises a warning flag in the mind of an >experienced Python programmer. Depends on the circumstance, I'd think. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From BELLEMAIL-SA at exponent.com Wed Jun 23 22:31:09 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 19:31:09 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F80@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = fumanchu at amor.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 261 Scanning time = 06/23/2004 19:31:08 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment id43342.zip contained WORM_NETSKY.P virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From a.schmolck at gmx.net Fri Jun 18 16:10:43 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Fri, 18 Jun 2004 21:10:43 +0100 Subject: Attention, hyperlinkers: inference of active text References: <10d6bln988rmne6@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: > I'm looking for ideas, although their expression in executable > certainly doesn't offend me. > > I do text manipulation. As it happens, I'm in a position to > "activate" the obvious URI in > Now is the time for all good men to read http://www.ams.org/ > That's nice. End-users "get it", and are happy I render > "http://www.ams.org" as a hyperlink. Most of them eventually > notice the implications for punctuation, that is, that they're > happier when they write > Look at http://bamboo.org ! > than > Look at http://bamboo.org! > > The design breaks down more annoyingly by the time we get to > the "file" scheme, though. How do the rest of you handle this? > Do you begin to make end-users quote, as in > The secret is in "file:\My Download Folder\dont_look.txt". > ? Is there some other obvious approach? I am confident that > requiring > It is on my drive as file:\Program%20Files\Perl\odysseus.exe > is NOT practical with my clients. Can't you get them to write (or, alternatively which, although not backed up by a RFC, also ought to do the job and is less to type and to remember). Apart from making escaping superfuous, this should also solve all your punctuation and linebreak problems robustly. '<','>' can't occur in URIs so matching '.' or so (and then kicking out '\n\s.*') ought to work, no? 'as From peter at engcorp.com Fri Jun 25 11:57:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jun 2004 11:57:29 -0400 Subject: Encryption with Python In-Reply-To: References: <889cbba0.0406221926.3f4e5776@posting.google.com> <889cbba0.0406231156.115b743a@posting.google.com> <2nend09je70o8a07lvemhbn8ieo8aamuip@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Fri, 25 Jun 2004 08:45:43 -0400, Peter Hansen > declaimed the following in comp.lang.python: >>Kamilche *did* state clearly that it was "not secure, but it should >>be enough to ward off casual hacking". > > About to the level of the old "CryptoGrams" puzzles some > newspapers run (though they usually give you one starting substitution > -- but in a long missive, that type of hint may not be needed). > > It would be a slow implementation in Python, but one > "improvement" I'd consider (since it looks like there are already > multiple tables): Using just a..z0..9 (ignoring case and punctuation > characters) would be to create 36 substitution tables, then use the > output of one character substitution as the index to the table for the > next character's translation. > > This would avoid the "bookkeeper" type input from giving hints > in the output. The reverse (decryption) gets a tad more difficult. But why would anyone want to improve the security of this approach? If one wants casual obscurification(tm), it does just fine as-is. If one wants real security, one would be insane to use anything less than Blowfish, 3DES, AES and their ilk... -Peter From me at privacy.net Tue Jun 8 07:22:07 2004 From: me at privacy.net (Duncan Booth) Date: 8 Jun 2004 11:22:07 GMT Subject: Destructors and exceptions References: Message-ID: nicksjacobson at yahoo.com (Nick Jacobson) wrote in news:f8097096.0406080308.6df86699 at posting.google.com: > You know, I noticed this in the Python Reference Manual, p. 13, and > have been wondering about it. > > "...note that catching an exception with a 'try...except' statement > may keep objects alive..." > > No explanation is given, and I don't know why that's the case either. > But at least they're aware of it...HTH > When an exception is handled, you can access the stack traceback. This contains references to all the local variables which were in scope at the point when the exception was thrown. Normally these variables would be destroyed when the functions return, but if there is a traceback referencing them they stay alive as long as the traceback is accessible which is usually until the next exception is thrown. If you really want to be sure your objects are destroyed, then use 'del' in the finally suite of a try..finally. This ensures that the traceback can't be used to reference the objects that you deleted. From uscode at dontspam.me Tue Jun 29 17:04:33 2004 From: uscode at dontspam.me (USCode) Date: Tue, 29 Jun 2004 21:04:33 GMT Subject: wxPython support non-GUI classes from wxWidgets? References: Message-ID: "Peter Hansen" wrote > > The docs, somewhere, note that primarily only the functionality that > is *not* duplicated by existing Python functionality is provided. > I believe that includes at least XML, threading, and anything to do > with networking, and probably other things. (Going entirely by > memory here, from the last time I read this stuff, well over a > year ago. I can find the exact location of the notes, if you aren't > able to.) > Thanks Peter. I guess what confused me was that the wxPython doc refers to the wxWidgets doc as it's official documentation. But elsewhere on the wxPython site it implies that only the GUI wxWidget functionality has Python wrappers provided. Is there a list somewhere of all the wxWidget classes that have wxPython wrappers currently available? From max at alcyone.com Wed Jun 2 20:12:56 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jun 2004 17:12:56 -0700 Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: <40BE6D08.96690367@alcyone.com> Josh Gilbert wrote: > If, on the other hand, you knew that one program took 3n+7 and another > took > (n^2) / 10^10 you WOULD say that one's O(n) and the other's O(n^2). > This > implies that the first one is faster for large data sets. For very, very large data sets. Remember that big-O notation is designed to describe the behavior as n tends toward infinity (which is why we drop the constant coefficients and the lesser terms). It's important to remember that big-O notation is not intended for a direct performance comparison of two algorithms in the real world; it's intended to examine scalability issues in the big picture. Those constant coefficients and lesser terms can make a big difference in the real world, even for really quite large n. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ I'll tell them that their daddy was / A good man -- India Arie From has.temp2 at virgin.net Wed Jun 9 13:59:11 2004 From: has.temp2 at virgin.net (has) Date: 9 Jun 2004 10:59:11 -0700 Subject: fast list search? References: Message-ID: <69cbbef2.0406090959.31e546a2@posting.google.com> "Thomas Guettler" wrote in message news:... > Use a dictionary instead of the list: > > if not long_dict.has_key(new_int): > long_dict[new_int]=1 Or use an ordered list, which can be searched using an O(log n) binary search algorithm (e.g. see the bisect module) instead of O(n) linear search. Not sure which would be more efficient; if performance matters you'd need to implement both and run comparative timing tests, otherwise just use the dict solution as it's the simplest. If your original list is unsorted and order is important, you can maintain a second ordered list or dict alongside it purely for performing your itemExists(i) tests. Remember to always add and remove items to both to keep them in sync. And you can wrap the lot up as a single custom BigUniqueList class to keep it neat and tidy and mediate all access via accessor/mutator methods to ensure integrity is maintained. From r.gable at mchsi.com Sat Jun 19 10:17:26 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 19 Jun 2004 07:17:26 -0700 Subject: Another MSIE Python Question Message-ID: <22b7fd40.0406190617.a33514@posting.google.com> I am opening MSIE6 with this code: ie=Dispatch('InternetExplorer.Application.1') ie.Navigate(url) while ie.Busy: time.sleep(0.1) ied=ie.Document while ied.ReadyState != 'complete': time.sleep(0.1) ieh=ied.documentElement.outerHTML When opening Word or Excel, and using Dispatch('Word.Application') or Dispatch('Excel.Application'), the app comes up and is available and can be brought up on the screen by setting .Visible = 1. When using the above code, IE will not come up. I have to open IE by clicking on its icon and then the above code will work. If I don't do that I get a stack dump and my python program crashes. Any help would be appreciated. From rmb25612 at yahoo.com Mon Jun 14 14:39:08 2004 From: rmb25612 at yahoo.com (Richard James) Date: 14 Jun 2004 11:39:08 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <6ee58e07.0406140004.3d7c35c4@posting.google.com> Message-ID: <2c60f0e0.0406141039.2461a800@posting.google.com> llothar at web.de (Lothar Scholz) wrote in message news:<6ee58e07.0406140004.3d7c35c4 at posting.google.com>... > rmb25612 at yahoo.com (Richard James) wrote in message news:<2c60f0e0.0406131234.49b485ec at posting.google.com>... > > > Needless to say, the Ruby site was Slashdot-ed today. > > This has nothing to do with ./ > The site was hacked and corrupted two weeks ago and since this time > one a stub is online. This info was from an early post on comp.lang.ruby http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&threadm=a7c2a81904061313337ee962a2%40mail.gmail.com&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.ruby And it was corrected to reflect that the Ruby site is "down for maintenance". Maybe they need to use Zope? :) And it's /. :) From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 16 14:05:05 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 16 Jun 2004 20:05:05 +0200 Subject: Add methods to int? In-Reply-To: References: <2jbck8Fv3nqjU1@uni-berlin.de> Message-ID: <2jbg91Fvsfl0U1@uni-berlin.de> Peter Otten wrote: > int and str have no __dict__, neither in the class nor instance, and hence > no place to store your additions: > >>>> "__dict__" in dir(4) > False >>>> "__dict__" in dir(4 .__class__) > False So why does "print int.__dict__" produce a value? > Therefore you have to subclass them to gain the ability to add methods: > >>>> class Int(int): > ... def __new__(cls, n): > ... return int.__new__(cls, n) > ... >>>> x = Int(2) >>>> x.twice() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'Int' object has no attribute 'twice' > > Now let's grow our Int class a twice() method: > >>>> def twice(self): return 2*self > ... >>>> Int.twice = twice >>>> x.twice() > 4 That's clear, yes. But the problem with this solution is that I must convert all literals to Int before using them. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From fperez528 at yahoo.com Sat Jun 12 10:51:47 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 12 Jun 2004 08:51:47 -0600 Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I wonder if anyone can recommend any simple symbolic algebra modules > in Python. I just need to do some straightforward polynomial > arithmetic, no fancy calculus or special functions anything like that. > But I do need arbitrary precision rational coefficients in the > polynomials. Thanks. If _all_ you need are simple arithmetic operations on polynomials, then just go for a package with rational numbers (GMP has python wrappers). A polynomial is just a vector of coefficients, and Numeric accepts vectors of any object type (so you get convenient syntax). Best, f From opengeometry at yahoo.ca Fri Jun 4 19:17:12 2004 From: opengeometry at yahoo.ca (William Park) Date: 4 Jun 2004 23:17:12 GMT Subject: python vs awk for simple sysamin tasks References: <2ic128FllgicU1@uni-berlin.de> <2icbruFlqs1aU1@uni-berlin.de> Message-ID: <2ice7nFimf62U1@uni-berlin.de> Steve Lamb wrote: > >> It is amazing how much shell bogs down when you're running it > >> over several hundred thousand directories. :P > > > Same would be true for Python here. > > Not as much as shell. With shell you have thousands upon > thousands of fork/execs getting in the way. In the case I am > thinking of rewriting the shell script into Perl and doing all the > logic processing internally cut the run time down from 7-8 hours > down to *2*. I have seen similar perfomance numbers from Python > when compared to shell though not on that scale. I mean the same > could be said for C, or Assembly. Yes, iterations over large sets > of data is going to increase runtimes. However there are > inefficiencies not present in a scripting language which are > present in shell which make it exceptionally longer to run. 4x faster? Not very impressive. I suspect that it's poor quality shell script to begin with. Would you post this script, so that others can correct your misguided perception? -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From dieter at handshake.de Mon Jun 7 17:05:45 2004 From: dieter at handshake.de (Dieter Maurer) Date: 07 Jun 2004 23:05:45 +0200 Subject: Python 2.3.3 signals, threads & extensions: signal handling problem References: Message-ID: "Holger Joukl" writes on Thu, 3 Jun 2004 14:48:05 +0200: > migrating from good old python 1.5.2 to python 2.3, I have a problem > running a program that features some threads which execute calls to > an extension module. > Problem is that all of a sudden, I cannot stop the program with a keyboard > interrupt any more; the installed signal handler does not seem to receive > the signal at all. python-Bugs-756924 may be related to your problem. If so, you have a chance that the problem is fixed in Python 2.4. From tor.iver.wilhelmsen at broadpark.no Sat Jun 26 03:45:18 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 26 Jun 2004 09:45:18 +0200 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: Christian Tismer writes: > What exactly do you want to do? > Why is defining a function too much for you? One argument for "anonymous functions to be assigned to another object" is that defining such functions "pollute" the namespace with names that only serve one purpose, yet remain in some scope where they are no longer needed unless you delete them. def myAction(): print "You clicked me" b.OnClick = myAction del(myAction) etc. From peufeu at free.fr Fri Jun 25 02:43:44 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 08:43:44 +0200 Subject: z80 vs Python References: Message-ID: On 24 Jun 2004 16:36:09 -0700, Corey Coughlin wrote: > Personally, if I had the time, I'd try porting python to a gumstix > board: > > http://www.gumstix.com/ > > It probably wouldn't be too hard, but still, it'd be fun to get it > onto that tiny board. :) That board is incredible ! Is the "special" 286 processor on it 32-bit or 16-bit like the old 286 was ? I guess you can't run Linux on a 16 bit so it must be 32... And the price is so small ! From lbates at swamisoft.com Tue Jun 8 19:51:09 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 8 Jun 2004 18:51:09 -0500 Subject: POP3 and email References: <6PFwc.742$8k4.38828@news20.bellglobal.com> Message-ID: I knocked out exactly what you are looking for (I think??) today. Probably not the most 'elegant' way, but works for me and seems to be easy to use. Good luck, Larry Bates Syscon, Inc. import poplib import email import email.Parser import os import sys class email_attachment: def __init__(self, messagenum, attachmentnum, filename, contents): ''' arguments: messagenum - message number of this message in the Inbox attachmentnum - attachment number for this attachment filename - filename for this attachment contents - attachment's contents ''' self.messagenum=messagenum self.attachmentnum=attachmentnum self.filename=filename self.contents=contents return def save(self, savepath, savefilename=None): ''' Method to save the contents of an attachment to a file arguments: savepath - path where file is to be saved safefilename - optional name (if None will use filename of attachment ''' savefilename=savefilename or self.filename f=open(os.path.join(savepath, savefilename),"wb") f.write(self.contents) f.close() return class email_msg: def __init__(self, messagenum, contents): self.messagenum=messagenum self.contents=contents self.attachments_index=0 # Index of attachments for next method self.ATTACHMENTS=[] # List of attachment objects self.msglines='\n'.join(contents[1]) # # See if I can parse the message lines with email.Parser # self.msg=email.Parser.Parser().parsestr(self.msglines) if self.msg.is_multipart(): attachmentnum=0 for part in self.msg.walk(): # multipart/* are just containers mptype=part.get_content_maintype() filename = part.get_filename() if mptype == "multipart": continue if filename: # Attached object with filename attachmentnum+=1 self.ATTACHMENTS.append(email_attachment(messagenum, attachmentnum, filename, part.get_payload(decode=1))) print "Attachment filename=%s" % filename else: # Must be body portion of multipart self.body=part.get_payload() else: # Not multipart, only body portion exists self.body=self.msg.get_payload() return def get(self, key): try: return self.msg.get(key) except: emsg="email_msg-Unable to get email key=%s information" % key print emsg sys.exit(emsg) def has_attachments(self): return (len(self.ATTACHMENTS) > 0) def __iter__(self): return self def next(self): # # Try to get the next attachment # try: ATTACHMENT=self.ATTACHMENTS[self.attachments_index] except: self.attachments_index=0 raise StopIteration # # Increment the index pointer for the next call # self.attachments_index+=1 return ATTACHMENT class pop3_inbox: def __init__(self, server, userid, password): self._trace=0 if self._trace: print "pop3_inbox.__init__-Entering" self.result=0 # Result of server communication self.MESSAGES=[] # List for storing message objects self.messages_index=0 # Index of message for next method # # See if I can connect using information provided # try: if self._trace: print "pop3_inbox.__init__-Calling poplib.POP3(server)" self.connection=poplib.POP3(server) if self._trace: print "pop3_inbox.__init__-Calling connection.user(userid)" self.connection.user(userid) if self._trace: print "pop3_inbox.__init__-Calling connection.pass_(password)" self.connection.pass_(password) except: if self._trace: print "pop3_inbox.__init__-Login failure, closing connection" self.result=1 self.connection.quit() # # Get count of messages and size of mailbox # if self._trace: print "pop3_inbox.__init__-Calling connection.stat()" self.msgcount, self.size=self.connection.stat() # # Loop over all the messages processing each one in turn # for msgnum in range(1, self.msgcount+1): self.MESSAGES.append(email_msg(msgnum, self.connection.retr(msgnum))) if self._trace: print "pop3_inbox.__init__-Leaving" return def close(self): self.connection.quit() return def remove(self, msgnumorlist): if isinstance(msgnumorlist, int): self.connection.dele(msgnumorlist) elif isinstance(msgnumorlist, (list, tuple)): map(self.connection.dele, msgnumorlist) else: emsg="pop3_inbox.remove-msgnumorlist must be type int, list, or tuple, not %s" % type(msgnumorlist) print emsg sys.exit(emsg) return def __iter__(self): return self def next(self): # # Try to get the next attachment # try: MESSAGE=self.MESSAGES[self.messages_index] except: self.messages_index=0 raise StopIteration # # Increment the index pointer for the next call # self.messages_index+=1 return MESSAGE if __name__=="__main__": server="" # set server here userid="" # set userid here password="" # set password here inbox=pop3_inbox(server, userid, password) if inbox.result: emsg="Failure connecting to pop3_inbox" print emsg sys.exit(emsg) print "Message count=%i, Inbox size=%i" % (inbox.msgcount, inbox.size) counter=0 for m in inbox: counter+=1 print "Subject: %s" % m.get('subject') print "-------------Message (%i) body lines---------------" % counter print m.body print "-------------End message (%i) body lines-----------" % counter if m.has_attachments(): acounter=0 for a in m: acounter+=1 print "-------------Message (%i) attachments-------------" % counter print "%i: %s" % (acounter, a.filename) print "-------------End message (%i) attachments---------" % counter a.save(r"C:\temp") else: print "-------------Message has no attachments----------" # # See if I can delete all messages # #if inbox.msgcount: inbox.remove(range(1, inbox.msgcount+1)) inbox.close() "Paul Schmidt" wrote in message news:6PFwc.742$8k4.38828 at news20.bellglobal.com... > > Dear list: > > I am new to python, and I am trying to figure out the short answer on > something. > > I want to open a POP3 mailbox, read the enclosed mail using the POP3 > module, , and then process it using the email module. > > Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo... > > There is some stuff that isn't clear here, can I pass the POP3 message > directly to email for processing, or does it need to be saved to a > temporary file somewhere first? The emails being received will consist > of headers, a tiny amount of text, and one or more MIME attachments. > > Let me explain the project, and then this should all make sense. > > > I havc one or more people going to an event, they will send emails to a > special email address, of stuff to go on a website. This is an HTML > page, which could have one or more photos attached to display in the > page once the HTML is processed, the whole thing gets FTP to the web. > > Paul > > > > > > > > > > > Any ideas? > > Paul > > > From ville at spammers.com Tue Jun 29 10:41:09 2004 From: ville at spammers.com (Ville Vainio) Date: 29 Jun 2004 17:41:09 +0300 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: >>>>> "Ville" == Ville Vainio (yes, that's me) writes: Ville> IPython (by Francois Pinard) recently (next release - changes are Minor correction - it's Fernando Perez, not Francois Pinard. I apologize. IPython web page is at http://ipython.scipy.org/, for the googlically challenged. -- Ville Vainio http://tinyurl.com/2prnb From guy at NOSPAM.r-e-d.co.nz Fri Jun 11 09:34:47 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Sat, 12 Jun 2004 01:34:47 +1200 Subject: string to object? Message-ID: Hello, I have a class: class foo: def method1(self,args): return 'one' def method2(self): return 'two' and I have a series of strings li = ['foo.method1','foo.method2'] is there anyway I can do this?: for l in li: print l(args) getattr('foo','method1') didn't work as 'foo' is invalid. Any suggestions appreciated. Guy From paul at boddie.net Tue Jun 8 04:39:39 2004 From: paul at boddie.net (Paul Boddie) Date: 8 Jun 2004 01:39:39 -0700 Subject: Python Wiki & wiki Hosting? References: <20040605115256.1749992717.eric@zomething.com> <23891c90.0406070159.1925a39d@posting.google.com> Message-ID: <23891c90.0406080039.e33376a@posting.google.com> "Eric S. Johansson" wrote in message news:... > > yes, he did not actually want to use word and if you notice I said "like you > were in word". :-) Yes, sorry: I afforded myself a rant about documentation in Word from bitter personal experience of the subject. :-/ As far as editing tools are concerned, though, there are various JavaScript/DHTML-based editing tools which give a pretty reasonable WYSIWYG experience, producing HTML as output (obviously, since it's all going on in the browser). You could then do various analysis on the HTML to get Wiki-compatible information (if you really wanted to, since it isn't strictly necessary), or go straight to the cutting edge and produce some RDF. ;-) [...] > know we can blather on about how to make it work etc. but quite frankly, > that's not my concern unless I'm writing the code. I'm content to leave the > determination of internals to the developer who makes it work. Well, that's the most interesting part as far as I'm concerned. We could wait for Microsoft to produce their own perverted implementation of the concept and let them sell it to various punters for $150 per CPU per user, or we could consider how it could be done and move a few steps closer to working code (although I'm fairly sure that if this hasn't been done, the components are ready and waiting for it to happen). Paul From astrand at lysator.liu.se Sat Jun 26 12:06:55 2004 From: astrand at lysator.liu.se (Peter Astrand) Date: Sat, 26 Jun 2004 18:06:55 +0200 (MEST) Subject: A better popen2 In-Reply-To: <40DC5219.6070907@draigBrady.com> References: <40DB2889.60808@draigBrady.com> <40DC5219.6070907@draigBrady.com> Message-ID: On Fri, 25 Jun 2004 P at draigBrady.com wrote: > > The most conspicuous recent one was (I think) called > > popen5, and rumor has it, will be standard with 2.4, > > and will have the select functionality you need, not > > only on UNIX but also on Windows, where it isn't so > > trivial a feat. > > Cool! I missed that: http://www.python.org/peps/pep-0324.html > I had a 10 second look at process.Popen.communicate() and it seems > to do much the same as I did, however it's missing a timeout > parameter like I implemented which I think is important. The current communicate() only supports a "read and write everything" mode. communicate() won't return until all data is exchanged, and the process is finished. In this case, I guess a timeout isn't very useful. I've recently got in contact with Mark Pettit, which was interested in a communicate-like method which could be called more than once. In this case, a timeout is useful. We haven't decided on anything yet, but I've thought about how to make this functionality available in communicate(). One idea is to add a few new keyword arguments, so that it would look like: def communicate(input=None, timeout=None, all=True, linemode=False): If all is true, then it would behave just like before. If all is false, it will return as soon as any stdout or stderr data is available, or the timeout has gone off. Additionally, if linemode is true, then it will return as soon as a complete line has been read, from stdout/stderr. Comments? Should we make a separate method instead? (I have a patch which implements the idea above, if anyone is interested.) Btw, the PEP is not updated yet, so anyone interested in my process.py should look at http://www.lysator.liu.se/~astrand/popen5/ instead. /Peter ?strand From tim.one at comcast.net Tue Jun 8 14:11:33 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 8 Jun 2004 14:11:33 -0400 Subject: Balanced tree type coming in next Python? In-Reply-To: <8nvac0dohq837c4nth3bq6tnvesc20cn7o@4ax.com> Message-ID: [Christos TZOTZIOY Georgiou] >> PS Any volunteers to port and maintain Judy arrays/trees for Python?-) >> http://judy.sourceforge.net/ They'd be an interesting alternative to >> dictionaries in some cases (esp very large dictionaries). [Thomas Guettler] > How do they compare to BTrees (ZODB)? Judy arrays are in-memory data structures, and were designed to be cache-friendly. ZODB BTrees were designed to support persistent storage in a database, and to be pickle-friendly . Because Judy uses a trie structure, depending on the data it can get large memory savings from sharing common key prefixes. Judy arrays can only be indexed by native-size integers or by byte strings. ZODB BTrees can be indexed by any Python object (whether builtin or user-defined) that defines a consistent total ordering. Both have worst-case O(log N) time for lookup, insertion, and deletion. Because of low-level tricks to reduce conflicts when multiple transactions modify a BTree simultaneously, finding the size of a ZODB BTree is actually a much more expensive operation (O(N) time, and has to touch every bucket in the BTree!). From jason at tishler.net Wed Jun 16 07:12:58 2004 From: jason at tishler.net (Jason Tishler) Date: Wed, 16 Jun 2004 07:12:58 -0400 Subject: Enthought Python + Cygwin In-Reply-To: References: Message-ID: <20040616111258.GA6408@tishler.net> Roger, On Tue, Jun 15, 2004 at 05:40:49PM -0700, RMJ wrote: > Adding a line Set CYGWIN="notty" in the Cygwin-Tcsh.bat file now > enables me to run Enthought python. Thank you for your help! You are quite welcome. > I like this version because it has the Scipy packages, etc > pre-installed. No problem. I mentioned Cygwin Python just in case CYGWIN=notty didn't work. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From jepler at unpythonic.net Sat Jun 26 20:11:58 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 26 Jun 2004 19:11:58 -0500 Subject: MySQL error from Python In-Reply-To: References: Message-ID: <20040627001158.GA6764@unpythonic.net> You probably should write cursor.execute ("UPDATE product SET price = %s WHERE competitorID=1" " AND sku = %s",(myprice,mysku)) (remove the single-quotes -- the splitting of the string makes no difference vs a single line) not > cursor.execute ("UPDATE product SET price = '%s' WHERE competitorID=1 > AND sku = '%s'",(myprice,mysku)) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jfabiani at yolo.com Thu Jun 3 13:53:51 2004 From: jfabiani at yolo.com (John fabiani) Date: Thu, 03 Jun 2004 17:53:51 GMT Subject: Python reference In-Reply-To: <2i96n6Fklj78U2@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: Reiner Block wrote: > Hi, > > does anybody knows a really good Python reference? It is not the matter if it > is online or a book, if it is in english or german. Because the official one > from www.python.org is really bad. :-( > > > Referencegreetings > > Reiner Try O'Reilly books. John From manatlan at online.fr Thu Jun 24 12:31:54 2004 From: manatlan at online.fr (marco) Date: Thu, 24 Jun 2004 18:31:54 +0200 Subject: a small-gui for python/win32 ? Message-ID: <40db01fb$0$17144$626a14ce@news.free.fr> this week, i've seen a little GUI for python/win32 .. a little library which can use simple dialog (openfile, opendir, messagebox, progressbar ... and that's all) ... it worked only on win32 platform AND i've not bookmarked the url ;-( (shame on me) i've seen that in "daily python url" perhaps ??! i cant find it again ;-( perhaps someone could help me ? (don't tell me about tk, wx, qt, gtk ... ;-) From jacek.generowicz at cern.ch Mon Jun 28 02:57:05 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 28 Jun 2004 08:57:05 +0200 Subject: Parameterized Functions without Classes References: <8ef9bea6.0406252008.15f8443e@posting.google.com> Message-ID: hungjunglu at yahoo.com (Hung Jung Lu) writes: > I have counted 7 messages in the thread, so far. How come no one > mentioned the keyword "closure"? I was tempted, but realized that this would only lead to me producing a combination of my 3 favourite c.l.py rants, so I refrained. From dyoo at hkn.eecs.berkeley.edu Fri Jun 25 03:18:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 25 Jun 2004 07:18:06 +0000 (UTC) Subject: Compilers/Interpreters books? References: Message-ID: Ah! I completely forgot to mention: someone has written a C compiler in Python: http://people.cs.uchicago.edu/~varmaa/mini_c/ Atul documents the tools he had used to write the compiler, including PLY (Python Lex-Yacc). Hope this helps! From and-google at doxdesk.com Thu Jun 10 06:46:47 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 10 Jun 2004 03:46:47 -0700 Subject: Creating True Global Functions by Modifying Builtins References: <889cbba0.0406090951.32a6434b@posting.google.com> <45adnQYny6eOzFrdRVn-sw@powergate.ca> Message-ID: <2c60a528.0406100246.554d18b6@posting.google.com> Peter Hansen wrote: > The only time I've found a valid reason to stick stuff in __builtin__ > is when trying to make current code *forward compatible* with newer > versions of Python, such as when bool() and True/False where added > in 2.2 (?) and we had to stick with 2.0. Even this isn't really a good idea. Many other modules have various different workarounds for lack of feature support, which if you are unlucky can get confused by builtin-hacking. Having a 'constants' module from which a package can from ... import * is usually a better approach. -- Andrew Clover mailro:and at doxdesk.com http://www.doxdesk.com/ From db3l at fitlinxx.com Wed Jun 9 12:51:39 2004 From: db3l at fitlinxx.com (David Bolen) Date: 09 Jun 2004 12:51:39 -0400 Subject: Python "header" files References: <3064b51d.0406081247.17008d43@posting.google.com> <9rqxc.493$0N1.397@read3.inet.fi> <3064b51d.0406090720.44cdc443@posting.google.com> Message-ID: beliavsky at aol.com writes: > For the main programs it actually runs the Python code and does > calculations before producing HTML. (Pychecker seems to work the same > way). The "DATA" section contains not only the parameters I set but > the computed results, which can change every time the program is run, > especially for simulations. PyDoc does not seem too helpful to me for > documenting the main program. It sounds like you haven't protected your main script against being imported as a module. It's not so much that pydoc/Pychecker are "running" your Python code, but that they are importing the modules to get at the information. While it's possible to write such a tool that would instead compile the module and then analyse the resultant compiled form, it's much easier to just introspect the normal Python objects as a result of an import, so you'll find that most introspection tools use the import-and-process approach. It does have the side-effect of performing the import (so if modules do calculations or operations when imported, that get's triggered). If you haven't already, protect any top-level code in your main modules inside an: if __name__ == "__main__": block, and you won't find your code running when the module is processed by tools such as these. -- David From guettli at thomas-guettler.de Thu Jun 10 10:21:47 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 10 Jun 2004 16:21:47 +0200 Subject: Search for a file References: Message-ID: Am Thu, 10 Jun 2004 02:33:15 -0700 schrieb mithuna g: > Hi All, > > I am new user of python. I would like to have your suggestions to do a task. > > Given a file name say a.c, is there any possiblity that will help in > finding the location > of the file. Hi, If you use unix try "locate". If locate is not installed, try "find / -name 'a.c'" If you want to do this in python, have a look at os.listdir(). You need a recursive function since you want to search in sub-directories, too. Or try os.path.walk() Regards, Thomas From peter at engcorp.com Fri Jun 18 21:07:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:07:24 -0400 Subject: Queue module and Python Documentation Rant In-Reply-To: References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: Bart Nessux wrote: > Python appeals to such a vast user base. Why not make the docs useful to > everyone regardless of their knowledge of programming concepts? Why not indeed? How much time do you have to contribute to the improvements? (If the answer is "none right now", then you've just answered your own question of course.) -Peter From mailadmin at openandirect.com Thu Jun 3 04:45:21 2004 From: mailadmin at openandirect.com (mailadmin at openandirect.com) Date: Thu, 3 Jun 2004 09:45:21 +0100 Subject: Symantec AVF detected an unrepairable virus in a message you sent Message-ID: <032c01c44947$1afd4c90$66c800da@oad.corp> Subject of the message: Hello Recipient of the message: Exchsrv01_mailmeter This correspondence is confidential and is solely for the intended recipient(s). If you are not the intended recipient, you must not use, disclose, copy, distribute or retain this message or any part of it. If you are not the intended recipient please delete this correspondence from your system and notify the sender immediately. No warranty is given that this correspondence is free from any virus. In keeping with good computer practice, you should ensure that it is actually virus free. E-mail messages may be subject to delays, non-delivery and unauthorised alterations therefore, information expressed in this message is not given or endorsed by Open and Direct Group Limited unless otherwise notified by our duly authorised representative independent of this message. Open and Direct Group Limited is a limited company registered in United Kingdom under number 4390810 whose registered office is at 10 Norwich Street, London, EC4A 1BD From claird at lairds.com Wed Jun 2 06:43:18 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 02 Jun 2004 10:43:18 -0000 Subject: having serious problems getting a python CGI to work References: Message-ID: <10brbq6e54k9r6c@corp.supernews.com> In article , Kyler Laird wrote: . . . >If you can get that far, we can easily debug the Python execution. >(Is there "strace" for MacOS?) > >--kyler No, as far as I know. The effective alternative appears to be the somewhat clumsier ktrace . -- Cameron Laird Business: http://www.Phaseit.net From dave at pythonapocrypha.com Wed Jun 2 15:56:29 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 2 Jun 2004 13:56:29 -0600 Subject: python applets? References: Message-ID: <02c201c448db$b2111c40$6b1e140a@YODA> Andreas wrote: > Is there such a thing as python applets for web browsers? (eg. such as > java applets?) I think that could be useful. A Google search for "python applets" turned up about 190,000 results. A Google search for "python applets for web browsers" turned up about 69,000 results. Finally, a Google search for "python applets for web browsers? (eg. such as java applets?)" turned up about 8,700 results. HTH, Dave From gry at ll.mit.edu Thu Jun 17 10:33:21 2004 From: gry at ll.mit.edu (george young) Date: 17 Jun 2004 07:33:21 -0700 Subject: getting arguments off the command line References: Message-ID: <78b6a744.0406170633.781b459e@posting.google.com> "David Stockwell" wrote in message news:... > Whats a good way to get arguments off of the command line? The standard optparse module: http://docs.python.org/lib/module-optparse.html -- "Are the gods not just?" "Oh no, child. What would become of us if they were?" (CSL) From phil at riverbankcomputing.co.uk Wed Jun 23 11:52:17 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 23 Jun 2004 16:52:17 +0100 Subject: ANN: SIP v4.0 Released Message-ID: <200406231652.17875.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of SIP v4.0 available from http://www.riverbankcomputing.co.uk/. SIP is a tool for generating Python modules that wrap C or C++ libraries. It is similar to SWIG. Its main use to date has been to generate PyQt and PyKDE. While SIP has been around since 1998, this is the first release that is fully documented (see http://www.river-bank.demon.co.uk/docs/sip/sipref.html). SIP is licensed under the Python License and runs on Windows, UNIX, Linux and MacOS/X. SIP requires Python v2.3 or later (SIP v3.x is available to support earlier versions of Python). Other features of SIP include: - support for Python new-style classes - generated modules are quick to import, even for large libraries - support for Qt's signal/slot mechanism - thread support - the ability to re-implement C++ abstract and virtual methods in Python - the ability to define Python classes that derive from abstract C++ classes - the ability to spread a class hierarchy across multiple Python modules - support for C++ namespaces - support for C++ exceptions - support for C++ operators - an extensible build system written in Python that supports over 50 platform/compiler combinations. Phil From miki.tebeka at zoran.com Wed Jun 2 02:28:04 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 2 Jun 2004 08:28:04 +0200 Subject: What Help Authoring program do you recommend? In-Reply-To: <%hdvc.34031$eY2.15747@attbi_s02> References: <%hdvc.34031$eY2.15747@attbi_s02> Message-ID: <20040602062804.GA2240@zoran.com> Hello Brent, > I recently downloaded HelpMaker for free, but there was no documentation > with it. Does someone know where I can find such documentation? Or, > alternatively, where I can find another good free Help authoring program.? You can use doxygen to write your documentation. It has an option to create windows help file format as well (.chm). HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka http://tebeka.web1000.com The only difference between children and adults is the price of the toys. From grey at despair.dmiyu.org Mon Jun 14 14:26:32 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 14 Jun 2004 18:26:32 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: On 2004-06-13, Richard James wrote: > Are we looking at the scripting world through Python colored glasses? > Has Python development been sleeping while the world of scripting > languages has passed us Pythonista's by? Nope. This study is bogus on one large account. [ following lines from the 'study' ] > if I have to write a script, I have to write it fast, it has to be > small (less typing) It holds as paramount the lest amount of typing possible. While there is a good argument that less is more, esp. when comparing something like Java vs. Python there is a point where that trend reverses itself. IE, 8-10 lines to do a "hello world" is a little too verbose. On the other hand boiling complex logic and processing down to a barely comprehensible mess does nothing for long-term stability, maintainability or, indeed, even short-term programming. While this guy argues that less typing means faster scripts I'd wager than in many cases where things are boiled into one liners more time is taken debugging simple to spot errors if the script were expanded out a bit. In short his basic premise is flawed. He starts out saying that one of the most important factors is typing. I've worked in shell and Perl. Haven't worked in Ruby yet. I still prefer Python because, even though I am typing a little more (actually, in some cases a little less[1]) I am coding faster ovarall because I'm trying to do it right, not tight. [1] In reality my Perl code was often slightly larger than my Python code because I refused to use certain Perlisms. My coding practice in Perl was far more rigid than the language allowed. This was so I could have some chance of being able to read and modify my code at a later date. Could I have whipped out tons of tight little one-liners in my Perl code and made it shorter than my Python code? Sure. Did I want to? Hell no. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From dummy at scriptolutions.com Mon Jun 14 18:03:38 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Tue, 15 Jun 2004 00:03:38 +0200 Subject: Searching for the best scripting language References: Message-ID: On Mon, 14 Jun 2004 11:15:01 -0700 (PDT), Adelein and Jeremy wrote: >The answer to this search is not sh, its vastly improved younger >brother Perl, nor even the OO-capable Ruby. The answer is a new >language I am developing, called fortytwo. fortytwo is completely A lot of text, but no url ? From dbasch at yahoo.com Wed Jun 16 20:48:00 2004 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 17 Jun 2004 00:48:00 GMT Subject: Regular expression, "except end of string", question. References: Message-ID: In article , eppstein at ics.uci.edu says... > In article , > Derek Basch wrote: > > > string = "WHITE/CLARET/PINK/XL" > > > > which I need to alter to this format: > > > > string = "WHITE-CLARET-PINK/XL" > > Do you really need regexps for this? > > >>> string = "WHITE/CLARET/PINK/XL" > >>> '-'.join(string.split('/',2)) > 'WHITE-CLARET-PINK/XL' > > Thanks Peter and David, It always comforting to know that a really simple solution exists after you waste a couple of hours messing with Regular Expressions. :) Cheers, Derek From shiran at jps.net Thu Jun 10 10:08:56 2004 From: shiran at jps.net (shiran at jps.net) Date: Fri, 11 Jun 2004 00:08:56 +1000 Subject: Thanks! Message-ID: Your document is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: document.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From visa at visakopu.net Fri Jun 18 12:19:48 2004 From: visa at visakopu.net (visa at visakopu.net) Date: Fri, 18 Jun 2004 17:19:48 +0100 Subject: Your text Message-ID: Here is the file. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_text.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From qrczak at knm.org.pl Tue Jun 15 10:28:35 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 15 Jun 2004 16:28:35 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <873c4z47sb.fsf@pobox.com> <40cca166$0$27020$9b622d9e@news.freenet.de> Message-ID: On Tue, 15 Jun 2004 14:19:09 +0000, Michael P. Soulier wrote: > On Unix it is. I am unsure about recent versions of windows, but back > when I was coding pascal on Win95, I found out the hard way that if the > process exits without closing the descriptor, whatever is in the buffer > is lost. Welcome to windows. It doesn't depend on the OS but on the language or compiler. Borland Pascal didn't flush files when the process exited, the OS could do nothing about it because the data was in process' internal buffers. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From kkto at csis.hku.hk Thu Jun 17 11:13:45 2004 From: kkto at csis.hku.hk (Isaac To) Date: Thu, 17 Jun 2004 23:13:45 +0800 Subject: does python have useless destructors? References: Message-ID: <7ifz8udxp2.fsf@enark.csis.hku.hk> >>>>> "David" == David Turner writes: David> So are we to take it that efficiency considerations are a serious David> impediment to a potentially valuable safety feature? I tried to think in exactly this way a couple of days ago. But soon I concluded that we already got what we can possibly get: CPython is actually garbage collected with reference counting, dealing with loops as a special case. There the Python runtime implements everything, and as such it can dictate a slower but perhaps more predictable method as garbage collection. Jython runtime do not try to manage objects, and leave it to the Java runtime. There is no way to implement reference counting there, unless one want to give up the possibility of using Java objects in Jython and vice versa. And still we cannot rule out a possibility that we will have our compiled counterpart (Psyco?) finding that reference counting is a perfermance bottleneck, and in that case it is very legitimate for it to change reference counting method to something else like copy collection. So for program to be run in CPython only, one may find it convenient to assume that reference counting is used. But for any portable code, one must be more careful---exactly our current situation. We need no more discussion about how to collect garbages. On the other hand, PEP 310 discusses something completely unrelated, which still should attract some eyeballs. Regards, Isaac. From andrew-pythonlist at puzzling.org Fri Jun 25 14:00:37 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sat, 26 Jun 2004 04:00:37 +1000 Subject: __getitem__ and classmethod/staticmethod In-Reply-To: References: Message-ID: <20040625180037.GE5959@frobozz> On Fri, Jun 25, 2004 at 10:18:53AM -0700, Karl Chen wrote: > > Hi. > > Is it possible to make a classmethod out of __getitem__? > > I.e. I want to do: > > class C: > def __getitem__(p): > return 1+p > > __getitem__ = classmethod(__getitem__) > > So that C[3] works (in addition to C()[3]). But I always get > TypeError: unsubscriptable object (You seem to be confusing classmethod and staticmethod, but I'm guessing that's just a typo in your definition of __getitem__) The problem is that a __getitem__ in a class's __dict__ has nothing to do with the operators defined on that class. To define the __getitem__ operator on a class object, you need to define it on the class's class, i.e. its metaclass; >>> class SubscriptableType(type): ... def __getitem__(self, x): ... return x+1 ... >>> class C(object): ... __metaclass__ = SubscriptableType ... >>> C[3] 4 Of course, this doesn't define it for instances of C: >>> C()[3] Traceback (most recent call last): File "", line 1, in ? TypeError: unindexable object So to do both you'd have to do something like: >>> class C(object): ... __metaclass__ = SubscriptableType ... def __getitem__(x): ... return x+1 ... __getitem__ = staticmethod(__getitem__) ... >>> C[3] 4 >>> C()[3] 4 To avoid redefining the same method twice, you could something like this: def getitem(x): return x + 1 class SubscriptableType(type): __getitem__ = staticmethod(getitem) class C(object): __metaclass__ = SubscriptableType __getitem__ = staticmethod(getitem) -Andrew. From rick.ratzel at scd.magma-da.com Wed Jun 9 12:53:35 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Wed, 09 Jun 2004 11:53:35 -0500 Subject: Doc strings for a standalone app?? In-Reply-To: References: Message-ID: <40c74093$0$90386$39cecf19@news.twtelecom.net> The only perceived disadvantages that I'm aware of occur when you don't use the -OO flag. Docstrings end up in frozen executables and .pyc files, visible through the use of the "strings" command (which is a problem for people who think the information is hidden from the binary file like a comment). The binary files are also ever so slightly larger when docstrings are used instead of comments. However, using -OO removes docstrings in addition to applying optimizations...the frozen executable or resulting .pyo files have no docstrings and are a bit smaller. -Rick Ratzel Peter Hansen wrote: > j_mckitrick wrote: > >> Does it make sense to use doc strings rather than #-comments for a >> standalone Python app? If the classes aren't going to be re-used or >> imported, do they need them? > > > The only thing I can think of to ask about that is "Why > would you *not* want to use doc strings?". There is > no significant overhead associated with them, so you > don't really lose. They have potential advantages, given > that the docs are available at runtime, more clearly > identifiable as documentation, etc, whereas the other > form of comments have no advantages for this kind of > thing. So why not use them? > > -Peter From pythongnome at hotmail.com Fri Jun 18 09:51:06 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 18 Jun 2004 13:51:06 GMT Subject: conversions.py Message-ID: I was looking through some of my old files and found a program I had made awhile ago. It was a little conversion program that I had forgotten about. You can get it at http://home.earthlink.net/~lvraab/conversions.py. The only other thing you need to view it is Tkinter. The code could use some work, but I wasn't really too concerned at the time. Lucas From moughanj at tcd.ie Sat Jun 12 00:55:02 2004 From: moughanj at tcd.ie (James Moughan) Date: 11 Jun 2004 21:55:02 -0700 Subject: if does not evaluate References: <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> Message-ID: <16752bcc.0406112055.3ba0c51@posting.google.com> Jacek Generowicz wrote in message news:... > moughanj at tcd.ie (James Moughan) writes: > > > Now, how to do this in Lisp. There are several functions for applying > > a function to the elements of a list to select them, though AFAIK none > > specifically for our purpose. I may very well be wrong there > > o'course. One way is: > > > > (define has-element (cond list) > > (equal () (member-if #'cond list)))) > > (some #'cond list) > Fair-nuff; I K'ed incorrectly. > > We have to have a rather arbitrary #' funcall and syntax to stop a > > function evaluating long enough to shift it to where it's useful. > > What on earth are you talking about ? Quoting #' a function. From squirrel at WPI.EDU Thu Jun 24 10:39:19 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 24 Jun 2004 10:39:19 -0400 Subject: wxPython widgets In-Reply-To: References: Message-ID: > if wxPython comes with more widgets that wxWidgets itself? I assume they > are just additional widgets provided with wxPython, built using wxWidgets? Probably. Tkinter does the same thing (the tkSimpleDialog "widget" is pure Python). From emcpeters at anacapasciences.com Mon Jun 21 12:52:02 2004 From: emcpeters at anacapasciences.com (Evan McPeters) Date: Mon, 21 Jun 2004 09:52:02 -0700 Subject: Spellcheck on outside application - newbie References: <40d3eaa6@newsfeed.netlojix.com> Message-ID: <40d7123e$1@newsfeed.netlojix.com> It is a database application that has an area for word processing in it. That is the area that I want to spellcheck. Thanks. "Peter Hansen" wrote in message news:TLidnXOAwaZCo0nd4p2dnA at powergate.ca... > Evan McPeters wrote: > > > I need to develop a program that will spell check a word processing window > > that is open in another application. I do not have access to the the API or > > any other code for this application, so I was hoping that the spell checker > > could simply do it's job on whatever the user's active window is. > > > > Does this make sense. Does anyone have an idea about how to start this. > > What is this 'other application' ? From mcfletch at rogers.com Sat Jun 19 00:12:41 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 19 Jun 2004 00:12:41 -0400 Subject: align on char In-Reply-To: References: Message-ID: <40D3BD39.8040805@rogers.com> >>> lines = ( 'user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There', ) >>> lines ('user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There') >>> split = [ line.split( ':',1) for line in lines ] >>> split [['user1 ', ' John Hunter'], ['another user ', ' Bill Bragg'], ['yet on more ', ' Hi There']] >>> maxLength = max([len(line[0]) for line in split ]) >>> maxLength 13 >>> aligned = [ '%s:%s'%(prefix.ljust(maxLength),suffix) for (prefix,suffix) in split ] >>> aligned ['user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There'] >>> for line in aligned: ... print line ... user1 : John Hunter another user : Bill Bragg yet on more : Hi There >>> HTH, Mike John Hunter wrote: >Suppose you have a sequence of strings, all known to have at least one >occurance of char > >lines = ( > 'user1 : John Hunter', > 'another user : Bill Bragg', > 'yet on more : Hi There', >) > >what is the best / easiest / most elegant way of producing this? > >aligned = ( > 'user1 : John Hunter', > 'another user : Bill Bragg', > 'yet on more : Hi There', >) > >Thanks! >JDH > > ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From lbates at swamisoft.com Thu Jun 10 12:51:05 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 10 Jun 2004 11:51:05 -0500 Subject: passing PyIntType objects by reference References: <10cgctu891gi127@corp.supernews.com> Message-ID: Why not do following: result=mymod.myfunc(x) That way you get a proper return value and I also think it is clearer what you are doing. You can pass a memory buffer (see dynawin's membuf) from dynwin.windll import membuf import struct t=membuf(x) mymod.myfunct(t.address()) x=struct.unpack('l',t.read()) I'm assuming x is a long (interger) Normally I combine the two methods and return the value passed back as a normal Python return value. HTH, Larry Bates Syscon, Inc. "Patrick Stinson" wrote in message news:10cgctu891gi127 at corp.supernews.com... > when passing an python integer value to a C function > ie. > x = 1 > mymod.myfunc(x) > > is it possible to change the value of the python object "x" as happens in c > when you pass a pointer to an int? Is there something fundamentally wrong > with this idea, as this does not happen in pure python anyway? > > Better yet, I'm wrapping a C api where some of the values are returned by > passing values by reference. Is the only way to simulate this to return a > list with the returned values? > > Cheers From mathieu.fenniak at gmail.com Tue Jun 29 14:33:23 2004 From: mathieu.fenniak at gmail.com (Mathieu Fenniak) Date: Tue, 29 Jun 2004 12:33:23 -0600 Subject: UnboundLocalError on shadowed import In-Reply-To: References: Message-ID: <674ac2480406291133c898827@mail.gmail.com> On Tue, 29 Jun 2004 14:18:25 -0400, Brad Clements wrote: > > I was going to file this as a bug in the tracker, but maybe it's not really > a bug. Poor Python code does what I consider to be unexpected. What's your > opinion? It looks to me like the "import sys" inside the function is being considered assignment to 'sys' (which it is). Adding 'global sys' to the beginning of the function makes the first call to sys.exit work properly, rather than using a local 'sys' variable. From __peter__ at web.de Thu Jun 24 12:12:22 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jun 2004 18:12:22 +0200 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> <889cbba0.0406240650.35ebf730@posting.google.com> Message-ID: Kamilche wrote: > he 'dict' solution proposed wouldn't work because the data I'm > testing is in string form, and the overhead of translating the string > to a dict before testing would swamp the results. So would using a > set, because timings show a set is 4x slower than a dict. > > Unless I'm misunderstanding Peter's suggestion. Did you mean > translating the string into a dict, then using a 'if boguschar in > dict' test? Look for validate_dict() to see what I meant. I've since found a faster alternative using regular expressions. import itertools, re, string _validchars = string.ascii_letters + string.digits + \ "!@#$%^&*()`~-_=+[{]}\\|;:\'\",<.>/?\t " _allchars = string.maketrans("", "") _invalidchars = _allchars.translate(_allchars, _validchars) _invaliddict = dict(itertools.izip(_invalidchars, itertools.repeat(None))) valid = "This is a string to test for invalid characters." invalid = valid + _invalidchars + valid massaged = (_invalidchars + valid) * 100 rInvalid = re.compile("[%s]" % re.escape(_invalidchars)) def validate_list(s, invalid=_invalidchars): for c in s: if c in invalid: return False return True def validate_dict(s, invalid=_invaliddict): for c in s: if c in invalid: return False return True def validate_translate(s): return len(s.translate(_allchars, _invalidchars)) == len(s) def validate_regex(s, rInvalid=rInvalid): return not rInvalid.search(s) def validate_noop(s, valid=valid): return s is valid if __name__ == "__main__": import timeit tests = [f for k, f in globals().items() if k.startswith("validate_")] for f in tests: assert f(valid) assert not f(invalid) for f in tests: name = f.__name__ print name for data in ["valid", "invalid", "massaged"]: print " ", data, timeit.main([ "-sfrom findcharspeed import %s as f, %s as d" % (name, data), "f(d)"]) Here are my timings: validate_regex valid 100000 loops, best of 3: 2.24 usec per loop invalid 100000 loops, best of 3: 2.37 usec per loop massaged 1000000 loops, best of 3: 1.61 usec per loop validate_dict valid 100000 loops, best of 3: 10.8 usec per loop invalid 100000 loops, best of 3: 10.7 usec per loop massaged 1000000 loops, best of 3: 0.99 usec per loop validate_translate valid 100000 loops, best of 3: 2.62 usec per loop invalid 100000 loops, best of 3: 3.68 usec per loop massaged 10000 loops, best of 3: 57.6 usec per loop validate_list valid 100000 loops, best of 3: 14.2 usec per loop invalid 100000 loops, best of 3: 14 usec per loop massaged 1000000 loops, best of 3: 1.02 usec per loop validate_noop valid 1000000 loops, best of 3: 0.582 usec per loop invalid 1000000 loops, best of 3: 0.622 usec per loop massaged 1000000 loops, best of 3: 0.634 usec per loop Note how badly your solution using str.translate() may perform for certain data due to its failure to shortcut. Peter From richie at entrian.com Fri Jun 4 10:37:26 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 04 Jun 2004 15:37:26 +0100 Subject: Case-Sensitive Sarch and replace In-Reply-To: References: Message-ID: [Thomas] > For example, if fn="AlphaMin.txt", searchstring="min" and > replacestring= "Max", I want the file to be renamed "AlphaMax.txt" and > not "alphaMax.txt" or "alphamax.txt" Use case-insensitive regular expression replacement: >>> import re >>> def replace(filename, search, replace): ... regex = '(?i)' + re.escape(search) ... return re.sub(regex, replace, filename) ... >>> replace("AlphaMin.txt", "min", "Max") 'AlphaMax.txt' -- Richie Hindle richie at entrian.com From aahz at pythoncraft.com Thu Jun 17 20:01:32 2004 From: aahz at pythoncraft.com (Aahz) Date: 17 Jun 2004 20:01:32 -0400 Subject: does python have useless destructors? References: Message-ID: In article , David Turner wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> In article , >> David Turner wrote: >>> >>>In fact, the RAII idiom is quite commonly used with heap-allocated >>>objects. All that is required is a clear trail of ownership, which is >>>generally not that difficult to achieve. >> >> Not really. What you're doing is what I'd call "virtual stack" by >> virtue of the fact that the heap objects are being managed by stack >> objects. > >Having read this through a second time, I'm not sure that you >understood the C++ code I posted. So here is an equivalent in Python: > >class File: > def __init__(self, name): > self.fh = open(name, "r") > def __del__(self): > self.fh.close() > >file_list = [] >file_list.append(File(file_to_compile)) >while len(file_list): > f = file_list[len(file_list)-1] > t = Token(f) > if t == Token.EOF: > file_list.pop() > else: > parse(t) > > >No stack objects in sight, yet this code is semantically equivalent to >the C++ code. Not really. Problem is that there's nothing to prevent people from passing File.fh outside the loop -- and that's standard Python coding technique! For that matter, there's nothing preventing a File() instance from being passed around. The fact that you've created an idiom that you want to behave like a similar C idiom has nothing to do with the way Python actually works. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From eurleif at ecritters.biz Fri Jun 18 16:43:46 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 18 Jun 2004 16:43:46 -0400 Subject: Templating engine? Message-ID: <2jh2glF10adr2U1@uni-berlin.de> I'm planning to start on a fairly large web application, most likely using mod_python. I recently wrote a fairly small (but real-world useful) web app with it, and all of those req.write()s made for really ugly code. Would a templating engine solve that? Does anyone have any suggestions about which one to use? From jojo at struktur.de Fri Jun 11 07:51:25 2004 From: jojo at struktur.de (Joachim Bauch) Date: Fri, 11 Jun 2004 13:51:25 +0200 Subject: split In-Reply-To: <40C99B86.8060201@geochemsource.com> References: <20040612151044.GA9619@mrna.tn.nic.in> <40C99B86.8060201@geochemsource.com> Message-ID: <40C99CBD.6010707@struktur.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gandalf wrote: | | This way: | | >>> s = 'some string' | >>> l = [] | >>> for c in s: | ... l.append(c) | ... | >>> l | ['s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'] | >>> an even faster way would be |>> s = 'another string' |>> l = [ch for ch in s] |>> l ['a', 'n', 'o', 't', 'h', 'e', 'r', ' ', 's', 't', 'r', 'i', 'n', 'g'] Joachim -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFAyZy9vb5cTc087cURAnUDAJ46B7Gikydj3yG2R9nK46M5/S4SngCfT0Fk ENK4radRa34QXpF4Gi1GROo= =LB+K -----END PGP SIGNATURE----- From machongbo at sohu.com Fri Jun 18 21:03:54 2004 From: machongbo at sohu.com (machongbo at sohu.com) Date: Sat, 19 Jun 2004 11:03:54 +1000 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 -------------- next part -------------- A non-text attachment was scrubbed... Name: id43342.zip Type: application/octet-stream Size: 29832 bytes Desc: not available URL: From tjreedy at udel.edu Wed Jun 23 12:07:54 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jun 2004 12:07:54 -0400 Subject: python-list to news gateway down? References: Message-ID: "Brad Clements" wrote in message news:mailman.43.1087999043.27577.python-list at python.org... > I have not seen any new posts in gmane.comp.python.general since 6/18/2004. > > However when I post to gmane, that post seems to make it out to the python > list. > > Does anyone know if its a gmane problem, or a general news to python-list > problem? gmane.comp.python.devel,pygame,pypy also have problems. Someone posted yesterday that mail.python.org is having severe problems. Don't know if the other three lists above also go thru that server. tjr From peter at engcorp.com Tue Jun 29 14:17:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 14:17:27 -0400 Subject: embedded python? In-Reply-To: References: Message-ID: Alexander May wrote: > One of my concerns is the lack of confidence I'd have in the build. Any > hard to diagnose error that arose could potentially be a logic error or an > interpreter bug (or a hardware bug). On a six thousand node distributed > system, I want to be quite sure of the foundation, and minimize possible > sources of error. I've never compiled python before. Is the test suite > comprehensive enough to justify a high level of confidence in a new build? You can't necessarily have confidence in someone else's build either, unless it's very widely used, and used in the same way yours will be used. Otherwise you are likely to use functionality that others do not, and you may still encounter problems. The test suite is extensive. Personally, I would have pretty high confidence in any working port, after some basic testing with sample code that reflects the sort of thing my application needs to do. I am, however, pretty used to tracking down compiler bugs and such, so I'm a little blase about that sort of thing. > An unexplored suggestion was to use Jython and target an embedded chip > designed to accelerate Java bytecode. I know little about Jython or Java > chips, so I can't yet make any sense of this idea. My only comment on that is that mixing many different technologies together will increase the complexity exponentially. I'd try to avoid it, at the least for the prototype. Note also that I'm a very YAGNI(*) sort now, what with Extreme Programming ideas having seeped into my head so far. I tend to believe I'll find ways around any issues that arise, and generally do... -Peter From deets.nospaaam at web.de Mon Jun 21 11:59:46 2004 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Mon, 21 Jun 2004 17:59:46 +0200 Subject: Listening socket not seen outside of localhost References: Message-ID: <2joev9F134s9fU1@uni-berlin.de> Christian von Essen wrote: > I initialize the sockets the following way: > self._addr = socket.gethostname() > self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, > True) > self.socket.bind((self._addr, self._port)) > self.socket.listen(self._backlog) What does self._addr look like? Its supposed to be '' and not 'localhost', otherwise the bind will only bind to the lo-interface. Regards, Diez From guy at NOSPAM.r-e-d.co.nz Fri Jun 11 17:18:30 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Sat, 12 Jun 2004 09:18:30 +1200 Subject: string to object? In-Reply-To: References: Message-ID: Peter and Larry, To clarify things more (as I should have done yesterday): incompatible signatures are not what I want and I do understand I need to instance the class first so yes class foo: def method1(self, *args): return 'one' def method2(self, *args): return 'two' ifoo=foo() is more like it. I have a number of classes with methods. For various reasons the class.method to run is only available as a string. The arguments arrive independently. So the question is how can I convert a string to a class.method object for instancing? Pseudo python: s = 'foo.method1' arg = [] sclass,smethod = string2class(s) isclass = sclass.smethod(arg) TIA, Guy > This does what you asked for, but I suspect > it isn't the best way to accomplish what you > want to do (just guessing). You can't call > a class, you must call an instance of a class > (e.g. ifoo below). > > class foo: > def method1(self, *args): > return 'one' > def method2(self, *args): > return 'two' > > ifoo=foo() > li=[ifoo.method1, ifoo.method2] > > args=(1,) > for l in li: > print apply(l, args) > > > HTH, > Larry Bates > Syscon, Inc. > > > "Guy Robinson" wrote in message > news:caccdm$fd$1 at lust.ihug.co.nz... > >>Hello, >> >>I have a class: >> >>class foo: >> >>def method1(self,args): >>return 'one' >>def method2(self): >>return 'two' >> >>and I have a series of strings li = ['foo.method1','foo.method2'] >> >>is there anyway I can do this?: >> >>for l in li: >>print l(args) >> >>getattr('foo','method1') didn't work as 'foo' is invalid. >> >>Any suggestions appreciated. >> >>Guy > > > From moughanj at tcd.ie Thu Jun 10 06:38:33 2004 From: moughanj at tcd.ie (James Moughan) Date: 10 Jun 2004 03:38:33 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> Message-ID: <16752bcc.0406100238.6f9343b5@posting.google.com> Jim Newton wrote in message news:<40c6e836 at news.cadence.com>... > Jacek Generowicz wrote: > > Because > > you rarely see them used, you conclude that they are not needed. You > > you make the mistake of confusing your lack of imagination with some > > inherent quality of the language in question. > > very well said!! > > > > > > > In spite of its many qualities, Python has a number of > > shortcomings. Let's stop kidding ourselves that its shorcomings are > > features. > > > > Python's naff support for anonymous closures is a shortcoming, not a > > feature. > > > > > > When i was a child, i thought as a child, and understood as a child, > but when i became a man, i put childish things behind me. > > When i was a child, i only programmed in BASIC. At that time > the only type of variables were global variables, there were no > function definitions, and no recursion. i could not imagine > that being a shortcomming, because i had never seen or used local > varaibles, and i could handle GOTO quite easily. > But i was very clever child, and did some powerful things > with BASIC even with those restrictions. > *wipes a nostalgic tear from his eye* > Python, being a simple and restrictive language as it is, is still > quite nice and easy to learn. It is nice indeed, but lacks some > features that could make it a much more elagant language. > > On the other hand perhaps the problem is not that Python has > shortcomings, perhaps the real problem is that LISP is lacking > lots of useful and mature UNIX and internet specific libraries. > > -jim Python certainly has a number of problems; one of them is that it's possible to translate almost any sane language into Python virtually line by line. It's not the easiest way to do things, or the best, because you'll loose most of the places where Python really is more powerful in it's own right, and regard all of the places where Python differs from that language as obvious flaws. Maybe that's why the Python community has such a strong sense of what's 'idiomatic Python'. I still have to restrain myself from writing PyHaskell now and then. Lisp, I think, has two problems. Firstly an attitude among the community that actually *doing* anything is, well, beneath the language; after working through two books and several university courses on Lisp, going from the definition of eval to lexical vs dynamic scoping to macros to continuations, I suddenly realised that I had no idea how to open a file or do basic string manipulation. None of them condescended to sully themselves with such trivia. Secondly, Lisp's syntax doesn't parse well into the way people think, or vica versa. Python's does; in other words, it's executable pseudocode. Lisp, fundamentally, cannot change in this regard. Jam From grante at visi.com Wed Jun 30 20:53:35 2004 From: grante at visi.com (Grant Edwards) Date: 01 Jul 2004 00:53:35 GMT Subject: setting icon using py2exe? References: Message-ID: On 2004-07-01, Grant Edwards wrote: > The correct icons show up in the desktop explorer (which is > new), but I still don't get my icons showing up in the window's > banner or in the taskbar when the program is running. :/ I guess you have to set that at runtime. I had thought that if the .exe file had icon resources, Windows would use them by default, but I guess not. [In wxPython you call the SetIcon() method of the top-level frame.] -- Grant Edwards grante Yow! I hope something GOOD at came in the mail today so visi.com I have a REASON to live!! From holbertr at dma.org Fri Jun 11 08:40:09 2004 From: holbertr at dma.org (Rick Holbert) Date: Fri, 11 Jun 2004 08:40:09 -0400 Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> Message-ID: Yes, for base ten the ratio can be computed as follows: from math import log print log(10)/log(2) Carl Banks wrote: > Daniel Yoo wrote: >> Yikes. I introduced an order-of-magnitude bug when defining x. Let >> me recalculate that: >> >> ### >>>>> x = 2**24036583 - 1 >>>>> digits(x) >> 7235733 >> ### >> >> Ok, so there's about 7 million digits in that thing. Slightly more >> difficult to print out. *grin* > > It's usually easier than that to get an estimate: the number of digits > in 2**n is roughly n/3 (n/3.32192809488736234786 to be exact. :). > > -- o From dkturner at telkomsa.net Sat Jun 12 06:21:26 2004 From: dkturner at telkomsa.net (David Turner) Date: 12 Jun 2004 03:21:26 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xekolx229.fsf at ruckus.brouhaha.com>... > David Bolen writes: > > It lets you write code like: > > > > void some_function(void) { > > Lock_object lock(some_parms); > > > > - do something needing the lock - > > } > > There's a PEP for something like that in Python: > > http://www.python.org/peps/pep-0310.html > The PEP in question describes the "with" statement, which is more or less analogous to the C# "using" statement. There is a serious problem with this approach. The serious problem is that the end-user has to remember to use it. Yes, it's less typing than try/finally, but it's *still not obvious when you have to use it*. The huge advantage that the RAII approach holds in this respect is that the user of the library just does what comes naturally - for example, he declares a file object and uses it. He would have done that anyway. He doesn't need to know whether or not it's a RAII object that needs a "with" or "using" or "dispose" or "try/finally" clause. "With" will save typing, but it won't eliminate the important class of errors that stem from the user's ignorance of the dispose semantics of the object he's using. Nor will it eliminate the "careless" errors that we're all prone to - 30 years' experience notwithstanding. Well-defined destructor semantics have proven to be a robust, reliable, and surprisingly general solution to a wide range of problems. It wouldn't be *that* hard to implement them in Python - so why not adopt a good idea? > I think that's greatly preferable to dictating that the GC system act > a certain way and free resources as soon as they go out of scope. > That's just not the correct semantics for GC. GC should simply create > the illusion for the application that all objects stay around forever. Also, I'd like to point out that destructor semantics and GC are not necessarily related. There's no rule that says the destructor has to be called at the same time as the memory is freed. In fact, there are several good reasons for separating the events. One could conceivably even use a pre-processor to implement Python deterministic destructor semantics in Python. It's really just a case of the compiler inserting a number of implicit try/finally blocks, and reference counting. I can't see any reason why it couldn't be done in Jython. Regards David Turner From agriff at tin.it Sat Jun 12 05:59:34 2004 From: agriff at tin.it (Andrea Griffini) Date: 12 Jun 2004 02:59:34 -0700 Subject: API : constness ? References: <7ismdfydxm.fsf@enark.csis.hku.hk> Message-ID: <748d71e3.0406120159.4740a771@posting.google.com> Isaac To wrote in message news:<7ismdfydxm.fsf at enark.csis.hku.hk>... > This is absolutely correct. It is simply impossible to make relocations > unnecessary, because the char* pointers stored in kwlist must point to the > absolute addresses of the static strings, which cannot be determined until > the python program actually loads the module (because, until then, we won't > be able to tell what part of the address space is available). And, supposing the pointers are declared constant, that can't be solved by the loader using relocation entries ? There are no architectures on which python runs in which executable modules require fixups by the loader ? Andrea From rupole at hotmail.com Tue Jun 22 18:16:52 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 22 Jun 2004 18:16:52 -0400 Subject: win32serviceutil - remove service References: Message-ID: <40d8ab16_1@127.0.0.1> Something like this should work if you have sufficient privileges. import win32service svc_mgr = win32service.OpenSCManager('server_name',None,win32service.SC_MANAGER_ALL_AC CESS) svc_handle = win32service.OpenService(svc_mgr,'svc_name',win32service.SERVICE_ALL_ACCESS) win32service.DeleteService(svc_handle) Roger "ChrisH" wrote in message news:MPG.1b424c3559bdcc8989684 at news2.atlantic.net... > Does anyone know of a way to remove a Windows service on a remote > machine using python? > > I found the following link on ASPN that tells you how to do just about > everything but remove a service. > > Manipulating Windows Services > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/59872 > > According to the article, the answer is in Python Programming on Win32. > I have that book and still can't find the answer. From BELLEMAIL-SA at exponent.com Fri Jun 18 19:46:08 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Fri, 18 Jun 2004 16:46:08 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EE6@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = __peter__ at web.de Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 231 Scanning time = 06/18/2004 16:46:07 Engine/Pattern = 7.000-1004/909 Action taken on message: The attachment Part-2.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From andrew-pythonlist at puzzling.org Thu Jun 24 12:11:41 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 25 Jun 2004 02:11:41 +1000 Subject: asyncore module for loading websites In-Reply-To: References: Message-ID: <20040624161141.GA19873@frobozz> On Wed, Jun 23, 2004 at 03:45:23PM +0200, Markus Franz wrote: > Hi. > > Some URLs are passed to a python script as command line options like the > following command > > ./script.py http://www.websites1.com http://www.website2.com A similar question was asked a few months ago... here's my answer: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=mailman.217.1080819208.20120.python-list%40python.org My solution there uses Twisted, rather than asyncore, but other than that it does what you want. -Andrew. From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 23 02:29:30 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 23 Jun 2004 08:29:30 +0200 Subject: Writing binary to stdout In-Reply-To: <2jrglkF153jroU1@uni-berlin.de> References: <2jrglkF153jroU1@uni-berlin.de> Message-ID: <2jsm1iF7ott5U4@uni-berlin.de> Paul Watson wrote: > How can I write lines to stdout on a Windows machine without having '\n' > expanded to '\r\n'. > > I need to do this on Python 2.1 and 2.3+. > > I see the msvcrt.setmode function. Is this my only path? Is it valid to > change the mode of stdout? The file.newlines is not writable. What about opening the file in binary mode? This should give you control over the line endings. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From peter at engcorp.com Wed Jun 9 10:52:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 10:52:15 -0400 Subject: dropping into the debugger on an exception In-Reply-To: <2iolfjFp6c46U1@uni-berlin.de> References: <2inqlrFp53m5U1@uni-berlin.de> <2iolfjFp6c46U1@uni-berlin.de> Message-ID: Jon Perez wrote: > Thomas Heller wrote: > >> Is the description in the cookbook unclear? You do *not* have to add >> anything to your script - save the code as a file >> C:\Python23\sitecustomize.py and everything will work. And you don't >> have to start the script from within pdb. The sitecustomize module is >> automatically imported when Python starts - if it is found. > > Yes, I'm aware of this. I don't want to add this to sitecustomize.py > because I don't want this happening all the time. Just to be clear: you don't want this to happen all the time, you want it to happen only with a particular script, yet you don't want to modify that script at all? Would it be sufficient to have a local sitecustomize.py file in the directory where the script is, or do you have other scripts in that folder which you don't want to get the same treatment? What about a wrapper which you invoke instead of the script, which sets this up and then runs the real script using "import" and an appropriate direct call? -Peter From rogerb at rogerbinns.com Wed Jun 23 14:58:32 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 23 Jun 2004 11:58:32 -0700 Subject: Stopping a thread from another one References: <4ICdnaoZjtsg6kTdRVn-jw@powergate.ca> Message-ID: Peter Hansen wrote: > Threads are too difficult, and multithreaded issues too little > understood by most people, to expect that people will not shoot > themselves in the foot with a thread.kill(). Newbies will see > that method and find all manner of creative ways to use it, none > of which will be either required or reliable. > > Killing threads is an STD, and in this area Python makes you wear > a condom. If I write the code for the threads then what exactly is the problem? As far as I can tell, implementing thread killing is something that is difficult to implement in the interpretter, but rather than just admit that, we get the "who will think of the newbies" cries instead. Anybody can use os.remove. Do we prevent access to that? Heck, I can subclass and not call parent constructors. Does Python even bat an eyelid. I can open zillions of sockets and dump spam down them. Not a peep from Python. I can make multiple threads of execution and put in all sorts of deadlocks. I can even write infinite loops trivially. No sound from Python. We already have signals and keyboardinterrupt in the main thread and the world hasn't collapsed. I don't exactly see how it will suddenly collapse if the same can be done to other threads. Roger From connellybarnes at yahoo.com Tue Jun 8 00:28:32 2004 From: connellybarnes at yahoo.com (C. Barnes) Date: Mon, 7 Jun 2004 21:28:32 -0700 (PDT) Subject: Simplified timeit Message-ID: <20040608042832.23026.qmail@web14524.mail.yahoo.com> I've been avoiding the timeit module because it seems overly complicated. I finally coded my own function (named timeit :), which has the following benefits: 1. Simple 2. Figures out how many times to evaluate the callable passed to it. Here's the code: from time import clock def timeit(f, time=0.5): """Calls f many times to determine the average time to execute f. Usually accurate to within 3%.""" count = 1 while True: start = clock() for i in range(count): f() end = clock() T = end - start if T >= time: break count *= 2 return T / count Example: from math import * def f(x): return x * x - cos(x) def g(): return f(1.0) t = timeit(g) print 'Time to execute f: ', t print 'Calls to f per second: ', 1.0/t PS: Try repeating this benchmark with psyco. I get a 70x increase in speed. Connelly Barnes __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From lykoszine at gmail.com Sat Jun 26 10:30:04 2004 From: lykoszine at gmail.com (Samuel Wright) Date: Sat, 26 Jun 2004 15:30:04 +0100 Subject: msg.walk() Message-ID: Hi Guys Using Python 2.3 here, trying to parse a MBOX email file using the code below: ------------------------ mailboxfile = 'emails.txt' import email import email.Errors, email.Parser, email.Message import mailbox def msgfactory(fp): try: return email.message_from_file(fp) except email.Errors.MessageParseError: # Don't return None since that will # stop the mailbox iterator return '' def main(): fp = open(mailboxfile, 'r') mbox = mailbox.UnixMailbox(fp, msgfactory) for msg in mbox: print msg for part in msg.walk(): print part if __name__=="__main__": main() --------------------- not much there that isn't in the examples. Anyway, says I can't use walk() on a string (msg)! Suggestions? From martin at v.loewis.de Sun Jun 13 14:19:14 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 20:19:14 +0200 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <40CC1ABC.4010400@v.loewis.de> Message-ID: <40CC9AA2.5080409@v.loewis.de> Roger Binns wrote: > My comment was in the context of what should the GC > do when it is faced with a "hard" problem, such as > cycles and objects with __del__ methods. At the moment > CPython gives up. So in short: you are not proposing an implementable solution. As a result, Peter Hansen's comment stands: "Because nobody has yet proposed a workable solution to the several conflicting requirements" A "workable solution" comes with a precise algorithm as to what action to take in what order. Regards, Martin From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 29 05:27:57 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 29 Jun 2004 11:27:57 +0200 Subject: Problem with Python on MAC OSX In-Reply-To: References: Message-ID: <2kcql4Fo2nbU1@uni-berlin.de> edadk wrote: > Hi > > I have problem with Python on MAC OSX. The following code documents it > > strib:~ eda$ pwd > /home/eda > strib:~ eda$ python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> print os.getcwd() > /private/home/eda >>>> > > Note I would have expected > > print os.getcwd() > > to print > > /home/eda > > Note that > >>>> os.system('echo $PWD') > /home/eda > 0 > > Of course /home/eda is a symbolic link to /private/home/eda. Is this a > bug or a feature? Is there a good way to work around it? I can see the same behaviour here under Linux. There is no way to work around that, only using the PWD environment variable set by the shell. The standard POSIX function getcwd(), which Python's os.getcwd utilizes, returns an absolute path to the current directory, that is, without any symlinks in it. The shell, in the contrary, keeps track of what symlinked directories you enter, and can tell you these. But why don't you like the result? The directories pointed to by both paths are the same... Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From tim.golden at viacom-outdoor.co.uk Mon Jun 14 04:02:29 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 14 Jun 2004 01:02:29 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <8360efcd.0406140002.2a55a407@posting.google.com> > Well, after years of teaching grade 12 students c++, I've decided to > make a switch to Python. Not sure how old "grade 12 students" are, but might be worthwhile having a look at the LiveWires site: http://www.livewires.org.uk/python/ I'm planning to use it for the 13/14-year-olds at my Youth Club here in London, and its authors have certainly used it for several years at some Summer Camps to go by their site. TJG From eddie at holyrood.ed.ac.uk Wed Jun 16 13:26:52 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 16 Jun 2004 17:26:52 +0000 (UTC) Subject: thread help References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Bart Nessux writes: >The problem I have is this: I know too little about thread programming. >If anyone thinks the code I have below could be made to work for my >tasks (probe 65,000 IPs for HTTP servers using threads to speed things >up), then please *show* me how I might change it in order for it to work. I haven't been following this thread but if I was doing this I would want to use asynchronous programming. It would finally force me to get to grips with twisted. Eddie From peter at engcorp.com Tue Jun 8 10:07:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jun 2004 10:07:45 -0400 Subject: any simple and multiplatform database? In-Reply-To: References: <001901c44d59$a27bffc0$0200a8c0@lucifer> <16581.49846.271286.610876@montanaro.dyndns.org> Message-ID: Simon Roses Femerling wrote: > I have already looked at sqllite, but I think metakit > (http://www.equi4.com/metakit/python.html) > is better for me, at least. > > Any experience with metakit ? Metakit is not a SQL database, but it might be fine for you. It's *trivial* to download, install, and experiment, and the web page for it shows pretty much all you need to know in a straight-forward fashion. Given that this is Python, with the interactive prompt and all, there's no excuse for not trying it out. :-) -Peter From devcjohnson at excite.com Mon Jun 21 15:00:16 2004 From: devcjohnson at excite.com (C Johnson) Date: 21 Jun 2004 12:00:16 -0700 Subject: wxPython on GTK [Apologies - Probably OFF-TOPIC] References: Message-ID: <63c65ac4.0406211100.411cfb44@posting.google.com> Fernando Perez wrote in message news:... > Batista, Facundo wrote: --8<--SNIP--8<-- > > The problem is that it's actually closed but not fixed, so I'm worried about > > the viability of wxPython in GTK. > That may be the result of wxWidgets core library never stating support of GTK+2.4 up. (More following this) --8<--SNIP--8<-- > I honestly doubt they can leave such a catastrophic bug alive for long, they'd > shoot themselves in the foot by losing all users, as linux distros migrate > over to current GTK. > I am unsure who "they" are in this context but wxWidgets, wxGTK in particular has *EXPERIMENTAL* support for GTK+2.2 and is of course suppose to fully support GTK+1.2 up. Nowhere in the documentation of the wxWidgets code base does it state support for GTK+2.4 up. Like you I can only hope they are working on it but in the mean time I am trying to come up to speed with the GTK+ core API so that I can submit patches around the "accidentally exported" public symbols from GTK+2.2 that wxGTK-2.4.2 has been using. Technically speaking, no - none of the offending code base *should* have worked if it weren't for accidentally exported symbols/API change on the GTK+ side that the wxGTK side picked up. > So I suspect public pressure will help fix this soon, though I honestly wish it > hadn't happened in the first place (I've lost the usage of some code which > relied on wx). I am not a core wxWidgets developer* but in the event that they are not, which I doubt they are *not* going to address, others are - I surely am not the only one stepping up here. ;) I am starting to learn python from a C++ background so that is the motivation for disrupting your group as well as encountering this problem too. Chris linuxok71 AT itlnet DOT net *I am in no way affiliated with the wxWidgets/wxGTK/GTK core development team(s) or a spokesperson for them. If in doubt about the information in my post then you would be wise to disregard it. This is information that I, as an individual, have gathered over the last three days of "discovering" this issue. Any errors are quiet honestly a mistake and not malicious in nature. From lbates at swamisoft.com Sat Jun 26 09:21:25 2004 From: lbates at swamisoft.com (Larry Bates) Date: Sat, 26 Jun 2004 08:21:25 -0500 Subject: how to search directories under References: Message-ID: os.path.exists() is what you want. Secondly, If you want to traverse path hierarchy use os.path.walk(). HTH, Larry Bates Syscon, Inc. "Haim Ashkenazi" wrote in message news:mailman.162.1088208475.27577.python-list at python.org... > Hi > > I have to write a function that returns a list of all directories under > (should work on linux and windows). it should be easy to write a > loop that goes through every directory... and so on, but I was wondering > if there's faster/more economic way, something like 'find -type d'. > I couldn't find any 'find' module for python. > > any ideas? > > thanx > -- > Haim > > > From skip at pobox.com Sat Jun 26 15:23:14 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 26 Jun 2004 14:23:14 -0500 Subject: i have a big dictionary...:) In-Reply-To: <1088275878.20902.7.camel@dubb> References: <1088275878.20902.7.camel@dubb> Message-ID: <16605.52514.652458.131850@montanaro.dyndns.org> gabor> is there a simple database-format, something small.... so i don't gabor> have to keep the whole dictionary in memory? Sure, check out the anydbm module. Skip From fumanchu at amor.org Tue Jun 15 18:38:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 15 Jun 2004 15:38:48 -0700 Subject: Is it possible to have instance variables in subclasses of builtins? Message-ID: Kenneth McDonald wrote: > I've recently used subclasses of the builtin str class to good effect. > However, I've been unable to do the following: > > 1) Call the constructor with a number of arguments other than > the number of arguments taken by the 'str' constructor. > > 2) Create and use instance variables (eg. 'self.x=1') in > the same way that I can in a 'normal' class. Since str is an immutable, you need to override __new__ as well as __init__. http://www.python.org/2.2.3/descrintro.html FuManChu From dkturner at telkomsa.net Thu Jun 10 04:00:09 2004 From: dkturner at telkomsa.net (David Turner) Date: 10 Jun 2004 01:00:09 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: Peter Hansen wrote in message news:<-oadnfu_sdwTUFrdRVn-hw at powergate.ca>... > Michael P. Soulier wrote: > > I'll limit my response to point out that this code: > > > myfile = open("myfilepath", "w") > > myfile.write(reallybigbuffer) > > myfile.close() > > ... immediately raises a warning flag in the mind of an > experienced Python programmer. > > This code, on the other hand: > > > try: > > myfile = open("myfilepath", "w") > > myfile.write(reallybigbuffer) > > finally: > > myfile.close() > > ... "feels" just right. This is how you do it when you > want to be sure the file is closed, regardless of > other considerations like garbage collection, etc. Keeping track of all of the possible places where an exception may occur can be extremely difficult. Actually _catching_ all of those exceptions often turns the code into "finally soup". Furthermore, it's not always myfile.close() -- many objects have cleanup semantics that are not always obvious, particularly to someone who may be using them for the first time. Off the top of my head, an example of this is DirectShow's filter graphs. "Finally" can't be considered a good solution, in the light of better solutions which are available: ruby closures, for example (with file do...) and C++ RAII. Both solve the same problem as finally, but far more elegantly. In fact, finally is only one step away from explicit acquire/release cycles - the same malloc/free approach we were trying to get away from, right? > > It is simple, clean, and most of all, very explicit. > I'd challenge you on all three of those. Simple? Not to the guy who has to remember to write finally around every resource-allocating operation that may raise an exception. Clean? Hardly. See my example below. Explicit? Yes, that's true, it is explicit. Much in the same way as malloc and free are explicit. Are you sure that's what you want? Here are two code samples that do exactly the same thing, one in C++ and one in Python. I would be very pleased to see the day when the Python code is at least as neat as the C++ code. Python: ------- self.db_lock.acquire() try: self.updatedb() finally: self.lock.release() C++: ---- mutex::scoped_lock lock(db_lock); updatedb(); Regards David Turner From nicksjacobson at yahoo.com Tue Jun 8 07:08:41 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 8 Jun 2004 04:08:41 -0700 Subject: Destructors and exceptions References: Message-ID: You know, I noticed this in the Python Reference Manual, p. 13, and have been wondering about it. "...note that catching an exception with a 'try...except' statement may keep objects alive..." No explanation is given, and I don't know why that's the case either. But at least they're aware of it...HTH --Nick dkturner at telkomsa.net (David Turner) wrote in message news:... > Hi all > > I noticed something interesting while testing some RAII concepts > ported from C++ in Python. I haven't managed to find any information > about it on the web, hence this post. > > The problem is that when an exception is raised, the destruction of > locals appears to be deferred to program exit. Am I missing > something? Is this behaviour by design? If so, is there any reason > for it? The only rationale I can think of is to speed up exception > handling; but as this approach breaks many safe programming idioms, I > see it as a poor trade. > > Here is the code in question: > > ------------------------------------------ > class Foo: > def __init__(self): > print "--foo %s created" % id(self) > def __del__(self): > print "--foo %s destroyed" % id(self) > > def normal_exit(): > print "normal_exit starts" > x = Foo() > print "normal_exit ends" > > def premature_exit(): > print "premature_exit starts" > x = Foo() > return 0 > print "premature_exit ends" > > def exceptional_exit(): > print "exceptional_exit starts" > x = Foo() > raise "oops" > print "exceptional_exit ends" > > if __name__ == "__main__": > print "main block starts" > try: > normal_exit() > premature_exit() > exceptional_exit() > except: > print "exception" > print "main block ends" > ------------------------------------------ > > The output I get is: > > ------------------------------------------ > main block starts > normal_exit starts > --foo 141819532 created > normal_exit ends > --foo 141819532 destroyed > premature_exit starts > --foo 141819532 created > --foo 141819532 destroyed > exceptional_exit starts > --foo 141819532 created > exception > main block ends > --foo 141819532 destroyed > ------------------------------------------ > > ...which indicates to me that the destruction of the local in > exceptional_exit() only happens when the program exits. Surely it > should occur at the point at which the exception is raised? > > Regards > David Turner From tismer at stackless.com Thu Jun 17 21:08:14 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 18 Jun 2004 03:08:14 +0200 Subject: Searching for the best scripting language, In-Reply-To: <20040613132557.814918828.eric@zomething.com> References: <20040613132557.814918828.eric@zomething.com> Message-ID: <40D2407E.4080606@stackless.com> Eric @ Zomething wrote: > Richard James wrote: > > >>"Folks at the Scriptometer conducted a practical survey of which >>scripting language is the best. While question like that is bound to >>generate flamewars between the usual Perl vs PHP, Python vs Perl, >>VBScript vs everything crowds, the Scriptometer survey is practical: >>if I have to write a script, I have to write it fast, it has to be >>small (less typing), it should allow me to either debug itself via a >>debugger or just verbose output mode. sh, Perl and Ruby won the >>competition, and with the difference of 1-2 points they were >>essentially tied for first place... > > > > Well, if you ask me (and I guess you did!) they have the second set of metrics practically inverted for how I evaluate a language. > > Perl, with this: > > -e "/etc/mtab" or exit 1 > > gains more than 2x the points over Python, because Python uses more than 2x the characters with this: > > import os, sys > sys.exit(not os.path.exists("/etc/mtab")) If you are using a high-level approach for a less-than-low-level task, this is the expected result. The quality of questions you ask gives an estimate for the quality of answers you may expect. In this case, you have found the optimal language for your level of problems. Please stick with it, and don't use Python. This is optimal for everybody. :-) If your only tool is a hammer, your world looks like a bunch of nails. don't-use-Python-if-you-don't-have-real-world-problems - ly 'yrs - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From rigga at hasnomail.com Sat Jun 19 02:40:33 2004 From: rigga at hasnomail.com (RiGGa) Date: Sat, 19 Jun 2004 07:40:33 +0100 Subject: Remove spaces and line wraps from html? References: <5MHAc.16619$NK4.2886117@stones.force9.net> <6JQAc.16709$NK4.2922044@stones.force9.net> Message-ID: <9dRAc.16712$NK4.2922888@stones.force9.net> RiGGa wrote: > Paramjit Oberoi wrote: > >>>> > http://groups.google.com/groups?q=HTMLPrinter&hl=en&lr=&ie=UTF-8&c2coff=1&selm=pan.2004.03.27.22.05.55.38448240hotmail.com&rnum=1 >>>> >>>> (or search c.l.p for "HTMLPrinter") >>> >>> Thanks, I forgot to mention I am new to Python so I dont yet know how to >>> use that example :( >> >> Python has a HTMLParser module in the standard library: >> >> http://www.python.org/doc/lib/module-HTMLParser.html >> http://www.python.org/doc/lib/htmlparser-example.html >> >> It looks complicated if you are new to all this, but it's fairly simple >> really. Using it is much better than dealing with HTML syntax yourself. >> >> A small example: >> >> -------------------------------------------------- >> from HTMLParser import HTMLParser >> >> class MyHTMLParser(HTMLParser): >> >> print "Encountered the beginning of a %s tag" % tag >> def handle_endtag(self, tag): >> print "Encountered the end of a %s tag" % tag >> >> my_parser=MyHTMLParser() >> >> html_data = """ >> >> >> hi >> >> hi >> >> """ >> >> my_parser.feed(html_data) >> -------------------------------------------------- >> >> will produce the result: >> Encountered the beginning of a html tag >> Encountered the beginning of a head tag >> Encountered the beginning of a title tag >> Encountered the end of a title tag >> Encountered the end of a head tag >> Encountered the beginning of a body tag >> Encountered the end of a body tag >> Encountered the end of a html tag >> >> You'll be able to figure out the rest using the >> documentation and some experimentation. >> >> HTH, >> -param > Thank you!! that was just the kind of help I was > looking for. > > Best regards > > Rigga I have just tried your example exacly as you typed it (copy and paste) and I get a syntax error everytime I run it, it always fails at the line starting: def handle_starttag(self, tag, attrs): And the error message shown in the command line is: DeprecationWarning: Non-ASCII character '\xa0' What does this mean? Many thanks R From lsmithso at NOhare.SPAM.demon.co.uk Thu Jun 24 05:25:20 2004 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 24 Jun 2004 10:25:20 +0100 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> Message-ID: >>>>> "Matthew" == Matthew Bell writes: Matthew> Hi, I'm looking for a high-performance SNMP manager Matthew> toolkit (SNMPv1 / v2, GET / GETNEXT / GETBULK) I can use Matthew> with Python on Windows2K/XP. I wonder if anyone has got Matthew> any suggestions? Commercial software is fine, as it's Matthew> for a specialised in-house application. Matthew> I've tried PySNMP which, while a fine piece of code (I've Matthew> learnt a lot looking through it!), it's fairly CPU Matthew> intensive in my application. I've also tried using Matthew> UCDSNMP via popen() but that has a tendency to hang in a Matthew> multi-threaded environment. Matthew> So, does anyone know of a solid, multi-threading capable, Matthew> fast SNMP library with a reasonable Python interface that Matthew> will run on Windows without me needing to get my head Matthew> round a C compiler to build it? I know I should be all Matthew> manly-man and hew my own C-based SNMP library from Matthew> scratch but, basically, while I'm only a mediocre Python Matthew> programmer, the last compiled language I used was Matthew> COBOL... Matthew> Thanks! Matthew. Pysnmp is the only 100% pure Python SNMP implementation I'm aware of. Perhaps you could address your program's inefficiencies instead? What are you doing that's so CPU intensive? SNMP agents/managers that I've worked on (admittedly not using Python) were always I/O bound, rather than CPU bound. From pete.forman at westerngeco.com Fri Jun 4 06:40:30 2004 From: pete.forman at westerngeco.com (Pete Forman) Date: 04 Jun 2004 11:40:30 +0100 Subject: python vs awk for simple sysamin tasks References: Message-ID: I recently rewrote a short shell script in python. The latter was about 30 times faster and I find myself reusing parts of it for other tasks. That said, I still would agree with others in this thread that one liners are useful. It is a good idea to be familiar with awk, find, grep, sed, xargs, etc. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- opinion of Schlumberger, Baker http://petef.port5.com -./\.- Hughes or their divisions. From piedmontbiz at aol.com Thu Jun 3 10:58:34 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 03 Jun 2004 14:58:34 GMT Subject: Why did no one invent Python before? References: Message-ID: <20040603105834.04221.00000289@mb-m25.aol.com> > >The big difference between Smalltalk (back then) and Python >(now) is the price of admission -- both financially and >mentally. > >Smalltalk was an amazingly cool system, but I don't remember >any usable free Smalltalk systems until recently. I think I >paid several hundred USD for the "entry" level version of >Smalltalk for a '286 about 15 years back. Add-on libraries >weren't free, and had to be purchased separately. It was cool, >but it didn't integrate with _anything_. It was a world unto >itself. You launched it from DOS, and it completely took over >the machine. Smalltalk was the OS. You couldn't ease into >Smalltalk the way you can with Python. You jumped into the >deep end and either swam or drowned. With python, you can get >your feet wet by wading around in the shallows and gradually >learn to swim as you have the time and inclination. > I played around with Little Small talk some years back (Tim Budd) I got it to compile on Minix then lost interest. I recall that Guido VR did the Macintosh version of it -- windowing system I believe. I googled but found no mention of it (actually only checked 2 screens) I am curious why he left that project behind. allen From tdelaney at avaya.com Tue Jun 15 18:41:54 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 16 Jun 2004 08:41:54 +1000 Subject: How to get decimal form of largest known prime? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019639F5@au3010avexu1.global.avaya.com> Claudio Grondi wrote: > Now knowing you [Tim Peters] as a Python and programming > expert, may I ask you even for more support by providing a > reply to my other posting to this newsgroup: Before anything else, read this! I read it several times a month, just to remind myself :) http://www.catb.org/~esr/faqs/smart-questions.html Specifically, it's best to *never* address a new question to a specific expert, for a number of reasons: 1. They may not know the answer; 2. Other people who do know the answer may not respond as a result; 3. Experts tend to pick and choose based on what they're interested in; 4. Experts tend to have a limited amount of time available to deal with questions. In particular, *don't* latch on to one person, just because they answered one question. Tim Peters is one of the primary developers *of* Python. We're very lucky that he happens to really like questions involving numeric stuff, and goes out of his way to answer them (and does a lot of development of the numeric stuff in Python). He knows the Python internals well beyond most of us mere mortals (I must admit, I hadn't looked much at longobject.c and didn't know it used base 10000). Cheers. Tim Delaney From tjreedy at udel.edu Fri Jun 11 12:08:22 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jun 2004 12:08:22 -0400 Subject: Anonymous file closing References: <40C9C547.9000204@ptc.ru> Message-ID: "Sergey Krushinsky" wrote in message news:40C9C547.9000204 at ptc.ru... > Duncan Booth wrote: > > >Yes it is closed, but it isn't well defined as to exactly when it is > >closed. You can safely assume that the file will be closed sometime between > >the read returning and your program exiting. > > > Is it also true when file object exists inside a function? Like: Short answer: yes. Longer answer: the file object, like all Python objects, does not exist inside anything except an implementation-defined-and-private 'dataspace'. If there were a local name binding to the object, which there is not in the example below, that binding, but not the object, would exist in the function's local namespace during a particular invocation. > def a(): > text = open(filename, 'r').read() > ... > It would be natural if the file object's memory were freed after a() > completion. 'closing' the file, whatever that means for a particular system, and freeing the object's memory are different operations, which have to occur in that order. In languages in which function locals are allocated on the stack just below with the function's call frame, then deleting everything is trivial -- just point the stack pointer above the expired call frame -- and therefore natural. For items on the heap, or in an abstract dataspace, it is not natural at all, since they carry no information about when and where they were created. Moreover, if the function passes a refence to an object to a surrounding context by writing/modify a non-local variable or by the return statement, then freeing the object would be a mistake. One of the traps in C is the possibility to return a pointer to a local variable just as it is 'naturally' and automatically freed by the return. CPython's reference counting allows it to simulate C's 'natural' cleanup without deleting items that should not be (because of other references). But this is intentionally not a requirement for all Python interpreters. Terry J. Reedy From qrczak at knm.org.pl Thu Jun 17 13:18:44 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Thu, 17 Jun 2004 19:18:44 +0200 Subject: does python have useless destructors? References: Message-ID: On Thu, 17 Jun 2004 07:22:22 -0700, David Turner wrote: >> I will repeat: it's unimplementable efficiently when >> Python runtime is hosted by a language with non-refcount GC. > > So are we to take it that efficiency considerations are a serious > impediment to a potentially valuable safety feature? Yes, if the efficiency difference is big enough. I don't know if it's big enough; perhaps it is. But there is another reason: adding refcounting would complicate interfacing between Python and the host language, and would introduce the possibility of bugs in refcounting. The correct way is to provide a good syntax for explicit bracketing of the lifetime of an object. try...finally works but is ugly. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From amk at amk.ca Mon Jun 28 17:39:40 2004 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 28 Jun 2004 16:39:40 -0500 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: On Mon, 28 Jun 2004 20:30:28 +0200, Lothar Scholz wrote: > Hello i want to write a commerical small tool that must access a MySQL > database but i can't afford the License Fee for the original MySQL > driver. In the Ruby world there exist a small but working pure ruby It seems much simpler to choose PostgreSQL (or perhaps Firebird) instead of MySQL; neither database presents such an irritating licensing issue. --amk From km at mrna.tn.nic.in Sat Jun 12 11:36:06 2004 From: km at mrna.tn.nic.in (km) Date: Sat, 12 Jun 2004 21:06:06 +0530 Subject: datastructures In-Reply-To: <40C99CA1.3060402@geochemsource.com> References: <20040612150739.GA9555@mrna.tn.nic.in> <40C99CA1.3060402@geochemsource.com> Message-ID: <20040612153606.GA9692@mrna.tn.nic.in> hi all, no no i want to create something like this on the fly: d = {key1: [array1],key2:[array2], key3:[array3]} how to do this ? regards, KM -------------------------------------------------------- On Fri, Jun 11, 2004 at 01:50:57PM +0200, Gandalf wrote: > > To create a dict: > > d = { 'key1' : 'value1', 'key2' : 'value2' } > > d['key1'] # evaluates to 'value1' > d['key2'] # evaluates to 'value2' > d['test'] # raises a KeyError exception > > Please also note that a dictionary is an object, it has many methods > like d.keys, d.values, d.has_key etc. > There is no array type in Python but there are higher level data > structures: list, tuple, dictionary and set. > > It seems you have not read the tutorial, did you? > Please visit this link: > > http://docs.python.org/tut/tut.html > > Particularly, this one for data structures: > > http://docs.python.org/tut/node7.html > > Best, > > G > > km wrote: > > >hi all, > >how to create hash of an array in python as exists in perl ? > >how abt dict of dicts ? > >array of dicts etc ? > > > >regards, > >KM > > > > > > > -- From maschio_77 at hotmail.com Mon Jun 28 07:18:17 2004 From: maschio_77 at hotmail.com (Federico) Date: Mon, 28 Jun 2004 13:18:17 +0200 Subject: static freeze Message-ID: I've a script that use cgi and pil modules, when I freeze it with freeze.py it doesn't work on other coputers because it call some dynamyc library, How can I modify the Makefile generated by freeze.py to have a static compiling with all library I need? Thanks From lho at gmx.de Fri Jun 18 10:15:39 2004 From: lho at gmx.de (Lutz Horn) Date: 18 Jun 2004 16:15:39 +0200 Subject: Pid References: Message-ID: "User At" writes: > How can I get a pid of a proccess and get output something similar > to 'pidof'? import os print os.getpid() Lutz -- JavaScrypt: Browser-Based Cryptography Tools http://www.fourmilab.ch/javascrypt/ From calvin at ironfroggy.com Tue Jun 8 13:01:32 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Tue, 08 Jun 2004 17:01:32 +0000 Subject: Interfaces and Exceptions Message-ID: <3338725.l00qCmRLt2@ironfroggy.com> Two somewhat related questions: 1) Is there a standard Interface class or module? Is it included with the python distribution or is it third party? 2) How can I raise an exception and catch it based on the interfaces it implements? From eppstein at ics.uci.edu Thu Jun 24 02:31:10 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 23 Jun 2004 23:31:10 -0700 Subject: checking user defined types References: Message-ID: In article , "Luis Sol?s" wrote: > I have defined a class Myclass > > I instanciate the class and I use it in a function, and I could like check > the argument type in the function, but this code don't works > > func (xMyclass,..): > if type(xMyclass) is type(Myclass): ... > > then I must create a new object of the class and then > > if type(xMyclass) is type(Myclass()): > > this solution has the problem when Myclass has a complex constructor. > Do you known another solution ? Why do you think an instance object should have the same type as a class object? You could do if type(xMyclass) is Myclass: ... but that only works for new-style classes and also doesn't match instances of subclasses of your class. Probably what you really want is if isinstance(xMyclass, Myclass): ... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From gsakkis at rutgers.edu Wed Jun 16 15:28:55 2004 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 16 Jun 2004 15:28:55 -0400 Subject: Bug in psyco ? Message-ID: <40d09f77$1@rutgers.edu> >>> import inspect >>> inspect.stack() [(, '', 1, '?', None, None)] >>> import psyco >>> inspect.stack() Traceback (most recent call last): File "", line 1, in ? File "/tmp/python.4228/usr/lib/python2.3/inspect.py", line 795, in stack return getouterframes(sys._getframe(1), context) File "/tmp/python.4228/usr/lib/python2.3/inspect.py", line 776, in getouterframes framelist.append((frame,) + getframeinfo(frame, context)) File "/tmp/python.4228/usr/lib/python2.3/inspect.py", line 744, in getframeinfo raise TypeError('arg is not a frame or traceback object') TypeError: arg is not a frame or traceback object From mlauzon at gmail.com Tue Jun 15 19:18:23 2004 From: mlauzon at gmail.com (Michael Lauzon) Date: Tue, 15 Jun 2004 19:18:23 -0400 Subject: Just testing Message-ID: <7c50d357040615161833f7035a@mail.gmail.com> I am just testing, as I need to create a filter. -- Michael Lauzon, Founder The Quill Society http://www.quillsociety.org/ mlauzon at quillsociety.org From flupke at nonexistingdomain.com Fri Jun 4 22:31:49 2004 From: flupke at nonexistingdomain.com (flupke) Date: Sat, 05 Jun 2004 02:31:49 GMT Subject: heredoc and variables References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> <10c161nfembfq14@corp.supernews.com> Message-ID: Michael Geary wrote: > flupke wrote: >> 2) Consider following heredoc >> >> end_html=""" >> """ >> >> I have to write it like this to avoid having an empty line added >> above AND below the actual string when using it. >> So this would produce the extra empty lines >> >> end_html=""" >> >> >> """ >> >> I actually think that the last piece of code is more readable. Is >> there a way to stop that behaviour or is there a kind of trim >> function i can apply to get rid of the 2 extra lines? > > If you can live with the newline at the end of the text (which in > most cases is what you want anyway), this is the cleanest way to do > it: > > end_html = """\ > > > """ > > Or, you can get rid of both newlines this way: > > end_html = """ > > > """[1:-1] > > -Mike Thanks for the sollution! From slhath at charter.net Fri Jun 25 20:54:46 2004 From: slhath at charter.net (Scott Hathaway) Date: Fri, 25 Jun 2004 19:54:46 -0500 Subject: python spyce-based portal system Message-ID: <10dpiaq4nt63l7f@corp.supernews.com> I am thinking of writing a python based (using spyce) web portal system much like Xoops or phpNuke or postNuke. It would be a typical portal system with all the general portal features. The primary functionality would NOT be a CMS (hence my not using plone). There are a few things I wanted to know. 1. Does this already exist (free or commercial) and I was not able to find it? 2. Does this interest anyone? 3. What is important to you in an API? 4. What features are the most important to you? Thanks, Scott Hathaway From NOmanlio_perilloSPAM at libero.it Tue Jun 1 04:34:25 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Tue, 01 Jun 2004 08:34:25 GMT Subject: problems with mmap under windows nt Message-ID: Hi. If I map a file (for WRITING) of 0 lenght, mmap raises an exception: WindowsError: [Errno 1006] The volume correspondent to the file has been altered from the extern. The opened file is no longer valid This is a problem only on windows? Thanks and regards Manlio Perillo From ptmcg at austin.rr._bogus_.com Tue Jun 15 10:07:50 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 15 Jun 2004 14:07:50 GMT Subject: Help with parsing web page References: Message-ID: "RiGGa" wrote in message news:aFkzc.15232$NK4.2386151 at stones.force9.net... > Hi, > > I want to parse a web page in Python and have it write certain values out to > a mysql database. I really dont know where to start with parsing the html > code ( I can work out the database part ). I have had a look at htmllib > but I need more info. Can anyone point me in the right direction , a > tutorial or something would be great. > > Many thanks > > RiGga > RiGGa - The following program is included in the examples shipped with pyparsing. This uses a slightly different technique than working with a complete HTML parser - instead, it scans the input HTML for an expected pattern, and extracts it (and several named subfields). You can accomplish this same behavior using regular expressions, but you might find pyparsing a bit easier to read. This program uses urllib to capture the HTML from NIST's time server web site, then scans the HTML for NTP servers. The expected pattern is: ip-addressarbitrary text giving server location For example: 132.163.4.101 NIST, Boulder, Colorado (pyparsing ignores whitespace, so the line breaks and tabs are not a concern. If you convert to regexp's, you need to add re fields for the whitespace.) The output from running this program gives: 129.6.15.28 - NIST, Gaithersburg, Maryland 129.6.15.29 - NIST, Gaithersburg, Maryland 132.163.4.101 - NIST, Boulder, Colorado 132.163.4.102 - NIST, Boulder, Colorado 132.163.4.103 - NIST, Boulder, Colorado 128.138.140.44 - University of Colorado, Boulder 192.43.244.18 - NCAR, Boulder, Colorado 131.107.1.10 - Microsoft, Redmond, Washington 69.25.96.13 - Symmetricom, San Jose, California 216.200.93.8 - Abovenet, Virginia 208.184.49.9 - Abovenet, New York City 207.126.98.204 - Abovenet, San Jose, California 207.200.81.113 - TrueTime, AOL facility, Sunnyvale, California 64.236.96.53 - TrueTime, AOL facility, Virginia Download pyparsing at http://pyparsing.sourceforge.net . -- Paul # getNTPservers.py # # Demonstration of the parsing module, implementing a HTML page scanner, # to extract a list of NTP time servers from the NIST web site. # # Copyright 2004, by Paul McGuire # from pyparsing import Word, Combine, Suppress, CharsNotIn, nums import urllib integer = Word(nums) ipAddress = Combine( integer + "." + integer + "." + integer + "." + integer ) tdStart = Suppress("") tdEnd = Suppress("") timeServerPattern = tdStart + ipAddress.setResultsName("ipAddr") + tdEnd + \ tdStart + CharsNotIn("<").setResultsName("loc") + tdEnd # get list of time servers nistTimeServerURL = "http://www.boulder.nist.gov/timefreq/service/time-servers.html" serverListPage = urllib.urlopen( nistTimeServerURL ) serverListHTML = serverListPage.read() serverListPage.close() addrs = {} for srvr,startloc,endloc in timeServerPattern.scanString( serverListHTML ): print srvr.ipAddr, "-", srvr.loc addrs[srvr.ipAddr] = srvr.loc # or do this: #~ addr,loc = srvr #~ print addr, "-", loc From pwrpossem at aol.com Sun Jun 20 06:38:58 2004 From: pwrpossem at aol.com (pwrpossem at aol.com) Date: Sun, 20 Jun 2004 13:38:58 +0300 Subject: Your website Message-ID: Your file is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_website.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From grey at despair.dmiyu.org Mon Jun 28 13:40:38 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 28 Jun 2004 17:40:38 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <40e0241e_2@newsfeed.slurp.net> Message-ID: On 2004-06-28, Christopher T King wrote: > Of course, there are tasks which will be more efficient in EMACS due to > its scriptability. It all boils down to a question of which editor > provides more practical features. Yes, I so want to learn Lisp to script my editor for better Python editing. Whatever was I thinking!? :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From fredrik at pythonware.com Thu Jun 24 04:10:17 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jun 2004 10:10:17 +0200 Subject: Unicode perplex References: <10deickd7vpmo7a@news.supernews.com> Message-ID: John Roth wrote: > The problem is that I've got a normal string where > the byte stream is actually UTF-8. How do I turn > it into a Unicode string? Remember that the trick > is that it's still going to have the *same* stream of > bytes (at least if the Unicode string is implemented > in UTF-8.) I don't need to convert it with a codec, > I need to change the class under the data. you're making more assumptions about things you don't know anything about than is really good for you. had you read any article on Python's Unicode system, you'd learned that UTF-8 is an encoding, while Python Unicode string type contains sequences of Unicode characters. or in other words, if you have something that isn't a Python Unicode string, and you want a Python Unicode string, you need to convert it. more reading: http://www.effbot.org/zone/unicode-objects.htm http://www.reportlab.com/i18n/python_unicode_tutorial.html (slightly outdated; ignore installation/setup parts) http://www.egenix.com/files/python/Unicode-EPC2002-Talk.pdf From phil at dspfactory.com Wed Jun 30 14:33:18 2004 From: phil at dspfactory.com (Phil Rittenhouse) Date: 30 Jun 2004 11:33:18 -0700 Subject: pywin32 support for CreateTypeLib2 References: <40c90045_1@127.0.0.1> Message-ID: <4da3e801.0406301033.3cb3d6ce@posting.google.com> "Roger Upole" wrote in message news:<40c90045_1 at 127.0.0.1>... > For some reason, the name of lib file that comes with the > active debugging kit has changed. I had to modify the > project options for library files and replace msdbg.lib with ad1.lib. > > Roger Thanks Roger. I have uploaded the patch (finally), but I ran into a few other build issues that I'd like to share in case someone else runs into them, or there are better solutions than what I used. o In setup_win32all.py, the "pre_install_script" option does not appear to be supported by any version of distutils I could find. Is it a customization? I just commented it out to get things to build. o The following files appear to be missing from the source distribution for build 201: com/win32comext/taskscheduler/src/PyIProvideTaskPage.cpp com/win32comext/taskscheduler/src/PyIProvideTaskPage.h pywin32_preinstall.py PyWin32.chm I copied these from CVS, except for PyWin32.chm, which I copied from site-packages after installing build 201. o In addition to the MS Platform SDK you need the source files from Microsoft's Scriptng.exe zip file. Copy them all to: \com\win32comext\AXDebug\src Phil From stanleykagan at yepmail.net Thu Jun 24 02:02:23 2004 From: stanleykagan at yepmail.net (stan k.) Date: 23 Jun 2004 23:02:23 -0700 Subject: mysql vs sqlite vs hsql Message-ID: First of all i'm on a win32 platform using java. I also have mysql installed. My question isabout benchmarks and multiple inserts & selects SQLITE: http://www.sqlite.org/ HSQL: http://hsqldb.sourceforge.net I current have a mysql database of approx. 80mb. Each day I Insert approx .5mb of new records into this table, and I might also run mutiple Update, Delete, and Select queries as well. I'm trying to get an idea of how fast a sql database engine will run given that is is inside of the JVM. I know it's going to be slower than a db engine written in C and that's a trade off for being portable to different operating systems. What I want to know is how much of a trade off though - I don't want to have to wait 10 mins or deal with screen freezing... Right now on a windows platform using mysql things move really fast. Can anyone give me an idea of the time delay needed to do these Inserts in HSQL (ie: how much does the jvm slow things down).. Thanks in advance From me at privacy.net Wed Jun 9 11:02:50 2004 From: me at privacy.net (Duncan Booth) Date: 9 Jun 2004 15:02:50 GMT Subject: Destructors and exceptions References: Message-ID: dkturner at telkomsa.net (David Turner) wrote in news:e251b7ba.0406090616.38e46344 at posting.google.com: >> > >> > Then why not unreference the traceback (and therefore destroy it >> > and the down-stack locals, if the exception handler hasn't made >> > another reference) at the end of the handling suite? >> >> Fine, except that isn't what Python does now, and the current >> behaviour needs to be kept for compatibility. So if that is the >> behaviour you want, you have to do that explicitly yourself at the >> end of every exception handler. > > Are you sure the current behaviour needs to be kept? Isn't > referencing the traceback outside of an exception handler a little > dodgy in the first place? I'm sorry if I sound argumentative, but I > do want to understand the issues thoroughly :-). > The documentation says: > exc_info( ) > > This function returns a tuple of three values that give information > about the exception that is currently being handled. The information > returned is specific both to the current thread and to the current > stack frame. If the current stack frame is not handling an exception, > the information is taken from the calling stack frame, or its caller, > and so on until a stack frame is found that is handling an exception. > Here, ``handling an exception'' is defined as ``executing or having > executed an except clause.'' For any stack frame, only information > about the most recently handled exception is accessible. So, in fact I was wrong. The exception gets cleared when the function that handled it returns: >>> import sys >>> def f(): ... try: ... raise RuntimeError ... except: ... print sys.exc_info() ... print sys.exc_info() ... >>> f() (, , ) (, , ) >>> def g(): ... sys.exc_clear() ... f() ... print sys.exc_info() ... >>> g() (, , ) (, , ) (None, None, None) >>> Evidently Python does clear the exception when you leave the exception handler, it is just that the exception handler stretches a bit further than you might expect. This of course matters more when you put the exception handler inside a loop, or do more processing after the handler has caught the exception. I'm not sure how much effect it would have to restrict the handler to actually inside the except clause. In fact further investigation shows that the exception context is saved and restored across function calls: >>> def h(): ... try: ... raise ValueError, 'h' ... except: ... print sys.exc_info() ... f() ... print sys.exc_info() ... >>> h() (, , ) (, , ) (, , ) (, , ) >>> I never knew it did that. From peter at engcorp.com Thu Jun 10 22:31:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 22:31:43 -0400 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Roger Binns wrote: > The correct answer of course is that the object itself > should be aware that it needs to be disposed of and that > real world resources can leak if it isn't. > > Which brings us back in a full loop. Currently objects > signify that they need disposing by having a destructor. > Why not "fix" that mechanism? Very likely the answer is "Because nobody has yet proposed a workable solution to the several conflicting requirements". Do _you_ have a solution? If you do and it really works, it seems to me unlikely it would be ignored... -Peter From peufeu at free.fr Wed Jun 23 17:07:55 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Wed, 23 Jun 2004 23:07:55 +0200 Subject: parsing References: Message-ID: Try YAML http://yaml.org/ Example YAML file from their site : import yaml yaml.load( data below ) et voil?... it's done... read the site, it's really worth a look. This format is great for data serialization, and very human-readable unlike XML. invoice: 34843 date : 2001-01-23 bill-to: &id001 given : Chris family : Dumars address: lines: | 458 Walkman Dr. Suite #292 city : Royal Oak state : MI postal : 48046 ship-to: *id001 product: - sku : BL394D quantity : 4 description : Basketball price : 450.00 - sku : BL4438H quantity : 1 description : Super Hoop price : 2392.00 tax : 251.42 total: 4443.52 comments: > Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. > > I would like to use Python to parse a *python-like* data description > language. That is, it would have it's own keywords, but would have a > syntax like Python. For instance: > > Ob1 ('A'): > Ob2 ('B'): > Ob3 ('D') > Ob3 ('E') > Ob2 ('C') > > I'm looking for the ':' and indentation to provide nested execution so I > can use a description like the one above to construct an object tree. > > In looking at the parser and tokenize sections of the Python Language > Services (http://docs.python.org/lib/language.html), it looks as though > this will only parse Python keywords. Is there a way to tap into Python > parsing at a lower level so that I can use it to parse my own keywords? > > Thanks, > Todd Moyer > > > > -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From rupole at hotmail.com Mon Jun 21 18:14:47 2004 From: rupole at hotmail.com (Roger Upole) Date: Mon, 21 Jun 2004 18:14:47 -0400 Subject: Running the makepy tool automatically from a python script References: <67c8710b.0406211039.1824b6dc@posting.google.com> Message-ID: <40d759fb_2@127.0.0.1> win32com.client.gencache.EnsureDispatch('your.application') will generate the makepy module for the interface if it doesn't already exist. hth Roger "Svenn-Ivar Svendsen" wrote in message news:67c8710b.0406211039.1824b6dc at posting.google.com... > Hi, > I use the makepy tool in pythonwin to generate wrappers for my > connection point (event) interfaces in a project. It works fine. > The question is; Is it possible, in a python script, to detect if > wrappers for COM (event) interfaces the script uses have been created, > and in case not somehow call the makepy tool manually before > proceeding? How should this be done? > Best regards, > Svenn-Ivar From brittis at panthermail.tii.se Mon Jun 14 11:14:17 2004 From: brittis at panthermail.tii.se (Britt-Mari Andersson) Date: Mon, 14 Jun 2004 17:14:17 +0200 (CEST) Subject: This is a recording... [Re: E-vykort!] Message-ID: <20040614151417.1CE7C2F0942@panthermail.tii.se> I will be away on holiday until the 19th of July. I won't be reading my mail during this time. There will be someone present at the admin, so if necessary please contact one of the other girls in Stockholm. Let the sun shine in................ Britt-Marie Andersson From steve.menard at videotron.ca Wed Jun 16 13:26:11 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Wed, 16 Jun 2004 13:26:11 -0400 Subject: Something simular to java's hsqldb for python?? In-Reply-To: <792ea523.0406160601.1b217d78@posting.google.com> References: <792ea523.0406160601.1b217d78@posting.google.com> Message-ID: <1t%zc.107045$CD5.1376605@weber.videotron.net> pet100us wrote: > Hi, > > Is there some program that is simular to java's hsqldb > (http://hsqldb.sourceforge.net/). It is a relational database that can > easily be used within a small java program without installing a MySQL, > Postgresql etc. It is used within the same virtual machine whitout > installing anything extra. > > Is there somthing similar for python? I need a small database that I > can build into my application. When the program starts the database > should start and when the programm exits the database can stop. I know > that the samething could be done with xml files or binary files. The > database has some advantages. e.g. when I want to change the program > that it uses a "real" database I dont need to replace much of the > code. I just change the database driver an off we go. (the programmers > dream) > > Thanks in advance > pet100us Others have mentioned SQLlite. There is also gadfly ( http://gadfly.sourceforge.net/ ) which while less efficient than sqllite, is pure python and thus more portable. Steve From holcombea at cardiff.ac.uk Sun Jun 6 19:35:45 2004 From: holcombea at cardiff.ac.uk (Alex Holcombe) Date: 6 Jun 2004 16:35:45 -0700 Subject: OSX IDE usability issues Message-ID: <1b720baf.0406061535.241aebbc@posting.google.com> ?One thing that attracted me to Python was the prospect of significantly shorter debugging times and debug-execution cycles thanks to Python being an interpreted rather than compiled language. In the case of MATLAB, the interpreted language I use currently, programming is quite speedy because one can test small sets of lines of code by copying them directly from the program file to the command line and debugging them in isolation- e.g. allowing one to easily set individual variables manually and checking the result. ? I was disappointed to find that I was not able to do this with Python programs using OSX's PythonIDE (also I didn't find any alternative IDEs on the web that might take care of this). ?I am a newbie, so I may be wrong, but there appear to be three reasons for this. ? 1. when I copy text from a Python script (using command-C or the menu) and paste it in on the command line, only the first line of the text is actually executed, even though manually entering the same lines one by one with carriage returns between them does execute the code perfectly. ?Why the problem with pasting occurs I don't know- does anyone know? ? 2.Even if the above did work, trying to execute a few lines of code out of a Python script should typically not work, if I understand Python syntax correctly. ?Because to Python indentation whitespace is meaningful, one cannot e.g. copy the contents out of a nested if-then statement and expect it to execute, because when you paste the text it will have that level of indentation still rather than having no indentation as it should. ?Am I right about this and is there a way around it? 3. One nice thing about MATLAB is I can execute a script and then query the values of all the script's variables from the command line. By just typing the variable name, I can see its value. ?In contrast, it appears that in Python variables have more restricted scope such that the command line can't "see" the variables executed in a Python script. ?Is there some way to make the variables in a Python script global so that I can play with them on the command line? Without solutions or workarounds to the above three issues, much of the everyday efficiency advantage of using an interpreted language seems to me to be lost. ?So despite the beauty of Python, for my new laboratory I might end up using MATLAB and Psychophysics toolbox instead (presuming they someday get that to work with OSX!). ? Thanks in advance for any corrections comments etc., Alex Holcombe From jan.dries at dcube-resource.be Wed Jun 9 13:40:02 2004 From: jan.dries at dcube-resource.be (Jan Dries) Date: Wed, 09 Jun 2004 19:40:02 +0200 Subject: Auth API in Python In-Reply-To: References: Message-ID: <40C74B72.6040905@dcube-resource.be> Peter Maas wrote: > Is there such a thing in Python or attempts to build one? Something > like JAAS for Java? Depending on what you are looking for, you may want to look at Pubcookie (www.pubcookie.org). It is only useful if you're trying to secure access to web applications, but it does a fine job at that. It's not written in Python, but you never really need to interact with it directly, as it takes authentication completely out of the application. It has pluggable authentication methods (which can be a Python script), and works well on Unix and Windows, with both Apache and IIS. Regarding, Jan From rogerb at rogerbinns.com Fri Jun 11 16:41:41 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 11 Jun 2004 13:41:41 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Duncan Booth wrote: > The object itself can know that it needs to be safely disposed of, but it > cannot tell *when* to dispose of itself. My example function might create > multiple objects some of which need disposing when the function returns, > and others have a longer lifetime. The choice between disposing at the end > of the function or when some containing object is disposed has to be one > for the caller. You have totally confused me now. Ignoring special cases such as cycles, Python destructs an object when there are no references left to it, and in CPython that happens at the moment the last reference is released. So in normal code the objects will go away as names referencing them go out of scope. If the Python object is a proxy for another non-Python visible object (such as a C level filehandle or GUI Window). In those cases the extension module author has to deal with the situation, either by adding an extra reference (the C level object is then the remaining reference) or handling the lifetime of the C level object independently. But for this thread, the actual problem is that __del__ methods may not be called on objects, and if you read the doc implies they almost never will be called. So we have the counter-intuitive (and IMHO user hostile) situation where someone marks a class as needing extra code to run to destroy it, and Python addresses that by saying you will be lucky if the object will be destroyed (ie by not destroying the object). The band aid is requiring the programmer/caller to call various "close" methods (effectively manually calling a destructor equivalent) with all the issues that entail, get real complex real quick and are prone to errors or ommissions, and are extremely difficult to test. And you can see the difficulties in this thread with the issues of just dealing with a single file handle. I certainly agree that dealing with destructors from a language implementor's point of view is hard. Try dealing with cycles, resurrection, exceptions etc. But handwaving and just not running them coupled with expecting manual code by callers all over the place is a bad solution. Garbage collection is also hard, but all recent languages do it. Roger From me at privacy.net Thu Jun 10 05:52:29 2004 From: me at privacy.net (Duncan Booth) Date: 10 Jun 2004 09:52:29 GMT Subject: lenght of char buffers in PyArg_ParseTuple References: <10cg839aq5cv53e@corp.supernews.com> Message-ID: Patrick Stinson wrote in news:10cg839aq5cv53e at corp.supernews.com: > is there any way to figure out how long the string buffer of a passed > string object was after PyArg_ParseTuple(args, "s", &mybuffer)? No, but there is if you call PyArg_ParseTuple(args, "s#", &mybuffer, &length) instead. From jjl at pobox.com Wed Jun 9 19:06:17 2004 From: jjl at pobox.com (John J. Lee) Date: 10 Jun 2004 00:06:17 +0100 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfihFq4aunU1@uni-berlin.de> Message-ID: <87vfi0ib6e.fsf@pobox.com> "Claudio Grondi" writes: > I wonder why the subject (Python scripting within HTML) is not > occuring in any past postings - do I miss something very obvious? [...] That subject line appears in all three of your recent posts. No need to repeat your posts more than once. John From fowlertrainer at anonym.hu Mon Jun 21 04:41:28 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 21 Jun 2004 10:41:28 +0200 Subject: How to do special encode in string ? Message-ID: <40D69F38.9000308@anonym.hu> Hi ! I'm hungarian, we use special characters like: ? - a' ? -o" etc. I want to encode this characters to in config file I see these characters as \nnn format. And I want to decode it automatically with python. How to I do it without write complex converter tool ? Thanx for it: FT Example: Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" From M.Waack at gmx.de Tue Jun 15 17:44:33 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 15 Jun 2004 23:44:33 +0200 Subject: Proper way to kill child processes References: Message-ID: <1774q1-63c.ln1@valpo.de> Bob Swerdlow wrote: > My application starts up a number of processes for various purposes > using: > self.popen = popen2.Popen3("/usr/local/bin/python -O > "myscript.py") This works for me: self.popen = popen2.Popen3(["python", "/usr/local/bin/python", "-O", "myscript.py"]) But I don't know if its a hack or a desired feature. Mathias From jepler at unpythonic.net Sat Jun 5 11:05:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 5 Jun 2004 10:05:46 -0500 Subject: SPA - Best way of implementation In-Reply-To: References: Message-ID: <20040605150546.GA8881@unpythonic.net> Here's an algorithm to find the shortest path from start to end. It is not Dijkstra's "single source shortest paths" algorithm, and that a crucial step of the BFS is O(|queue|) instead of O(1). def shortest_path(start, end, adj): seen = {start: None} # XXX use sets here instead queue = [[start]] while queue: partial = queue.pop(0) # XXX this is O(|queue|) tail = partial[-1] for edge in adj[tail]: if edge in seen: continue seen[edge] = None next_partial = partial + [edge] if edge == end: return next_partial queue.append(next_partial) >>> edges = {'A': 'K', 'K': 'R', 'R': 'BC', 'B': 'I', 'I': 'C'} >>> "".join(mallek.shortest_path('A', 'C', edges)) 'AKRC' Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rgacote at AppropriateSolutions.com Wed Jun 16 08:58:24 2004 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Wed, 16 Jun 2004 08:58:24 -0400 Subject: how to become a really good Python programmer? In-Reply-To: References: Message-ID: At 1:06 AM -0500 6/16/04, Randall Smith wrote: >I've been programming in Python for about 2 years. I think it >offers the best combination of simplicity and power of any language >I have explored. As I write more and larger and complex programs, I >need to code better. By better I mean clearer, cleaner, more >efficient and maintainable. As the subject states, I want to become >a really good Python programmer. I learn most everything from >random examples and experience and that's good, but now I would like >some sound, directed guidance. Following Guido around would be >ideal, but I will settle for a good book. Any recommendations for >learning resources? > >Randall >-- >http://mail.python.org/mailman/listinfo/python-list Hi Randall: Some random thoughts in random order. 1: Write lots of code. 2: Show it to other Python programmer's for comment/criticism. 3: Show it to other non-Python programmer's who will question why you did it a certain way. 4: Write lots of code. 5: Read about Python, product design (not just software), aesthetics, style. Python idiom. 6: Spend time in an art museum. 7: Go back and review, re-document, and redesign what you wrote last year. 8: Use other languages (Lisp, Java, Smalltalk, C++, C#, Perl, ...) to understand their approach to problem solving. 9: Test lots of code and try different approaches to solving the same problem. 10: Read lots of other people's code. 11: Walk through your code in the debugger. 12: Become familiar with one assembler language and walking through it in a debugger. 13 Become comfortable with Python idioms so your code 'looks like' the Python way to do things. 14: Oh yes, write lots of code. --Ray -- From flupke at nonexistingdomain.com Mon Jun 7 08:34:21 2004 From: flupke at nonexistingdomain.com (flupke) Date: Mon, 07 Jun 2004 12:34:21 GMT Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: "Timo Virkkala" schreef in bericht news:bB2wc.289$N94.214 at read3.inet.fi... > flupke wrote: > > There's no excuse for not having a decent search function. period. > > http://starship.python.net/crew/theller/pyhelp.cgi > > -- > WT This indeed helps a lot. I've entered the search key file to simulate what i would do if i wanted to know how to write to a file but didn't know where to start. (This is actually one of the cases where the Python docs are very clear and the info is easy to find). Then i find a lot of usefull info. Now this should be part of the main python site! Thanks From tim.one at comcast.net Thu Jun 10 21:09:49 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jun 2004 21:09:49 -0400 Subject: reference counting and PyTuple_SetItem In-Reply-To: <40C8AC0F.9010503@unidata.ucar.edu> Message-ID: [Anne Wilson] ... > Now I'm testing this: > > > while() { > pyFiveMinArgs = PyTuple_New(PY_CALL_ARG_CNT); > PyTuple_SetItem(pyFiveMinArgs, 0, PyInt_FromLong(300L)); > PyTuple_SetItem(pyFiveMinArgs, 1, PyInt_FromLong(1L)); > PyTuple_SetItem(pyFiveMinArgs, 2, PyString_FromString("5min")); > PyTuple_SetItem(pyFiveMinArgs, 3, PyString_FromString(statsDir)); > PyTuple_SetItem(pyFiveMinArgs, 4, PyString_FromString(rHost)); > > pyOneHourArgs = PyTuple_New(PY_CALL_ARG_CNT); > PyTuple_SetItem(pyOneHourArgs, 0, PyInt_FromLong(3600L)); > PyTuple_SetItem(pyOneHourArgs, 1, PyInt_FromLong(15L)); > PyTuple_SetItem(pyOneHourArgs, 2, PyString_FromString("1hr")); > PyTuple_SetItem(pyOneHourArgs, 3, PyString_FromString(statsDir)); > PyTuple_SetItem(pyOneHourArgs, 4, PyString_FromString(rHost)); > ... > > pyValue = PyObject_CallObject(pyFunc, pyFiveMinArgs); > Py_DECREF(pyValue); > pyValue = PyObject_CallObject(pyFunc, pyOneHourArgs); > Py_DECREF(pyValue); > > ... > Py_DECREF(pyFiveMinArgs); > Py_DECREF(pyOneHourArgs); > } > > > But, OW! It pains me to be so inefficient, creating the same damn > PyObjects over and over and over and over and over again. OTOH, it's so clear as to be darned-near obvious now -- even though it's still wrong To me this is way beyond "micro" optimization. In my own code I'm > actually doing this for three more cases beyond the fiveMin and oneHour > stuff shown above. Does it matter? That is, have you profiled the code and determined that this part is a bottleneck? If not, optimization will introduce bugs and waste *your* time (not to mention mine ). > Is there a more efficient way to do this embedded call? Ignoring error-checking, most people would float the argument construction outside the loop (faster), and use a higher-level API function to do the calls (slower); e.g., i1 = PyInt_FromLong(1); i15 = PyInt_FromLong(15); i300 = PyInt_FromLong(300); i3600 = PyInt_FromLong(3600); statsdir = PyString_FromString(statsDir); srhost = PyString_FromString(rHost); s5min = PyString_FromString("5min"); s1hr = PyString_FromString("1hr"); while() { pyValue = PyObject_CallFunction(pyFunc, "OOOOO", i300, i1, s5min, statsdir, srhost); Py_DECREF(pyValue); pyValue = PyObject_CallFunction(pyFunc, , "OOOOO", i3600, i15, s1hr, statsdir, srhost); Py_DECREF(pyValue); } Py_DECREF(i1); Py_DECREF(i15); [etc] > (... other than rewriting the Python code in C...) Can I use a list > instead of tuple? Not unless pyFunc takes a list as an argument. You would have exactly the same refcount woes: it's not tuples that cause those, it's trying to optimize low-level operations with flawed understanding of how they work. "Do the simplest thing that could possibly work" is good advice here. Write tests (preferably before coding) to ensure that things continue to work. If timing shows the code is truly too slow, and profiling shows that this part is truly the bottleneck, then it *may* be good to trade off maintainability for speed. But what you're doing in the C loop here is almost certainly insignificantly expensive compared to the overhead of calling back into Python at all. Indeed, I'd seriously question why this part is coded in C at all -- it's buying you bugs, but I'm not sure it's buying you anything worth having. From kirk at strauser.com Thu Jun 10 20:25:07 2004 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 11 Jun 2004 00:25:07 GMT Subject: Deeply-nested class layout suggestions wanted Message-ID: <87oenrq6vy.fsf@strauser.com> This is a long post, but I tried to keep it clean and concise. Please don't just skip over it because it has a lot of stuff - I really need some help. I want to get a project off on the right foot but lack the experience to be sure I'm doing it as efficiently [0] as possible. I'm creating a set of classes to implement an API [1]. It looks something like below, with the exception that I'm writing this from home and am not posting the several thousand lines of code. Suffice it to say that the program works alright, but I'm looking for a way to organize it for clean future expansion: FileRetriever.py: class DataSource: def __init__(self): self.containers = [] for container in remoteSource(): self.containers.append(Container(container)) class Container: def __init__(self, container): self.files = [] for subfile in message: self.files.append(DataStore(subfile)) class DataStore: def __init__(self, subfile): self.param1 = someTransform(attachment) self.param2 = someOtherTransform(attachment) self.param3 = YetAnotherTransform(attachment) def classMethodOne(self): pass ... def classMethodTwenty(self): pass Now, the problem is that I plan to subclass the heck out of each of these classes, with overloading appropriate to the type of data source being represented. For example, a DataSource that retrieves images from a POP3 mailbox might be defined like: POP3Retriever.py: import FileRetriever class POP3DataSource(Datasource): def __init__(self): self.containers = [] for message in getPop3MessageList(): self.containers.append(Container(message)) class POP3Container(Container): def __init__(self, message): self.files = [] for attachment in message: self.files.append(DataStore(attachment)) Such a class will be further subclassed into modules like POP3TiffFile, POP3ZipArchive, etc., the goal being to keep all functionality as high in the inheritence hierarchy as possible, so that the "leaf" modules define nothing more than the bare minimum possible to distinguish each other. I'd like to carry this to the point of not defining any classes that are the same between siblings (the DataSource class is identical between all of the different POP3Retriever subclasses, for example). I've only been heavily using Python for about a year and haven't leaned too heavily on inheritence yet, so I want to do this the right way. First, a question on file layout. I've thought about several ways to classify these modules: 1) Stick each set of classes in a file in the same directory. That is, FileRetriever.py, POP3Retriever.py, POP3TiffFile.py, etc. are all in the same place. 2) Create a tree like: + FileRetriever +-- __init__.py +-- DataSource.py +-- Container.py +-- DataStore.py +-- POP3Retriever | +-- __init__.py | +-- DataSource.py | +-- Container.py | +-- DataStore.py | +-- POP3TiffFile | | +-- __init__.py | | +-- DataStore.py | +-- POP3ZipArchive | +-- __init__.py | +-- Container.py +-- SFTPRetriever +-- __init__.py ... ... 3) Just kidding. I only have two ideas. The first layout has the advantage that it's simple and involves a minimum of files, but has annoying quirks such as if I define a DataSource subclass before a Container subclass, then that DataSource will use the parent's Container class since the local one hasn't been defined yet when the local DataSource definition is being read. The second layout has more files to deal with, but (hopefully?) avoids that dependency on defining things in a particular order. Second, what's a good way to name each of the classes? Again, I see two main possibilities: 1) Name all of the DataSource classes "DataSource", and explicitly name the parent class: class DataSource(FileRetriever.DataSource): 2) Name all of the DataSource classes with some variation: class POP3ZipArchive(POP3Retriever): The first seems preferable, in that whenever a client program wants to use one of the leaf classes, it will always be named DataSource. However, that seems like a whole lotta namespace confusion that could come back to bite me if I didn't do it right ("What do you mean I accidentally inherited CarrierPigeonDataSource and nuked all of the files our customer uploaded?!?"). I ask all of this because the project is still relatively young and malleable, and this is something that will have to be maintained and expanded for years to come. I want to take the time now to build a solid foundation, but I don't have enough experience with Python to have a good grasp on recommended styles. [0] "Efficient" being hereby defined as "easy for me to understand when I revisit the code six months from now". [1] We receive files from our customers via many means - fax, email, ftp, you name it. I'm developing delivery method agnostic tools to manipulate those files and flatly refuse to write n tools to handle n methods. -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ From bogus_address at nospam.com Wed Jun 30 18:48:43 2004 From: bogus_address at nospam.com (Conrad) Date: Wed, 30 Jun 2004 22:48:43 GMT Subject: Time delay loop - better way? Message-ID: Greetings, Q: Is there some way to gracefully suspend a python app for a second or so then resume? I could write the classic basic dumb loop-tenzillion-times delay, but that seems inelegant, and well, just wrong. By the way, I'm also using wxPython, if that helps any. I need to delay a python program for about a second. Googling around, it looks like most of the timer stuff has to do with thread handling, but my application is not threaded, just a small app that has problems printing to a serial label printer if there's not some delay between labels. The best solution would be if the freakin printer worked right, but I've tried all the possible flow control settings in pyserial and the windows com port, and apparently there just has to be some magic undocumented delay between labels, or they get screwed up. Not a huge crisis, I admit, as I can work around with a dumb loop, but again - I know there's a more correct way to do this. Thanks, Conrad From dwelch91 at comcast.net Sat Jun 5 12:37:34 2004 From: dwelch91 at comcast.net (djw) Date: Sat, 05 Jun 2004 16:37:34 GMT Subject: Python Speed Question and Opinion In-Reply-To: <40c1e793$0$563$e4fe514c@news.xs4all.nl> References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Maboroshi wrote: > > >> In my opinion Python is the best language there is and I love it. The >> reason for me asking these questions was because I saw a lot of people >> trying to compare python to C and I had to find out what the big deal was >> and why C would be a faster language - I like to know how things work - > > > > I have taken the liberty of taking a few of the comments made > in this thread and writing them down here: > http://www.razorvine.net/python/PythonSpeed > I've added a few other things related to Python's performance, > such as a short reference to Psyco. > > > --Irmen de Jong. > I don't think I agree with your statement at the bottom that says "if all else fails, try Psyco." Since using Psyco is so effortless and may produce dramatic speedups, I would recommend to people that they try it before resorting to writing extension modules in C/C++. Sending people that are new to Python down the extension writing path may turn them off to Python altogether. -Don From zhimin at iss.nus.edu.sg Fri Jun 11 04:40:40 2004 From: zhimin at iss.nus.edu.sg (Zhi Min) Date: Fri, 11 Jun 2004 16:40:40 +0800 Subject: pystone: pydotorg's RPM scores better than Fedora 2's RPM Message-ID: Hi, I find the pystone varies between the python2.3 from pydotorg (www.python.org) and Fedora Core 2's bundled python. But the highest pystone is obtained from rebuilt RPM from pydotorg source RPM. I use "rpm --replacefiles" to install pydotorg RPM on FC2. Fortunately, those python-based system config tools still works. Here's the pystone score: os, python-version, low, high, ----------------------------------------- FC1, 2.2.3-fc1, 22321, 23923, FC1, 2.3.3-pydotorg, 33557, 35971, FC2, 2.3.3-fc2, 28248, 29585, FC2, 2.3.3-pydotorg, 32467, 33112, FC2, 2.3.4-pydotorg, 31446, 32894, FC2, 2.3.4-pydotorg-src, 35461, 37037, Test condition: Dual Xeon 2.8Ghz, 4GB RAM, hyperthreading on, no cpu binding (no diff if cpu bound) The difference in the source rpm spec file is: - pydotorg disable ipv6 and enable pymalloc - FC2 enable ipv6 but does not specify enable/disable pymalloc Is the pymalloc that improve the pystone score? What is it? -- zhimin From m9x4nz0067d0b5 at messenger.hotmail.com Tue Jun 22 02:55:08 2004 From: m9x4nz0067d0b5 at messenger.hotmail.com (m9x4nz0067d0b5 at messenger.hotmail.com) Date: Tue, 22 Jun 2004 08:55:08 +0200 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: something is going wrong! -------------- next part -------------- A non-text attachment was scrubbed... Name: nothing.zip Type: application/x-zip-compressed Size: 25473 bytes Desc: not available URL: From surrender_it at remove.yahoo.it Sat Jun 26 05:27:54 2004 From: surrender_it at remove.yahoo.it (gabriele renzi) Date: Sat, 26 Jun 2004 09:27:54 GMT Subject: any trick to allow anonymous code blocks in python? References: Message-ID: il Sat, 26 Jun 2004 00:58:49 -0500, Doug Holton ha scritto:: >Perhaps that should be a proposal for Python. It's like the decorators >proposal (318). It just saves an extra step and is helpful for >framework designers (people who use metaclasses, etc.). Instead of >having to do this (or the other ways I mentioned): >def onclick(..): > ...code here >b.onclick = onclick > >You can save a step and just do like you said: >def b.onclick(...): > ...code here > just my two cents: you can do this in ruby with nearly the same syntax: def b.onkclick() ..code here.. end But even if that sounds like a great idea I have to admit it's not widely used, probably because every framework with callbacks like these already uses the common bind-a-function-to-this-event idiom, instead of allowing method overriding. Maybe this relates to the fact that GUI toolkits are mostly C/C++ based, and that years of limited languages have directed our mind toward the 'you have to subclass' dictat. I wonder if SmallTalk GUIs have something like this. It would be nice to have singleton method definition with this syntax in python, anyway. From __peter__ at web.de Sat Jun 19 06:51:56 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jun 2004 12:51:56 +0200 Subject: Help needed: optimizing dictionary creation/access References: <40d3e9fa$0$603$39db0f71@news.song.fi> <40d40e5d$0$1776$39db0f71@news.song.fi> Message-ID: Pekka Niiranen wrote: > does not using tuple (name, keyp, cost) as key make access time linear? I don't see how the kind of key can influence the big-O behaviour of a dict. A hash is a hash is a hash, after all. Or am I missing something? Peter From aahz at pythoncraft.com Sat Jun 5 00:25:21 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Jun 2004 00:25:21 -0400 Subject: Why did no one invent Python before? References: Message-ID: In article , Roy Smith wrote: > >Here's my take on the currently popular languages... > >C took off in the late 70's and early 80's because it was so much better >than the alternatives, and because it was wrapped up with Unix (about >which the same thing can be said). C really was (and still is) a very >good language for what it was intended for: low level procedural >programming. Heh. _The Unix Hater's Handbook_ and "Worse is Better" are just two examples of disagreement with that statement. http://research.microsoft.com/~daniel/uhh-download.html http://www.jwz.org/doc/worse-is-better.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From newsgroups at jhrothjr.com Sat Jun 19 17:33:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 19 Jun 2004 17:33:46 -0400 Subject: Am I crazy regarding the style guide for function names? References: <2jhlvtF11ti8bU1@uni-berlin.de> <10d8shvsq01auf0@corp.supernews.com> Message-ID: <10d9cb3qv3r6mc1@news.supernews.com> "Michael Geary" wrote in message news:10d8shvsq01auf0 at corp.supernews.com... > Peter Hansen wrote: > > Judging by the wording of the "function names" section before > > and after the edit, the earlier version which "allowed" > > mixedCase names was merely being descriptive (saying what > > the codebase currently looked like), while the new version is > > being *prescriptive* (attempting to force a particular style by > > defining it as the standard). > > > > Personally, I don't like the change, but I also have no intention > > of paying attention to it. Now that the editor and tab-wars are > > over, we have to have _something_ to argue over, don't we? ;-) > > I'm glad I'm not the only one. :-) > > ClassesLikeThis and methods_like_this sounds like a way to make everybody > unhappy: people who hate MixedCase and people who hate > names_with_underscores. > > Ruby uses exactly this same convention. I have no idea why. > > Myself, I'm sticking with ClassesLikeThis and methodsLikeThis for my Python > and Ruby code. (I don't like underscores at all!) Likewise. John Roth > > -Mike > > From wezzy at despammed.com Thu Jun 24 10:07:33 2004 From: wezzy at despammed.com (Wezzy) Date: Thu, 24 Jun 2004 16:07:33 +0200 Subject: Applications for ipaq and Palm Pilot References: <40dacb1a$1@newsfeed.netlojix.com> Message-ID: <1gfw7an.9vgrir1e4q9z1N%wezzy@despammed.com> Evan McPeters wrote: > I need to develop an application that will run on an ipaq handhelp and > possibly the Palm Pilot as well. > Can this be done in python? Do I need a special library to make it work? > I'm looking for a Python implementation for Palm but i haven't found anything interesting. i've found only pippy but it seems that the project doesn't grow. The last stable version is python 1.5 :-( if you found something interesting please post -- Ciao Fabio From simoninusa2001 at yahoo.co.uk Wed Jun 30 15:02:42 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 30 Jun 2004 12:02:42 -0700 Subject: TERMIOS.py References: <40e2cf9b$1@pfaff2.ethz.ch> Message-ID: <30260531.0406301102.22289ec1@posting.google.com> Josef Meile wrote: > > under windows : ren TERMIOS.py termios.py > I don't think that's the problem: > first: TEMIOS != termios. They are two different modules: > http://docs.python.org/lib/module-TERMIOSuppercase.html > > second: Those two modules aren't available on windows. > > I guess you either didn't install the module or you have a really old > python. I have TERMIOS.py under Python 2.3.4 for Windows. I think it's actually installed by some other library (pyQt or wxPython IIRC) if you Google it, there is a solution (I think it was basically "just delete them both"). From dave at pythonapocrypha.com Fri Jun 25 10:32:56 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 25 Jun 2004 08:32:56 -0600 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: <040d01c45ac1$4ec38180$6400fea9@boba> Mark wrote: > > Wait, so is the exclamation point required or not? IOW, say you have a > class > > like this: > > > > class List(list): > > def append(self, what): > > list.append(self, what) > > return self > > > > a = List() > > b = a.append(5) > > > > So in the call to append, is it a.append!(5) or just a.append(5) ? If it's > > the former, then does the compiler detect that it's required because the > > function returns 'self' or is the determining factor something else? > > > > Or, does the append method not really return anything, and the language > > takes care of substituting in the object? (in which case, does that mean > you > > can override the return value by adding '!' - such that z=foo.bar!() > ignores > > the return value of bar and z references foo?) > > As I said above: It's not that the exclamation mark that causes append to > return the sequence. The exclamation mark is always there and the sequence > is always returned. In Prothon (and Ruby and other languages before) the > exclamation mark is just part of the method name and is there to warn you > that in-place modification is happening. Ahh...so the method name is just _spelled_ with an exclamation point? IOW, the ! is a token you can use at the end of an identifier, but it is not actually used by the language itself - it's some sort of pseudo-syntax? I think I understand now. But is it truly part of the name in that you are required to include the ! when calling the method? (I'm still thinking of the confusion I'd experience with something like w = x.y.z!() ) So if I want a reference to one of those methods I could end up doing ref = obj.method! or ref! = obj.method! and the program runs the same either way, it's just that in one case the code is misleading? If it's up to the programmer to remember to add it (meaning that it doesn't cause an error to forget to use it), and if is really just part of the name, then it's just a naming convention, right? Wouldn't you get the same result by establishing the convention that e.g. method names ending in a single underscore signify in-place modification (foo.append_() ) ? Seems like a waste to reserve a symbol for something so rarely needed. > > Personally, I don't like the modify-in-place-and-return-the-object > > 'feature' - it's not needed _that_ often, but more importantly, it makes > the > > code harder to read (to me at least). > > If you use the Prothon append!() exactly as you use the Python append() you > will get the exact same results. This is just an extra feature for those > that want it. > > Guido avoided returning values from in-place modification functions because > of the confusion as to whether in-place mods were happening or not. We have > solved that confusion with the exclamation mark. Our code is very readable > because of this. Clearly, readability is in the eye of the beholder. :) -Dave From davidf at sjsoft.com Mon Jun 14 11:02:23 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 14 Jun 2004 17:02:23 +0200 Subject: Generic database dictionary access In-Reply-To: References: Message-ID: Edward Diener wrote: > Version 2.0 of the Python database API was written over 5 years ago, in > 1999. While it has been used successfully by many implementations, there is > no generic access into the data dictionary of relational databases except at > the table column level. I am working on some Python which would hopefully > give me a form of generic access to more common data dictionary > functionality such as indices, constraints etc. but no such functionality > currently exists in the official Python distribution. Has there been any > movement in the 5 year time span since the 2.0 API was published to add > richer generic functionality for relational databases as regards data > dictionary access ? I fully realize that each major RDBMS has its own > methods for programatically querying its data dictionary, and I suspect that > there is no common SQL specification for doing so, but I would think that > richer functionality along these lines might be welcome to Python database > programmers other than myself. > > Hear Hear. This would be a welcome improvement. Note that you could create it as a library that runs on top of DB-API drivers and knows various flavours of database, and then work towards standardizing the interface... I for one would be interested in the library David From irmen at -nospam-remove-this-xs4all.nl Mon Jun 21 14:04:50 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 21 Jun 2004 20:04:50 +0200 Subject: ANN: kronos, a task scheduler In-Reply-To: References: <40ad1f5c$0$36860$e4fe514c@news.xs4all.nl> <95aa1afa.0405211958.57ae218b@posting.google.com> <40af3b46$0$65124$e4fe514c@news.xs4all.nl> Message-ID: <40d72342$0$563$e4fe514c@news.xs4all.nl> rosendo wrote: > Can you publish some usage or examples or a man pages?. > Will help those who want to use this module! :-) Use the source, Luke! :-) Seriously: there are lots of comments in the Kronos.py source code. Is there something not clear? It also contains a ready-to-run example in main()... I've placed a slightly updated version of the scheduler at http://www.razorvine.net/downloads.html --Irmen. From gumuz at NO_looze_SPAM.net Tue Jun 8 05:41:43 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Tue, 8 Jun 2004 11:41:43 +0200 Subject: About a plugin framework! References: Message-ID: <40c589ca$0$5071$4d4ebb8e@news.nl.uu.net> Hi, change: cn = pxml.GetClassname() into: cn = globals()[pxml.GetClassname()] your line returns a string, the name of your class, which is not callable the correct line looks up the name in your globals() dict and returns a callable. cheers, guyon ========================================================== "Simon Roses Femerling" wrote in message news:mailman.693.1086683764.6949.python-list at python.org... Dear pythonnians :) Hopeful somebody can help me about implementing plugin support. I'm working on a python/wxpython app that needs plugin support. My problem is: The way my app works is a python module (plugin) that contains (imbedded) XML defining the classname and some extra information and the app will be load the module using the classname: Example: ------ mymodule.py ---- __xml__ =""" Test """ class Test: def Msg(self): print "Hello" --------------------------------- --- MyApp.py ----------- fp = open(f) exec(fp) in globals() str = __xml__ pxml = parsexml.ParseXML() pxml.BeginParse(str) cn = pxml.GetClassname() mymod = cn() <-- Here is the error mymod.Msg() ---------------------------------- The error is: Traceback (most recent call last): File "blackout.py", line 503, in onAttackMod mymod = cn() TypeError: 'unicode' object is not callable Any suggestions ? How can achieve this ? Each module (plugin) can have a different class name defined in the XML data. Besides this anyone have suggestions for a better plugin framework ? Maybe using imp module to dynamically import modules ? Any examples ? Thx for any help! Sincerely SRF From missive at frontiernet.net Wed Jun 23 16:52:10 2004 From: missive at frontiernet.net (Lee Harr) Date: Wed, 23 Jun 2004 20:52:10 GMT Subject: get screen output to file using get_payload() References: Message-ID: <_3mCc.46$Vr6.26@news01.roc.ny> On 2004-06-23, chuck amadi wrote: > Hi I have managed to print the output of the get_payload to screen > but I need to write to a file as I only require the email body messages > from the mailbox.My script using the fp.readlines() function writes the > entire contents of the mailbox of cause including the headers of the > emails I do not want. > > I have tried a few things but I cant get to my goal.Any ideas or > pointers I need only the email body and I cant figute out why I can > using the print statement but get those results to a file. > cheers > > mailout = file("/home/chucka/pythonScript/SurveyResults1.txt","r") > You have the file opened read only. You would need something like: mailout = file("/home/chucka/pythonScript/SurveyResults1.txt", "w") From yves.roy at umontreal.ca Thu Jun 10 13:01:48 2004 From: yves.roy at umontreal.ca (Roy Yves) Date: Thu, 10 Jun 2004 13:01:48 -0400 Subject: Compiling pymat: invalid conversion from `const maybelong*' to `int*' Message-ID: Hi: I am compiling pymat and I get this error all over the place: invalid conversion from `const maybelong*' to `int*' (see below) Any idea what I should do to solve that ? Thanks Roy make install g++ -c pymat.C -o pymat.o -I/usr/local/matlab6p5/extern/include -I/usr/include/python2.2/numarray -I/usr/include/python2.2 pymat.C: In function `mxArray* makeMxFromNumeric(const PyArrayObject*)': pymat.C:218: invalid conversion from `const maybelong*' to `int*' pymat.C:218: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = char]' pymat.C:221: duplicate case value pymat.C:217: previously used here pymat.C:222: invalid conversion from `const maybelong*' to `int*' pymat.C:222: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = unsigned char]' pymat.C:226: invalid conversion from `const maybelong*' to `int*' pymat.C:226: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = signed char]' pymat.C:230: invalid conversion from `const maybelong*' to `int*' pymat.C:230: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = short int]' pymat.C:234: invalid conversion from `const maybelong*' to `int*' pymat.C:234: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = int]' pymat.C:237: duplicate case value pymat.C:233: previously used here pymat.C:238: invalid conversion from `const maybelong*' to `int*' pymat.C:238: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = long int]' pymat.C:242: invalid conversion from `const maybelong*' to `int*' pymat.C:242: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = float]' pymat.C:246: invalid conversion from `const maybelong*' to `int*' pymat.C:246: initializing argument 5 of `void copyNumeric2Mx(T*, int, int, double*, int*) [with T = double]' pymat.C:250: invalid conversion from `const maybelong*' to `int*' pymat.C:250: initializing argument 6 of `void copyCplxNumeric2Mx(T*, int, int, double*, double*, int*) [with T = float]' pymat.C:254: invalid conversion from `const maybelong*' to `int*' pymat.C:254: initializing argument 6 of `void copyCplxNumeric2Mx(T*, int, int, double*, double*, int*) [with T = double]' pymat.C: In function `mxArray* numeric2mx(const PyObject*)': pymat.C:296: invalid conversion from `const PyObject*' to `PyObject*' make: *** [pymat.o] Error 1 Compilation exited abnormally with code 2 at Thu Jun 10 12:49:28 From news01 at metrak.KILLSPAM.com Mon Jun 28 08:31:53 2004 From: news01 at metrak.KILLSPAM.com (sosman) Date: Mon, 28 Jun 2004 22:31:53 +1000 Subject: unpickle error Message-ID: <40e00fdb$0$18195$afc38c87@news.optusnet.com.au> After pickling several lists of objects using protocol 2, when I unpickle I get: TypeError: ord() expected a character, but string of length 0 found When I use protocol 0 (ascii) this doesn't occur. Now it is almost certainly something I have stuffed up but it is not obvious to me how to debug this kind of problem. When I mean pickling several lists, I open a file, call dump for each list of objects then close the file. Similarly for unpickling. -- brewiki: http://www.metrak.com/wiki/homebrew/ From donn at u.washington.edu Fri Jun 11 12:09:05 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 11 Jun 2004 09:09:05 -0700 Subject: webrowser and linux (also os.execv) References: Message-ID: In article , Tim Newsham wrote: ... > Oh, on an unrelated note, the os.execv and os.execve functions > do not allow an empty argv to be passed in, even though the > underlying C/Unix primitives do. Although it is rare that > one would want to pass in an empty argv (with argc set to zero) > there are rare situations when this is desired. The fact > that python tries to protect the user from making a mistake > by limiting the flexibility of the API is a deficiency. On MacOS X, non-empty is a documented requirement for execve and its C library wrappers like execv, and an attempt to use an empty argv causes a `bus error'. Very likely the same on other Berkeley implementations. I also have a hard time imagining even a rare situation where it would make sense. Donn Cave, donn at u.washington.edu From chrisks at NOSPAMudel.edu Fri Jun 25 00:11:37 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Fri, 25 Jun 2004 00:11:37 -0400 Subject: a small-gui for python/win32 ? In-Reply-To: <40db01fb$0$17144$626a14ce@news.free.fr> References: <40db01fb$0$17144$626a14ce@news.free.fr> Message-ID: marco wrote: > this week, i've seen a little GUI for python/win32 .. > a little library which can use simple dialog (openfile, opendir, > messagebox, progressbar ... and that's all) ... > it worked only on win32 platform > > AND i've not bookmarked the url ;-( (shame on me) > > i've seen that in "daily python url" perhaps ??! > i cant find it again ;-( > > perhaps someone could help me ? > (don't tell me about tk, wx, qt, gtk ... ;-) Doesn't Python come bundled with Tkinter? Isn't Tkinter cross-platform compatible? What's wrong with Tk? For the record, Tk and Wx work on windows. Tk is about as simple a gui library as you can get. From gohaku at earthlink.net Fri Jun 25 12:58:39 2004 From: gohaku at earthlink.net (gohaku) Date: Fri, 25 Jun 2004 12:58:39 -0400 Subject: Is there a Python Audio Library? Message-ID: Hi everyone, I would like to know if there is an audio library that will allow me to create and read .WAV and .MIDI files. When reading .WAV files, I am looking for amplitude information. Thanks. -gohaku From chris.cottee at onepost.net Mon Jun 7 13:27:32 2004 From: chris.cottee at onepost.net (Chris Cottee) Date: 7 Jun 2004 10:27:32 -0700 Subject: Functional test web site using python com and Internet Explorer Message-ID: Hi, I am trying to extend PAMIE (sourceforge project to functionally test web sites using com and python) and I wondered if anyone had done this sort of thing before and had any pointers. My main reason for doing this is that the website I want to test is so full of frames and javascript that it seems painful to try to fix httpunit to be able to cope with it. The difficulties I am having are in getting IE to behave repeatably, handling multiple levels of frames and handling events. In particular when I use dispatchWithEvents instead of Dispatch the IE6 gui almost seems to block (it gets much slower at any rate). Is this to be expected ? I have used pythoncom._GetInterfaceCount() to see if I was getting loads of references but I only have 2. Thanks, Chris From dkturner at telkomsa.net Mon Jun 14 03:00:39 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 00:00:39 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote in message news:<7ipt83o6qp.fsf at enark.csis.hku.hk>... > > Jython is not a separate language. It is just our favourite Python > language, running under the Java virtual machine. Perhaps it is "stifling" > the development of the Python language, but if it is, it is because we > explicitly *don't* want to introduce language dependency (i.e., don't depend > on C-Python implementation) rather than that we want to depend on a certain > language. Different people will have different idea about whether this is a > good thing. For me, I'd say that I prefer finding a different solution to > problems arising from the unspecified finalization behaviour, because > specifying the finalization time will more or less remove a use-case of the > Python language completely, and I do think that being able to use Python > within Java and able to use Java objects from Jython code without additional > "glue code" is something that should be dearly treasured. It is especially > the case because the lack of specification about when finalization happens > is, most of the time, not an issue at all. You don't have to specify the finalization time in order to make the destructors work. Destruction and finalization are *different things*. The D programming language somehow contrives to have both garbage collection and working destructors. So why can't Python? Regards David Turner From tzot at sil-tec.gr Tue Jun 22 05:35:18 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jun 2004 12:35:18 +0300 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: On 14 Jun 2004 00:00:39 -0700, rumours say that dkturner at telkomsa.net (David Turner) might have written: [snip text by Isaac To] >You don't have to specify the finalization time in order to make the >destructors work. Destruction and finalization are *different >things*. >The D programming language somehow contrives to have both garbage >collection and working destructors. So why can't Python? CPython for the time being reliably calls __del__ methods upon the object's end of life, *unless* the object is part of a reference cycle. There are ways to break these cycles. In reply to your question, "why can't Python?", I say: "There are no stack-allocated objects in Python". Counter questions: does D have heap-allocated objects? If yes, how are they finalised before being destructed? And what happens to references to these objects after their destruction? -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From danb_83 at yahoo.com Sat Jun 12 19:17:32 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Jun 2004 16:17:32 -0700 Subject: Newbie array question References: <2d7af4f8.0406112032.4cb4438a@posting.google.com> Message-ID: nhirsh2 at ieee.org (Neale) wrote in message news:<2d7af4f8.0406112032.4cb4438a at posting.google.com>... > My first task with Python is to scan multiple small text files and > "batch together" those records with a "5" or "6" in column 2, and then > save as a new file. The records are 256 characters. I know it sounds > like a homework problem, but it's not. Assuming that all your records are strings in an array called "records", you can discard the ones without a '5' or '6' in column 2 (column 1 in 0-based indexing) with: records = [r for r in records if r[1] in ('5', '6')] From anto at nye.it Tue Jun 8 17:57:20 2004 From: anto at nye.it (Antony) Date: Tue, 08 Jun 2004 21:57:20 GMT Subject: unknown encoding Message-ID: <4Dqxc.45872$Wc.1491118@twister2.libero.it> Hi! i've a problem with py2exe; my prog. on xp gives to me an error of MIMEText.pyc message.pyc Encoders.pyc: LookupError: unknown encoding: ascii ..but in the python idle 2.3 all works fine. Why the .exe doesn't work? From squirrel at WPI.EDU Thu Jun 24 11:34:53 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 24 Jun 2004 11:34:53 -0400 Subject: z80 vs Python In-Reply-To: References: Message-ID: > I have an idea that implements the Python interpreter for z80 as an > universal flexible language (like scripts) to support attached hardware. > What would it be shortest way to do it? > I think of course about C (Zilog has good support of own products...). I wouldn't recommend this. The standard Python interpreter is quite hefty (>700K dynamically linked), not to mention the standard libraries. Seeing as Z80 has only 64K address space, I don't see a full implementation as possible. What you /could/ do would be to implement a (very) small subset of Python; i.e. leave out generators, new-style class, list comprehensions, ability to override built-in types, functions, and operators, and most of the standard library, then you /might/ be able to fit a language with Pythonic syntax in that address space. Another issue would be speed. Z80s, though they've gotten faster over the years, still only run at speeds on the order of 10MHz. You might be better off writing a Z80 compiler for a Python-esque language -- this would save both speed and memory. If you can pick a different chip, go with something like a StrongARM. These have the power and address space necessary for Python. Plus, it's been done before (Python runs beautifully on modern PDAs). If you stick with the Z80 though, you've got quite a challenge ahead of you - good luck! If you succeed, you'll be sure to make hackers of Game Boys, TI-83s, and TRS-80s everywhere deliriously happy. From eurleif at ecritters.biz Sat Jun 12 12:58:23 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 12 Jun 2004 16:58:23 GMT Subject: Teaching Python In-Reply-To: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: Mediocre Person wrote: > So, what pitfalls should I look out for in introducing Python to > students who have had a year of Visual BASIC? I was a Visual Basic programmer for a few months in 2002. It took me almost a year to recover. It is vaguely object-oriented, but its definition of objects are horribly warped; going to a genuine OO language after VB is a complete nightmare. If at all possible, I would recommend changing the Visual Basic class to RealBASIC (http://realbasic.com/). It's not perfect, but it has proper OO support, and would make the transition to Python much easier. Even better would be teaching basic Python to the VB class and more advanced Python to the 12th graders; Python's biggest strength is allowing beginners to use simple OO or even procedural techniques without ever noticing the advanced stuff like list comprehensions and metaclasses. From dalcolmo at vh-s.de Wed Jun 16 09:18:53 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Wed, 16 Jun 2004 15:18:53 +0200 Subject: computer names and samba shares References: Message-ID: <20040616151853.00000628@titan> on Wed, 16 Jun 2004 10:59:13 +0100 Tim Golden wrote: > http://miketeo.net/projects/pysmb/ This seems to do what I was looking for. Thanks for the tips. Best regards - Josef From nemesis at nowhere.invalid Sat Jun 19 05:00:23 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Sat, 19 Jun 2004 09:00:23 GMT Subject: Easiest way to port Python program to PDA References: Message-ID: <5fu0bc.as1.ln@nemesis.homeinvalid> Mentre io pensavo ad una intro simpatica "Jeffrey Barish" scriveva: > have discovered a python for StrongARM Pocket PCs.??There?is?also?a > python port for PalmOS, but that project appears to be dormant.??I?have > also discovered handhelds.org, which explains how to run linux on iPAQ, > but it isn't clear to me that it is possible to run python on the > resulting linux installation. Hmmm I remember that on handelds.org there is the link to the "Familiar" distro, it should come with python+pygtk. -- Life in a vacuum sucks. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From km at mrna.tn.nic.in Mon Jun 28 12:54:05 2004 From: km at mrna.tn.nic.in (km) Date: Mon, 28 Jun 2004 22:24:05 +0530 Subject: wxPython woes Message-ID: <20040628165405.GA25093@mrna.tn.nic.in> Hi all, I feel its a real pain to install wxPython from sources it goes back to install gtk+ etc . may be thats why its not yet become defacto GUI standard for python. but i'd like to know if anyone has made it easy with an installer for wxPython on linux (Debian woody)? regards, KM ps: i have tried installing wxPython with the .deb files availble in testing and unstable section. it doesnt work - unable to load the module From piet at cs.uu.nl Wed Jun 2 17:59:00 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 02 Jun 2004 17:59:00 -0400 Subject: Regexp: unexspected splitting of string in several groups References: <39cbe663.0405310341.430d2035@posting.google.com> Message-ID: >>>>> pit.grinja at gmx.de (Piet) (P) wrote: P> vartypePattern = re.compile("([a-zA-Z]+)(\(.*\))*([^(].*[^)])") P> However, simple one-string expressions like P> vartypeSplit = vartypePattern.match("float") P> are always splitted into two strings. The result is: P> vartypeSplit.groups() = ('flo', None, 'at'). P> I would have either expected ('float',None,None) or ('float','',''). P> For other strings, the last two characters are also found in a P> separate group. P> Is this a bug or a feature? ;-) It is a feature: The last part: [^(].*[^)] says: a character which is not (, possibly more characters and a character which is not ). So at least two characters. Maybe you mean something like [^()]* Or would you like to accept )xxx) or )yyy(? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From ssvendsen at atmel.com Mon Jun 21 14:39:17 2004 From: ssvendsen at atmel.com (Svenn-Ivar Svendsen) Date: 21 Jun 2004 11:39:17 -0700 Subject: Running the makepy tool automatically from a python script Message-ID: <67c8710b.0406211039.1824b6dc@posting.google.com> Hi, I use the makepy tool in pythonwin to generate wrappers for my connection point (event) interfaces in a project. It works fine. The question is; Is it possible, in a python script, to detect if wrappers for COM (event) interfaces the script uses have been created, and in case not somehow call the makepy tool manually before proceeding? How should this be done? Best regards, Svenn-Ivar From peufeu at free.fr Fri Jun 18 03:18:14 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 09:18:14 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: > 2) Evaluate the default expression once at each call time when the > default > value is needed. The default expression would be evaluated in the > context > of the function definition (like a closure). I like Choice 2 because I've always wanted to do the following : def func( x, y=2*x ): do stuff... ie. use default values for function parameters which depend on previous function parameters. This can be very practical at times : before (suppose 'info' is a class which has "text" and "htmlclass" as members): def format_information( info, htmlclass = None ): if htmlclass == None: htmlclass = info.htmlclass return "

    %s

    " % (htmlclass, info.text ) after: def format_information( info, htmlclass = info.htmlcass ): return "

    %s

    " % (htmlclass, info.text ) the intended use would be : format_information( info ) format_information( info, 'red_text' ) overrides the html_class in info. The former example could be simplified (below) but I still think the second example using your choice 2 is more elegant. def format_information( info, htmlclass = None ): return "

    %s

    " % (htmlclass or info.htmlclass, info.text ) From usenet at caesium.me.uk Mon Jun 21 22:45:13 2004 From: usenet at caesium.me.uk (Chris Share) Date: 22 Jun 2004 02:45:13 GMT Subject: Curses and resizing windows Message-ID: I've been writing an application using curses, and have been trying to handle resizing the terminal, if running in xterm or similar. Increasing the window size is working perfectly, however shrinking it is not working at all. No matter how much I shrink the window, the size returned by getmaxyx() does not change. However as soon as I increase it again, it works fine. I've tracked the problem down to the fact I have created a window derived from stdscr. A small script showing the effect is at the end of this post. Can anyone suggest how to solve this problem, that doesn't involve not making a derwin of stdscr? I've been googling for hours, but found nothing to help. Python version is 2.3.4 on debian testing. chris #!/usr/bin/python import curses, sys def init_display(stdscr): stdscr.clear() stdscr.refresh() size = stdscr.getmaxyx() sys.stderr.write("Now %u x %u\n" % (size[1],size[0])) rootwin = stdscr.derwin(20, 50, 0, 0) return rootwin def main(stdscr): rootwin = init_display(stdscr) while 1: input = rootwin.getch() if ( input == curses.KEY_RESIZE): init_display(stdscr) elif input == ord("q"): sys.exit() rootwin.refresh() curses.wrapper(main) From bart_nessux at hotmail.com Thu Jun 3 08:13:28 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 03 Jun 2004 08:13:28 -0400 Subject: file fragmentation project In-Reply-To: <87ise9tykr.fsf@strauser.com> References: <87ise9tykr.fsf@strauser.com> Message-ID: Thanks for the advice Kirk, I appreciate it. Kirk Strauser wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > At 2004-06-02T21:10:02Z, Bart Nessux writes: > > >>In particular, I'd like to write a file fragmentor in Python that will >>randomly fragment x% of files on a NTFS filesystem into y number of >>fragments. > > > You may or may not be able to do so, depending on how smart your exact > version of NTFS decides to be on that given day. Still, the standard > algorithm to fragment a file m bytes long into n pieces is: > > 1) Create n * 2 files, each (m/n) bytes long. > 2) Delete every other file. > 3) Write the file to be fragmented, and hope that the filesystem naively > shoves it into the empty holes. > 4) Delete the remaining "pad" files. > > A similar algorithm is to replace step 1 with: > > 1) Fill the entire drive with files (m/n) bytes long. > > If the filesystem isn't smart enough to rearrange empty blocks, then that > should to the trick. > > >>Anyway, would Python be acceptable for this type of project? Speed is >>somewhat important, but not extremely. > > > You bet. Filesystem speed will be the limiting factor. > - -- > Kirk Strauser > The Strauser Group > Open. Solutions. Simple. > http://www.strausergroup.com/ > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (GNU/Linux) > > iD8DBQFAvky35sRg+Y0CpvERAkm9AKCOeYJZ3aEbgcFERo8Iy5dxAKD6aQCeMWEO > bnwx/bkTjkWo+JE/pCrMjvU= > =CmhE > -----END PGP SIGNATURE----- From connellybarnes at yahoo.com Fri Jun 18 01:34:15 2004 From: connellybarnes at yahoo.com (Connelly Barnes) Date: 17 Jun 2004 22:34:15 -0700 Subject: Automatic thread safety Message-ID: <32e4319c.0406172134.4fa7e8df@posting.google.com> Another useful code snippet... This allows you to take a non-threadsafe class, and automatically generate a threadsafe class. When a method is called for your class, it automatically locks the object, then calls the method, then unlocks the object. You will have to perform any further locking/unlocking manually. # ------------------------------------------------- # threadclass: Get a threadsafe copy of a class. # ------------------------------------------------- import types, threading def threadclass(C): """Returns a 'threadsafe' copy of class C. All public methods are modified to lock the object when called.""" class D(C): def __init__(self): self.lock = threading.RLock() C.__init__(self) def ubthreadfunction(f): def g(self, *args, **kwargs): self.lock.acquire() ans = f(self, *args, **kwargs) self.lock.release() return ans return g for a in dir(D): f = getattr(D, a) if isinstance(f, types.UnboundMethodType) and a[:2] != '__': setattr(D, a, ubthreadfunction(f)) return D Example: class Counter: def __init__(self): self.val = 0 def increment(self): self.val += 1 SafeCounter = threadclass(Counter) Now SafeCounter is a threadsafe class. Try it out! Enjoy, Connelly Barnes From imbosol at aerojockey.invalid Mon Jun 14 18:09:55 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 14 Jun 2004 22:09:55 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: Ryan Paul wrote: > The proof is in the source. This is part of a ruby program I wrote. This > snippet is actually a single 'line'. I broke it into several lines for > slightly improved readability. This single line would probably take at > least 15 lines to do in python, probably more if you wanted to do it > intelligently. > > ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| > Dir[$prefix+fn].collect {|x| > x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| > `cat #{sesc x}.* > #{sesc x}`} } Oh boy. I believe this untested Python code does what you want, also one line, also wrapped in the name of "clarity." for f in dict([(__import__('re').sub(r"\.\d+[\d.-]*$","",x),None) for fn in ("*.rar.*","*.r[0-9][0-9].*") for x in __import__('glob').glob(prefix+fn)]): __import__('os').system("cat %s.* > %s" % (sesc(f),sesc(f))) This would take about 7 lines in well-written Python, not 15. bad-code-can-be-written-in-any-language-ly yr's, -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From newsuser at stacom-software.de Wed Jun 30 03:25:26 2004 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Wed, 30 Jun 2004 09:25:26 +0200 Subject: Modal dialog of a foreign window Message-ID: <2kf876F1iimlU1@uni-berlin.de> Hi, I've a wxPython Application on Windows that glues a database, Excel, and a GUI for configuration issues using COM. Works pretty good. In the next step I want to integrate the GUI-dialog more into Excel, so it should look like a modal toplevel dialoge of Excel. I've a class for the main dialog derived from wxFrame, and doing on startup: wxFrame.__init__(self, NULL, -1, cnfDesText, size=(800,600)) My Idea is now to give as parent the Window handle of Excel to the constructor of wxFrame. Not sure how the window handle can be retrieved (VBA, win32-Extension, wxWindows, ...) Any idea ?? Thanks a lot for all ideas, comments, hints in advance Alexander From jgilbert+python at uvm.edu Tue Jun 1 11:09:56 2004 From: jgilbert+python at uvm.edu (Josh Gilbert) Date: Tue, 01 Jun 2004 11:09:56 -0400 Subject: Negative look-behind In-Reply-To: References: Message-ID: Bhargava wrote: > Hello, > > I am a newbie to python and need some help. > > I am looking at doing some batch search/replace for some of my source > code. Criteria is to find all literal strings and wrap them up with > some macro, say MC. For ex., var = "somestring" would become var = > MC("somestring"). Literal strings can contain escaped " & \. > > But there are 2 cases when this replace should not happen: > 1.literal strings which have already been wrapped, like > MC("somestring") > 2.directives like #include "header.h" and #extern "C". > > I tried to use negative look-behind assertion for this purpose. The > expression I use for matching a literal string is > "((\\")|[^"(\\")])+". This works fine. But as I start prepending > look-behind patterns, things go wrong. The question I have is whether > the pattern in negative look-behind part can contain alternation ? In > other words can I make up a regexp which says "match this pattern x > only if it not preceded by anyone of pattern a, pattern b and pattern > c" ? > > I tried the following expression to take into account the two > constraints mentioned above, (? )(MC\()])"((\\")|[^"(\\")])+". Can someone point out the mistakes in > this ? > > Thanks, > Bhargava Hi. It would have been nice if you simplified your example. Since you said that your base pattern matched properly (for example) you could have let that be a literal. But no matter. I think that your problem is that you're trying to use grouping in a character class (set). [(1 )(2 )] matches '1', ' ', '(', ')'. My proof: >>> re.sub('[(1 )(2 )]','a','1 2 ( ) ') 'aaaaaaaa' So you should just need to ditch the '[' and ']'. I think what you meant by the set was question marks, ie: (#include )?(#extern )?(MC\()? So at least one occurs, though all may. This is not a Python specific question, this is just plain Reg ex's. You may wish to consult a good reference site such as http://www.regular-expressions.info/ or the O'Reilly book http://www.oreilly.com/catalog/regex/ in the future. Josh Gilbert. From kevryan0701 at yahoo.com Mon Jun 7 21:14:49 2004 From: kevryan0701 at yahoo.com (Kevin T. Ryan) Date: Mon, 07 Jun 2004 21:14:49 -0400 Subject: Calling Python Script from MS Excel? Message-ID: <40c51309$0$2944$61fed72c@news.rcn.com> Hi Group - I have written a "semi-program" in MS Excel related to running a football pool. I've updated it over the past two years or so, to the point where it is getting pretty advanced. Only, there are a few tricks that I want to add that I could not do in Excel - so I did them in Python :) Except as it stands, the current python scripts have to be run via the command line. Does anyone know how to allow interaction between Excel and Python via EXCEL? I've looked on Mark Hammond's page, and I've figured out how to interact with Python and Excel from PYTHON, but I can't seem to find the right info for making the calls from the other end (i.e. from Excel). Any advice would be GREATLY appreciated! PS - If anyone has any interest in this type of program, please let me know - I'd be more than willing to release via the GPL or something to that effect. Thanks Again... From nomail at nospam.no Sun Jun 13 05:00:21 2004 From: nomail at nospam.no (Dominic) Date: Sun, 13 Jun 2004 11:00:21 +0200 Subject: Good IDE for Python In-Reply-To: <889cbba0.0406122346.2e77941b@posting.google.com> References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: Kamilche wrote: > I love Python, but I'm less than in love with IDLE. It's OK, but it > really doesn't have enough capabilities. > > What I consider critical, are a popdown listing of all my functions, > colored syntax printing, and a right-click 'definition' context menu > that will hop you to the spot where that keyword is defined, if > possible. Everything else I could learn to do without, but these > features keep me hoping for a better IDE for Python. > > I'm used to the Microsoft Visual C++ debugger, and though tooltip > variable debugging and intellisense were nice, they broke often enough > that you couldn't rely on them anyway, so I don't really need those > features. > > I would also like the ability to create application 'forms' visually. > I'm on a Windows XP machine. > > Any suggestions on what I should install next? Latest jEdit has support for a Python-plugin which is able to parse Python and display methods/classes in separate pane and it can be used to access the Python shell and it has support for debugging. :-) Source editing and navigation is fine, though debugging seems to need some more work. This plugin is still in development. The Tk based editors tend to get too slow on my PIII 800 MHz on XP 128MB, the longer the app runs and the bigger the source code amount gets... Ciao, Dominic From paddy3118 at netscape.net Sat Jun 5 16:59:30 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Sat, 05 Jun 2004 21:59:30 +0100 Subject: Python Speed Question and Opinion In-Reply-To: <40c1ff22$0$15440$e4fe514c@news.xs4all.nl> References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> <40c1ff22$0$15440$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > djw wrote: > >>> http://www.razorvine.net/python/PythonSpeed > > >> I don't think I agree with your statement at the bottom that says "if >> all else fails, try Psyco." Since using Psyco is so effortless and may >> produce dramatic speedups, I would recommend to people that they try >> it before resorting to writing extension modules in C/C++. Sending >> people that are new to Python down the extension writing path may turn >> them off to Python altogether. > > > I think you're right. So I changed the order a bit and removed the > "if all else fails" :) > > Feel free to add other suggestions to the page. It's a WIKI page after all. > > --Irmen Hi I read the page and think you have missed out a critical point: it is not the absolute speed that is important, you should think about what us an acceptable speed of execution. Optimisations beyond achieving this acceptable speed are wasteful of resources (your time). Could we think of "speed" as being a coordinate system of (td,tr,tm) where: td is the development time tr is the time to run the developed program tm is the time to maintain/modify/debug-once-released the program. Then, comparing C/C++ with Python (spot the generalisations folks) td(C) is much greater than td(python) tr(C) is much less than tr(python) tm(C) is much greater than tm(python) Cheers, Pad. From squirrel at wpi.edu Tue Jun 22 13:49:34 2004 From: squirrel at wpi.edu (Chris King) Date: 22 Jun 2004 10:49:34 -0700 Subject: Working xrange() replacement proposal Message-ID: <994b391.0406220949.2d35fb95@posting.google.com> You guys are probably sick of these by now, but I've come up with an xrange() replacement that is actually (almost) implementable in pure Python. Some have previously suggested the form "for 0<=i<10:" to indicate iterating over a range of integers. This form works well in languages like Icon that can bind variables to all possible values, but Python doesn't (yet?) have this ability. Instead, I propose the syntax "for i in 0<=ints<10:". Though slightly more verbose, this form has the advantage of being more "Pythonic" in nature, binding i to each integer in the given range in turn. The other (major) advantage of this form is that it is implementable in pure Python: 'ints' is simply an object which represents the mathematical set of all integers. Its comparison functions return a similar object representing a portion of this set, and its __iter__ method returns an iterator over these integers. My implementation defines an 'intrange' class to represent these ranges, along with (previously proposed) Min and Max objects to represent the minimum and maximum integers. The intrange constructor accepts two values, a lower and upper bound (with the same meaning as those of xrange()). Two default intrange objects are defined, 'ints' and 'nats'. ints has upper and lower bounds of Max and Min, respectively, whereas nats has an upper bound of Max and a lower bound of 0. Limitations of this implementation: * Python doesn't allow overriding of the 'and' operator. Since chained comparisons are implemented using this operator, "for i in 0<=ints<10:" won't work (it will instead iterate over all integers less than 10). Two workarounds are to use either "(0<=ints)<10" or "(0<=ints)&(ints<10)". Ideally intrange will be able to override "and" the same way it does "&". * 'Broken' ranges aren't supported; i.e. the ranges can't have any gaps in them. Whether or not this would be actually be useful (e.g. to emulate xrange(0,10,2)) is a question yet to be answered. The implementation is available at http://users.wpi.edu/~squirrel/temp/ints.py. Test it (in 2.3) with: from ints import ints,nats for i in (5<=ints)<10: print i print list(nats<10) From kveretennicov at yahoo.com Tue Jun 8 11:09:27 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 8 Jun 2004 08:09:27 -0700 Subject: Problem with Python xrange References: Message-ID: <5155aad2.0406080709.698cba47@posting.google.com> "Christian Neumann" wrote in message news:... > Hello, > > i have a problem with the built-in function xrange(). Could you by any > chance be able to help? > > I use Python 2.3.4 (final) and i think there is a bug in the built-in > function xrange(). > > An example is: > > x xrange(2, 11, 2) ## [2, 4, 6, 8, 10] > > I get an TypeError if i use it with SliceType: > > x[1:4] ## It should be return an xrange object with length 3 > As other posters have pointed out, slicing xrange object doesn't yield appropriate x(sub)range but raises exception instead. According to PEP 260 xrange slicing is a "rarely used behavior". You have at least three alternatives: 1) Obvious. Forget about xrange() and use range() when you need slicing :) Especially if you can happily trade speed and memory efficiency for ability to slice. 2) Quick and dirty. Use itertools.islice: >>> from itertools import islice >>> x = xrange(2, 11, 2) >>> s = islice(x, 1, 4) >>> for i in s: ... print i, ... 4 6 8 There are subtleties: islice and xrange objects behave slightly differently. For instance, you can iterate many times over xrange items, but only once over islice items: >>> from itertools import islice >>> x = xrange(3) >>> list(x); list(x) [0, 1, 2] [0, 1, 2] >>> s = islice(xrange(3)) >>> list(s); list(s) [0, 1, 2] [] 3) Involved. Write a class implementing the behaviour you need. You'll want to implement xrange interface and slicing protocol. It's not possible to subclass xrange (yet?), so you'll have to delegate. BTW, such class may already exist, but I'm too lazy to search... - kv From fBechmann at web.de Thu Jun 10 03:13:15 2004 From: fBechmann at web.de (fBechmann) Date: Thu, 10 Jun 2004 00:13:15 -0700 Subject: logical puzzle: how to generate reasonable archive file names from file and directory names Message-ID: I'm writing a module to convert between filesystem nodes (directory,file) and various archives (gz, zip, tgz). For this I want to automatically create reasonable file names for the archives where these file names depend from the type of the file system node to be archived and from the type of the archive to be created. I want the following transformations to take place: Dir abc =(gz)=> *not allowed* =(zip,tgz)=> abz.zip,abc.tgz abc.XY =(gz)=> *not allowed* =(zip,tgz)=> abc.XY.zip,abc.XY.tgz File abc =(gz)=> abc.gz =(zip,tgz)=> abz.zip,abc.tgz abc.ext =(gz)=> abc.ext.gz =(zip,tgz)=> abc.zip,abc.tgz For the decision to remove the extension from the file or directory this gives me the following table: gz zip,tgz Dir *n.a.* no File no yes I have the classes Dir, File, ArchiveGZ and MultiFileArchive (base class for ArchiveTGZ and ArchiveZIP, which share behaviour w/ respect to that naming transformation). I've found a way which looks quite cruel (and which I'll post later), so I have the hope that someone here finds a nice snippet of code for this. thx in advance From jimka at rdrop.com Mon Jun 7 17:51:00 2004 From: jimka at rdrop.com (Jim Newton) Date: Mon, 07 Jun 2004 23:51:00 +0200 Subject: how to use __str__ and __repr__? In-Reply-To: References: <2ik7qrFo8httU1@uni-berlin.de> Message-ID: <2ik9hjFnvcsbU1@uni-berlin.de> thanks for responding, i was expecting class().__str__() to evaluate to the string "<__main__.another instance at 0x8132b64>" because that what print does with class(). but alas it does not. why does print class() not give me the same error as class().__str__()? that's what i do not understand. -jim Larry Bates wrote: > I don't understand what you are trying to do, but > the problem is that when you define class 'another' > the following line doesn't make sense: > > middle = " ".join( [ substr.__str__() for substr in self]) > > The instance of another doesn't have a __str__ method > defined (e.g. it's an empty class). All of your other > tests have a class that does have a __str__ method > because it was inherited from the baseclass list. > > You could try: > > class another(list): > pass > > Larry Bates > Syscon, Inc. > > "Jim Newton" wrote in message > news:2ik7qrFo8httU1 at uni-berlin.de... > >>hi all, does anyone know what print does if there is no __str__ method? >>i'm trying ot override the __repr__. If anyone can give me some advice >>it would be great to have. >> >>I have defined a lisp-like linked list class as a subclass of list. >>The __iter__ seems to work as i'd like, by traversing the links, >>and the __repr__ seems to work properly for somethings but not others. >> >>The basic idea is that a list such as [ 1, 2, 3, 4] is converted to >>[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element >>non-destructively onto the beginning of the list; e.g. >> >>x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]] >>y = x.cons(2) --> [ 2, [3, [4, [5, nil]]] >>z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]] >> >>for elt in z: # iterates elt=1, elt=2, elt=3 ... >> pass >> >>I would love to know how to define the __repr__ or __str__ >>method so that it is able to print everything the way print >>normally works, except that instances of my class gets printed >>special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]] >>simple as a space seperated list. It works most of the time. >>--> ( 1 2 3 4 5) >> >>Another question is whether there is a way to promote an >>empty list [] to an instance of Pair? >> >>class Pair(list): >> >> def __iter__(self): >> while self: >> yield self.car() >> self = self.cdr() >> >> def __repr__(self): >> middle = " ".join( [ substr.__str__() for substr in self]) >> return "( " + middle + " )" >> >> # x = (cons x l_y) >> # ==> x = l_y.cons(x) >> def cons(self, car): >> new = Pair() >> new.append(car) >> new.append(self) >> return new >> >> def car(self): >> if self: >> return self[0] >> return nil >> >> def cdr(self): >> if len(self)<2: >> return nil >> return self[1] >> >>nil = Pair() >> >> >># [ 1, 2, 3] --> [1, [2, [3, nil]]] >>def seq2pair(seq): >> new = Pair() >> for index in xrange( len(seq), 0, -1): >> new = new.cons(seq[index - 1]) >> return new >> >>mylist = seq2pair( [1,2,3,4,5]) >>print mylist # correctly prints --> ( 1 2 3 4 5) >> >> >>mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist]) >>print mylist2 >># correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) ) >> >>class another: >> pass >> >>print another() # prints --> <__main__.another instance at 0x8132b64> >> >># ???????????????????????????????????????? >>print seq2pair( [ another(), another() ]) # FAILS >># ???????????????????????????????????????? >> >>Traceback (most recent call last): >> File "xyz.py", line 52, in ? >> print seq2pair( [ another(), another() ]) >> File "xyz.py", line 13, in __repr__ >> return "( " + " ".join( [ substr.__str__() for substr in self]) + > > " )" > >>AttributeError: another instance has no attribute '__str__' >> > > > From nocker at animail.net Sat Jun 19 04:23:25 2004 From: nocker at animail.net (.) Date: 19 Jun 2004 01:23:25 -0700 Subject: comp.os.ms-windows.networking.misc, misc.invest.mutual-funds, comp.lang.python, comp.os.magic-cap, comp.sources.games.bugs Message-ID: comp.os.ms-windows.networking.misc,misc.invest.mutual-funds,comp.lang.python,comp.os.magic-cap,comp.sources.games.bugs From J.Gerner at GernerOnline.de Mon Jun 7 08:26:24 2004 From: J.Gerner at GernerOnline.de (Juergen Gerner) Date: 7 Jun 2004 05:26:24 -0700 Subject: Storing files in a BLOB field via SQL References: <5a2071a0.0406061231.59c3bede@posting.google.com> <40c387ad$0$15440$e4fe514c@news.xs4all.nl> Message-ID: <5a2071a0.0406070426.45d054a0@posting.google.com> Hi Irmen, first of all, thanks for your help about compression & checksum! > Is there a special reason why you can't store the whole file in a > single BLOB? That's what it's a BLOB for, after all... L=Large :-) Yes, there's a special reason. After reading a lot of documentation I think it's better splitting large files in little blobs. It doesn't matter if the SQL server is on the same machine as the application, but if both parts are on different machines, large files have to be transmitted over the network. During this transfer the application isn't responding, I guess. So splitting would be much more flexible. Additionally I think, splitting files makes the database more scalable and the space on the harddrive better used. But the splitting isn't my main problem. It's the way I transmit the binary data to the database via an SQL syntax. Today I saw how PhpMyAdmin handles binary data: it codes each byte in hexadecimal values ("\0x..."). Is there any way to do something (or similar) with Python, or maybe with PyQt/QString/QByteArray? Thanks in advance! Juergen From mariano.df at tin.it Tue Jun 15 04:41:58 2004 From: mariano.df at tin.it (Mariano) Date: 15 Jun 2004 01:41:58 -0700 Subject: property file References: Message-ID: "Larry Bates" wrote in message news:... > I would use ConfigParser from the standard library. > It supports sections, built in conversions, default > values, variable insertion, and writing of the > file (as well as reading). > > -Larry Bates > > "Neil Benn" wrote in message > news:mailman.860.1086962012.6949.python-list at python.org... > > Hello, > > > > One way that I have done this is to make a file with : > > > > =\n > > > > Then open the file and use the following list comprehension to get > > back a dict with the properties in it : > > > > objFile = file('MyConfigurationFile.conf') > > > > dctConfiguration = dict([(key.strip(), value.strip()) \ > > for (key,value) in [line.split('=') \ > > for line in objFile]]) > > > > It's not as simple as Properties in Java but you could wrap it in a > > class to copy the Java Properties class. You could also add some > > intellegence to it so that it doesn't bomb out if the properties file is > > slightly wrong. > > > > Cheers, > > > > Neil > > > > Mariano wrote: > > > > >Hi > > > > > >Have someone any idea how create/read a property file as java property > file? > > >If not, is there some other solutions? > > > > > >Thank's in advance > > > > > > > > > > > > -- > > > > Neil Benn > > Senior Automation Engineer > > Cenix BioScience > > BioInnovations Zentrum > > Tatzberg 47 > > D-01307 > > Dresden > > Germany > > > > Tel : +49 (0)351 4173 154 > > e-mail : benn at cenix-bioscience.com > > Cenix Website : http://www.cenix-bioscience.com > > > > I've found a great solutions! I use the ConfigParser, as Larry Bates says, because the manual parser with the character "=" isn't good. I can have this possible problem: Userkey = dklf343=S234978 In this case, i would not simple problem. Instead, the ConfigParser is simple and affidable, with the sections! Thank's a lot at all!!! From franck.lepoutre at caramail.com Fri Jun 25 02:05:30 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Fri, 25 Jun 2004 08:05:30 +0200 Subject: Using Python with SyBase References: Message-ID: <40dbbf6b$0$16984$79c14f64@nan-newsreader-04.noos.net> Hi, > Does anybody expirience Python for writing user > front-end screens for SyBase-Anyware database ? Sybase Anywhere ASA (ex-watcom sql) is an odbc-orientated dbms solution from Sybase. We have been succssful using it from python via mxodbc both on linux (some tweaking may be required) and win32 (plain easy). I have no experience or feedback of ASA connections through FreeTDS. It should work as well... I'd be glad to hear that it does:) Fran?ois From askari at addressNonValide.com Sat Jun 12 02:38:13 2004 From: askari at addressNonValide.com (Askari) Date: Sat, 12 Jun 2004 06:38:13 GMT Subject: Unbind initial bind on basic widget (text) Message-ID: Hi, Do I can unbind the initial bind on basic widget? (ex.: the basic widget Text have the bind "" for the return to the first caracter of the line; but me I don't want this!) I try 'myText.unbind("")' but the bind is not remove. :-( Askari N.B. I wan't disabled ALL initial bind (not just the "") From jfast at poczta.onet.pl Mon Jun 21 09:37:45 2004 From: jfast at poczta.onet.pl (Jakub Fast) Date: 21 Jun 2004 06:37:45 -0700 Subject: Mozilla, XUL and the snake References: <6ld6bc.5b3.ln@news1.interplanet.it> Message-ID: deelan wrote in message news:<6ld6bc.5b3.ln at news1.interplanet.it>... > Jakub Fast wrote: > > > Does anybody know how far you can get nowadays with trying to use Python > > as the script language for XUL instead of JS? Is it possible (even > > theoretically) to write full-fledged applications on the Mozilla > > platform with python only? > > yeah, theoretically is it possible by using PyXPCOM: > > Isn't using JavaScript the only way to call XPCOM objects from XUL? I was aware of PyXPCOM, I was just wondering whether it was possible to get rid of JavaScript altogether... Kuba From nothanks at nothere.com Mon Jun 7 06:34:20 2004 From: nothanks at nothere.com (Emiliano Molina) Date: Mon, 07 Jun 2004 10:34:20 GMT Subject: wxPython DnD stops working after SetSizeHints Message-ID: This has been driving me crazy for a couple of days and I have finally narrowed it down to the following code. If the commented section is uncommented the drag and drop handler is never called. I have included the .xrc file for reference. Any help is greatly appreciated. An explanation would be great, but at the moment I would be eternally grateful for a workaround! Thanks in advance for those of you that spend some time helping out. Here is the blasted code, from wxPython.wx import * from wxPython.xrc import * class TestFrame(wxFrame): def __init__(self,parent,ID): wxFrame.__init__(self,parent,ID,"test frame",(100,30),(70,60),wxDEFAULT_FRAME_STYLE) self.panel=wxPanel(self,-1) class FileDropTarget(wxFileDropTarget): def __init__(self, window): wxFileDropTarget.__init__(self) def OnDropFiles(self, x, y, filenames): print filenames class App(wxApp): def OnInit(self): self.res=wxXmlResource("test.xrc") self.frame=self.res.LoadFrame(None,"FRAME1") self.frame.panel=XRCCTRL(self.frame,"test_list") dt=FileDropTarget(self.frame) self.frame.panel.SetDropTarget(dt) # The following lines break the drag and drop # self.panel=XRCCTRL(self.frame,"panel") # sizer=self.panel.GetSizer() # sizer.SetSizeHints(self.frame) self.frame.Show() self.SetTopWindow(self.frame) return True def main(): app=App(0) app.MainLoop() if __name__=="__main__": main() and here the XRC 100,100 wxVERTICAL wxVERTICAL 100,100 From nhirsh2 at ieee.org Sun Jun 13 20:48:03 2004 From: nhirsh2 at ieee.org (Neale) Date: 13 Jun 2004 17:48:03 -0700 Subject: How to Access Unix Shell Message-ID: <2d7af4f8.0406131648.42868c63@posting.google.com> In a python program, I want to do a Unix directory list and then append selected files to each other which, as you know, is just "cat filename2 >> filename1." How do I escape into the shell and then return, bringing with me a directory list? Where can I find some examples of mixing shell commands and Python? From peufeu at free.fr Fri Jun 25 14:04:53 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 20:04:53 +0200 Subject: Case insensitive dictionary? References: <9418be08.0406250921.71f4eba4@posting.google.com> Message-ID: Be careful about what character encoding and locale you use, as lower() won't process accented characters correctly if the encoding is wrong. On 25 Jun 2004 10:21:21 -0700, Elbert Lev wrote: > Hi! > > Here is the problem: > > I have a dictionary. Keys are strings. How to make dictionary lookup > case insensitive? > > In other words: > If dict = {'First":"Bob", "Last":"Tom"}, dict["first"] should return > "Bob" > > Maybe dictionary is not the right data type? If so what is? -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From ptmcg at austin.rr._bogus_.com Fri Jun 25 01:44:34 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 25 Jun 2004 05:44:34 GMT Subject: Rolling a Container Into a String References: <889cbba0.0406241742.51a2980b@posting.google.com> Message-ID: <6ZOCc.10997$w3.6878@fe2.texas.rr.com> "Kamilche" wrote in message news:889cbba0.0406241742.51a2980b at posting.google.com... > I want to convert a dict into string form, then back again. After > discovering that eval is insecure, I wrote some code to roll a Python > object, dict, tuple, or list into a string. I've posted it below. Does > anyone know an easier way to accomplish this? Essentially, I want to > avoid doing an 'eval' on a string to get it back into dict form... but > still allow nested structures. (My current code doesn't handle nested > structures.) > unroll is just repr(). Here is a pyparsing routine to "roll up" your data structures, a mere 60 lines or so. It's fairly tolerant of some odd cases, and fully handles nested data. (Extension to include remaining items, such as boolean data and scientific notation, is left as an exercise for the reader.) I hope this is fairly easy to follow - I've dropped in a few comments. For those of you who've been living in a cave, you can download pyparsing at http://pyparsing.sourceforge.net. -- Paul from pyparsing import Word, ZeroOrMore, OneOrMore, Suppress, Forward, \ quotedString,nums,Combine,Optional,delimitedList,Group # create a dictionary of ugly data, complete with nested lists, tuples # and dictionaries, even imaginary numbers! d1 = {} d1['a'] = [1,2,3,[4,5,6]] d1['b'] = (7,8,(9,10),'a',"",'') d1['c'] = { 'aa' : 1, 'bb' : "lskdj'slkdjf", 'cc':1.232, 'dd':(('z',),) } d1[('d','e')] = 5+10j print repr(d1) testdata = repr(d1) """ looks like this: {'a': [1, 2, 3, [4, 5, 6]], ('d', 'e'): (5+10j), 'c': {'aa': 1, 'cc': 1.232, 'dd': (('z',),), 'bb': "lskdj'slkdjf"}, 'b': (7, 8, (9, 10), 'a', '', '')} """ #define low-level data elements intNum = Word( nums+"+-", nums ) realNum = Combine(intNum + "." + Optional(Word(nums))) number = realNum | intNum imagNum = Combine( "(" + number + "+" + number + "j" + ")" ) item = Forward() # set up for recursive grammar definition tupleDef = Suppress("(") + ( delimitedList( item ) ^ ( item + Suppress(",") ) ) + Suppress(")") listDef = Suppress("[") + delimitedList( item ) + Suppress("]") keyDef = tupleDef | quotedString | imagNum | number keyVal = Group( keyDef + Suppress(":") + item ) dictDef = Suppress("{") + delimitedList( keyVal ) + Suppress("}") item << ( quotedString | number | imagNum | tupleDef | listDef | dictDef ) # define low-level conversion routines intNum.setParseAction( lambda s,loc,toks: int(toks[0]) ) realNum.setParseAction( lambda s,loc,toks: float(toks[0]) ) imagNum.setParseAction( lambda s,loc,toks: eval(toks[0]) ) # no built-in to convert imaginaries? # strip leading and trailing character from parsed quoted string quotedString.setParseAction( lambda s,loc,toks: toks[0][1:-1] ) # define list-to-list/tuple/dict routines evalTuple = lambda s,loc,toks: [ tuple(toks) ] evalList = lambda s,loc,toks: [ toks.asList() ] evalDict = lambda s,loc,toks: [ dict([tuple(kv) for kv in toks]) ] tupleDef.setParseAction( evalTuple ) listDef.setParseAction( evalList ) dictDef.setParseAction( evalDict ) # first element of returned tokens list is the reconstructed list/tuple/dict results = item.parseString( testdata )[0] print results if repr(results) == repr(d1): print "Eureka!" else: print "Compare results for mismatch" print repr(results) print repr(d1) From ialbert at mailblocks.com Mon Jun 28 12:39:53 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 28 Jun 2004 12:39:53 -0400 Subject: Interactive use of DISLIN In-Reply-To: References: Message-ID: <6pKdnezoA4VK1H3dRVn-uA@giganews.com> Andrej Dzerzhinsky wrote: > I'd like to plot a spline over several thousand (x,y) points from a > spectrum, reasonably fast, and be able to zoom in and out of the plot, > label peaks either automatically or by hand, display and overlay > multiple data sets and export plots as metafiles. DISLIN won't do interactive plots. I think it is more of a desing decision in DISLIN to make it as platform independent as possible. Istvan. From lbates at swamisoft.com Fri Jun 25 19:47:06 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 25 Jun 2004 18:47:06 -0500 Subject: Html Edit Control for Windows ( Pythonwin or wxPython / SWIG / COM ) ? References: <19804fd8.0406240147.7635d441@posting.google.com> Message-ID: Robert, Noticed you haven't received a response. You really need to provide a "little" more detail about what you are looking for. I'm just guessing but you might want to look at: http://vsbabu.org/webdev/zopedev/ieeditor.html http://www.kevinroth.com/rte/demo.htm HTH, Larry Bates Syscon, Inc. "Robert" wrote in message news:19804fd8.0406240147.7635d441 at posting.google.com... > Somebody knowing a (handy simple) solution for that? - Robert From dmq at gain.com Fri Jun 18 01:36:36 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 17 Jun 2004 22:36:36 -0700 Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> Message-ID: On Thu, 17 Jun 2004 11:05:58 GMT, Michael Hudson wrote: >michele.simionato at poste.it (Michele Simionato) writes: > >> David MacQuigg wrote in message news:... >> > I have what looks like a bug trying to generate new style classes with >> > a factory function. >> > >> > class Animal(object): pass >> > class Mammal(Animal): pass >> > >> > def newAnimal(bases=(Animal,), dict={}): >> > class C(object): pass >> > C.__bases__ = bases >> > dict['_count'] = 0 >> > C.__dict__ = dict >> > return C >> > >> > Canine = newAnimal((Mammal,)) >> > TypeError: __bases__ assignment: 'Mammal' deallocator differs from >> > 'object' >> > >> > If I remove the 'object' from the class C(object) statement, then I >> > get a different, equally puzzling error message: >> > >> > TypeError: __bases__ items must be classes >> > >> > The function works only if I remove 'object' from all base classes. >> > >> > -- Dave >> >> This is not a bug. The developers removed the possibility to change >> the bases of a new-style class. > >Bad news for you: I put it back in for 2.3. > >If you read the error message, you'll notice that it's phrased to >suggest that assignment to __bases__ is *sometimes* possible :-) > >David's assignment probably should work -- there's a bug on sf about >this -- but there are definitely situations where assignment to bases >*shouldn't* be allowed -- e.g. when the so-called 'solid base' changes >-- but noone's put in the thinking time to make this precise in code. >Being over-restrictive seems the better course. This may be just a documentation problem then. The error message is definitely misleading. >However, newAnimal could be written like this: > >def newAnimal(bases=(Animal,), ns=None): > if ns is None: > ns = {} > ns['_count'] = 0 > return type('C', bases, ns) > >which > >a) doesn't use the name of a builtin as a variable >b) doesn't suffer the 'mutable default arguments' problem >c) is rather less insane >d) actually works :-) (probably, haven't tested it) It works great. The only thing I would change is the return line, making that globals()[name] = type('C', bases, ns) so we don't have to type the name twice when creating a new class. I've also added an __init__ function. Using the factory is now very easy: >>> newAnimal('Dog',(Mammal,)) >>> dog1 = Dog() Hello from __init__ in Dog >>> Dog._count 1 The main limitation I see in using a factory function like this, instead of a metaclass, is that I can't customize the new animal as easily, because I don't have an indented block like in a class definition. I've got to call the newAnimal function, then add a bunch of attributes one at a time, with fully-qualified names. Dog.temperature = 102 Dog.pulse = 82 Dog.respiration = 36 If I'm adding methods, it gets even messier, because I've got to define functions at the module level, then assign them to attributes of Dog, then maybe delete all the excess names from the module namespace. I have one last question. In reviewing all the ways to solve the problem of creating specialized classes, I see there is a function new.classobj(name, bases, dict) which appears to do the same thing as type(name, bases, dict). What is the purpose of classobj()? The name is a little more self-explanatory than 'type', but using it requires a module import. - Dave From jarausch at igpm.rwth-aachen.de Mon Jun 28 05:00:32 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 28 Jun 2004 11:00:32 +0200 Subject: iterator support (in ext. module) Message-ID: <2ka51gF19her1U1@uni-berlin.de> Hi, sorry for the questions but I'm not sure I understand the C_API docu. In an own extension module I have a new type called Hitlist, which has the methods 'first', 'last', 'next' and 'previous'. Now I'd like to support iterating on this type, e.g. like HL= Hitlist(...) for Rcd in HL: and also for Rcd in HL.reverse() : What do I need to implement to get that functionality? Unfortunately the chapter 10.8 'Supporting the Iterator Protocol' of the (devel) docu seems to be empty. What should PyTypeObject.tp_iter be set to? Can I just return 'self' and is PyTypeObject.tp_iternext an alias for my 'next' method? Does a call to 'PyTypeObject.tp_iter' reset the iterator s.t. 'tp_iternext' returns the first object when called afterwards? Many thanks for your help, Helmut. (P.S. I'm using Version 2.4 -cvs) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From rupole at hotmail.com Mon Jun 14 18:17:40 2004 From: rupole at hotmail.com (Roger Upole) Date: Mon, 14 Jun 2004 18:17:40 -0400 Subject: Pythin createprocessasuser -- OpenProcessToken, 'Access is denied.' References: <9a361bc.0406132315.73f2db7a@posting.google.com> Message-ID: <40ce2028_1@127.0.0.1> You'll probably need to call AdjustTokenPrivileges before LogonUser, since you need SE_TCB_NAME enabled for the calling process. Also, you don't need to do ImpersonateUser in order to call CreateProcessAsUser. If you do, you might have to enable some privs for the logon token you're impersonating as well as your original process token. Another thing to keep in mind is that AdjustTokenPrivileges doesn't fail if you try to enable a privilege you don't have at all. win32security.GetTokenInformation(,TokenPrivileges) will list your privs and their current state. hth Roger "Pete Fong" wrote in message news:9a361bc.0406132315.73f2db7a at posting.google.com... > Dear all, > > I am a beginner with Python. I want to write a program as "runas" in > Windows XP. > But I have got the following error: > File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\python\Script1.py", line 30, in ? > File "C:\python\Script1.py", line 14, in AdjustPrivilege > print "Started as: ", win32api.GetUserName() > error: (5, 'OpenProcessToken', 'Access is denied.') > > There is my program : > > import win32security > import win32process > import win32api > import win32con > import sys > import time > import os > from ntsecuritycon import * > > > def AdjustPrivilege(priv, enable = 1): > # Get the process token. > flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY > htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), > flags) > # Get the ID for the privilege. > id = win32security.LookupPrivilegeValue(None, priv) > # Now obtain the privilege for this process. > # Create a list of the privileges to be added. > if enable: > newPrivileges = [(id, SE_PRIVILEGE_ENABLED)] > else: > newPrivileges = [(id, 0)] > win32security.AdjustTokenPrivileges(handel, 0, newPrivileges) > # and make the adjustment. > > > handel=win32security.LogonUser('administrator','domain','pwd',win32con.LOGON 32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT) > > win32security.ImpersonateLoggedOnUser(handel) > AdjustPrivilege(SE_TCB_NAME) > AdjustPrivilege(SE_INCREASE_QUOTA_NAME) > AdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) > AdjustPrivilege(TOKEN_DUPLICATE) > AdjustPrivilege(TOKEN_IMPERSONATE) > AdjustPrivilege(SE_CHANGE_NOTIFY_NAME) > > > > print "Started as: ", win32api.GetUserName() > #this prints target username, impersonation successful > > win32process.CreateProcessAsUser(handel,None,'notepad',None,None,0,0,None,No ne,win32process.STARTUPINFO()) > #os.execv('c:', 'notepad') > #os.execv(path, args) > #runs program, not as target user > > > win32security.RevertToSelf() > handel.Close() > > > Could anyone help me ? What's wrong ? Thanks a lot ? > > Best Regards, > Pete Fong From skip at pobox.com Mon Jun 7 12:03:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 7 Jun 2004 11:03:31 -0500 Subject: Decoding 'funky' e-mail subjects In-Reply-To: References: Message-ID: <16580.37331.589012.941181@montanaro.dyndns.org> Jonas> Hi, I need a function to parse badly encoded 'Subject' headers from Jonas> e-mails, such as ... Jonas> Can anyone recommend a safer method? There's something in the email package. I can't recall the name off the top of my head. Skip From dalcolmo at vh-s.de Wed Jun 16 10:23:34 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Wed, 16 Jun 2004 16:23:34 +0200 Subject: list to dict References: Message-ID: <20040616162334.0000082d@titan> on Wed, 16 Jun 2004 09:29:23 -0400 Bart Nessux wrote: > What is the easiest/fastest way to build a dictionary from a list? The > list contains 100,000 entries. The first question would be, what should the keys be? If the list consists of unique, unmutable items, then you might use the items themselves as key and write: mydict = dict(zip(mylist, mylist)) obtaining a dictionary with all the keys and values identical (therefore somewhat of a waste, but occasionally useful). Note: if your original list did not contain unique values, you end up with a set. If you want to remember the original order of the list, then write mydict = dict(zip(mylist, xrange(len(mylist)))) If you don't care about the key (that would be strange) then you can write: mydict = dict(zip(xrange(len(mylist)), mylist)) Instead of len(mylist) you can also write 1000000 or any other number larger than your list. - Josef From bvande at po-box.mcgill.ca Fri Jun 11 10:34:26 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 11 Jun 2004 10:34:26 -0400 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: <40C9C2F2.1020201@po-box.mcgill.ca> Aahz said unto the world upon 10/06/2004 16:56: > In article <-oadnfu_sdwTUFrdRVn-hw at powergate.ca>, > Peter Hansen wrote: > >>Michael P. Soulier wrote: >> >>>myfile = open("myfilepath", "w") >>>myfile.write(reallybigbuffer) >>>myfile.close() >> >>... immediately raises a warning flag in the mind of an >>experienced Python programmer. > > > Depends on the circumstance, I'd think. Hi all, I'm still learning Python as a first language since some BASIC quite some time ago, so my level of knowledge/understanding is not too sophisticated. From that standpoint, I am wondering why the code that Michael P. Soulier provided above would worry an experienced Python programmer. I've read the rest of the thread, but the ensuing references to C++ RAII, malloc, etc. are not yet within my grasp. (I recognize I'm not really the target audience of the thread.) I'd google for an explanation, but I don't have a clear sense of what to google for. I had thought I was being careful and smart by always checking for filepath existence and always explicitly closing files, but I am wondering what red flag I'm overlooking. Any pointers for stuff to read to understand the comment would be appreciated. Thanks and best to all, Brian vdB From davidf at sjsoft.com Wed Jun 2 07:37:06 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 13:37:06 +0200 Subject: preftree 0.3 released In-Reply-To: References: <40B72942.8060200@sjsoft.com> <8765agba17.fsf@blakie.riol> Message-ID: Donald 'Paddy' McCarthy wrote: > Wilk wrote: > >> David Fraser writes: >> >> >>> Following up on a promise in the Config discussion ... >>> >>> preftree has been released under the Python license. >>> You can get version 0.3 from >>> http://davidf.sjsoft.com/files/preftree-0.3.tar.gz >> >> >> >> thanks, it look a lot like yaml... Don't you think it could be a layer >> on top of yaml ? >> > The example shows string, integers and (nested) dictionary types. I > presume floating point would be obvious, and is included but what about > lists? Floating point? Never! :-) I should add that. Lists aren't included (which is something yaml does with different syntax), but the preftree approach would be to just have a number of elements. The inspiration for preftree was from the Mozilla prefs, where for example a list of mail accounts would contain account1, account2 etc. What we need to do is make it easier to iterate over elements at a point in a tree. David From iv at an.voras.fer.hr Mon Jun 14 06:31:34 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Mon, 14 Jun 2004 12:31:34 +0200 Subject: Pythin createprocessasuser -- OpenProcessToken, 'Access is denied.' In-Reply-To: <9a361bc.0406132315.73f2db7a@posting.google.com> References: <9a361bc.0406132315.73f2db7a@posting.google.com> Message-ID: Pete Fong wrote: > I am a beginner with Python. I want to write a program as "runas" in > Windows XP. > handel=win32security.LogonUser('administrator','domain','pwd',win32con.LOGON32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT) IIRC, you can't use these win32 calls if you don't hav e appropriate rights. Only administrators and backup users can do impersonation (see msdn or such for details). (I think Explorer gets around it by delegating the impersonation to some system service). From lsolis at mu.intecsa-inarsa.es Thu Jun 24 02:18:25 2004 From: lsolis at mu.intecsa-inarsa.es (Luis Solís) Date: Thu, 24 Jun 2004 06:18:25 GMT Subject: checking user defined types Message-ID: I have defined a class Myclass I instanciate the class and I use it in a function, and I could like check the argument type in the function, but this code don't works func (xMyclass,..): if type(xMyclass) is type(Myclass): ... then I must create a new object of the class and then if type(xMyclass) is type(Myclass()): this solution has the problem when Myclass has a complex constructor. Do you known another solution ? Thanks in advance From michael at foord.net Mon Jun 14 03:25:24 2004 From: michael at foord.net (Fuzzyman) Date: 14 Jun 2004 00:25:24 -0700 Subject: new to the list and... References: Message-ID: <8089854e.0406132325.1c8a640c@posting.google.com> "Daniel Farmer" wrote in message news:... > Hi... I'm just getting started with P, but am very eager to explore it's > possiblities. > > Where would I begin to find out about creating windows like GUI with > Python? > > I've downloaded tcl/tk... I'm not exactly sure what to do with them at > this point. ( they're sitting in folders on my desktop ). > > -- If you are using Python with Windows then Tk/Tcl and the Python Tkinter libraries all come with the Python distributions. You shouldn't need to download tcl seperately. 'Programming Python' has a really straightforward introduction to building GUIs using Tk. Alternatively there's a couple of simple apps with Tk interfaces on my website at http://www.voidspace.org.uk/atlantibots/pythonutils.html Regards, Fuzzy From brian at sweetapp.com Wed Jun 2 07:28:14 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 02 Jun 2004 13:28:14 +0200 Subject: Automated web documentation generation In-Reply-To: References: Message-ID: <40BDB9CE.1090006@sweetapp.com> I'm looking for a way to serve Python source documentation on our company's intranet. Pydoc-style documentation would be great, but the following features (that Pydoc lacks) would great: o hostable as CGI (this is the most important) o separation between library modules, site-packages modules and other modules o searchable o dynamic document generation i.e. no static HTML pages Does anyone know of a system with similar properties? Cheers, Brian From Scott.Daniels at Acm.Org Wed Jun 23 12:39:43 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 23 Jun 2004 09:39:43 -0700 Subject: http knowledge sought In-Reply-To: <6r3Cc.861817$Ig.9977@pd7tw2no> References: <6r3Cc.861817$Ig.9977@pd7tw2no> Message-ID: <40d9b755$1@nntp0.pdx.net> Elaine Jackson wrote: > I want to run an http server but I don't know how to get started. I've read > through the documentation for the relevant modules, but I don't have enough http > knowledge to get the initial spark I need, and I can't seem to track down the > knowledge in question on the web or at the library. Maybe somebody can point me > toward some resources? > > In case you feel like answering a specific question, here's one: How does http > addressing work? I remember reading in a book about dot-separated quadruples of > numerals, written in decimal but required to be two hexadecimal digits long. > Problem is, I can't get hold of that book right now. > > Any help will be much appreciated. > > Peace > > Probably the simplest thing to do is something like: Create a file 'myserver.py' in a directory with some .html (or .htm) files you want to see. Let's pretend one of the html files is named 'slithey.html'. Here is the body (no indentation in file) of 'myserver.py': import SimpleHTTPServer SimpleHTTPServer.test() Open a command line in your OS, go to the directory you chose above, and on that command line type the python magic incantation to run a python program. As the program starts, it will mention a port. For the purposes of this recipe, I'll pretend the port number printed out is "8123". While your program is still running, open a browser. Into the browser, enter one of the following URLs. http://127.0.0.1:8123/slithey.html http://localhost:8123/slithey.html Or, if you know the name of your computer, you can substitute that for "localhost". Similarly, if you know the TCP/IP address of your computer, substitute it for 127.0.0.1 localhost and 127.0.0.1 are "magic" ways to refer to your own computer. Neither should be using your actual internet connection (but you might get a cute page in firefox if you get the port number wrong). If you don't know your IP number, you can browse to: which creates a page with your number (every connection needs to know the number of the other side in order to reply). explains some basic tcp/ip address stuff (but operational stuff there is for Microsoft Windows). -- -Scott David Daniels Scott.Daniels at Acm.Org From pythonhda at yahoo.com.replacepythonwithlinux Sun Jun 6 15:07:35 2004 From: pythonhda at yahoo.com.replacepythonwithlinux (pythonhda) Date: Sun, 6 Jun 2004 15:07:35 -0400 Subject: POP3 and email References: <6PFwc.742$8k4.38828@news20.bellglobal.com> Message-ID: <20040606150735.4b631bae.pythonhda@yahoo.com.replacepythonwithlinux> On Sun, 06 Jun 2004 10:25:04 -0400 Paul Schmidt wrote: > > There is some stuff that isn't clear here, can I pass the POP3 message > directly to email for processing, or does it need to be saved to a > temporary file somewhere first? The emails being received will consist > of headers, a tiny amount of text, and one or more MIME attachments. > Yes you can pass the POP3 message directly. IIRC, when you download a message you'll get a tuple back that looks something like (response_code, message, size). The "message" is a list of lines in the message. To have the email package process the message, you can do something like: >>> import email.Parser >>> myemail = email.Parser.Parser().parsestr('\n'.join(mesg[1])) Where mesg is the full tuple that you downloaded. You can use the "get" methods on "myemail" to retrieve the parts you want. This should give you the text of the message (if it isn't a multipart message): >>> mymessage = myemail.get_payload() If it is multipart, use the "walk" method to iterate through each part and the get the payload. >>> for part in myemail.walk(): ... mypart = part.get_payload() ... # do something Check out Text Processing in Python: http://gnosis.cx/TPiP/ It's a great book to buy, chapter 5 is about the email module among other things. From fishboy at spamspamspam.com Wed Jun 2 07:21:33 2004 From: fishboy at spamspamspam.com (fishboy) Date: Wed, 02 Jun 2004 11:21:33 GMT Subject: HTTP Proxy server in python References: <2i4jmoFit192U1@uni-berlin.de> Message-ID: <15erb0do29obfclbithhr4jip7ppnhjhrs@4ax.com> On Wed, 02 Jun 2004 02:03:26 +0200, Ludovico Magnocavallo wrote: >Muhammad Ali wrote: > >> I am thinking of doing a proxy server for this purpose in python that will have >> a list of users and their hours, and would require logging in by the user, calculate >> their times etc. >> >> So, is this the best way of doing this? if not what else can be done? (what ever the >> solution, i would like to implement in python) > >A list of proxy servers implemented in Python can be found here > >http://xhaus.com/alan/python/proxies.html > >L. A place to buy sticks can be found here http://www.sticks.org/buy_sticks.htm In case you go with the "hitting with sticks" solution. ><{{{*> . From michele.simionato at poste.it Thu Jun 3 07:18:01 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 3 Jun 2004 04:18:01 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 2) References: <10bsm3r1h275cd7@corp.supernews.com> Message-ID: <95aa1afa.0406030318.4d8b92f6@posting.google.com> "Cameron Laird" wrote in message news:<10bsm3r1h275cd7 at corp.supernews.com>... > Michele Simionato illustrates Python's itertool-related chop(), > a far different thing than Perl's standard library member > http://mail.python.org/pipermail/python-list/2004-May/222673.html FWIW, I didn't know Perl had a 'chop'. I took the name from Chicken, a Scheme implementation I like a lot. Michele Simionato From me at privacy.net Mon Jun 7 05:52:58 2004 From: me at privacy.net (Duncan Booth) Date: 7 Jun 2004 09:52:58 GMT Subject: r'\' - python parser bug? References: <8089854e.0406070108.72739647@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) wrote in news:8089854e.0406070108.72739647 at posting.google.com: > I've written a command line tool called filestruct that compares a > file structure to a previous state and records the changes (for > remotely syncing directories - you only have to transfer the changes > and then filestruct will make the changes). If you give it a windows > path ending in \" then python interprets it *wrongly*.... Not that you ever need to give a well written script a path ending in \"? Why not just give it the directory without the spurious path separator? > > e.g. > D:\Python Projects\directory change >>> filestruct.py compare > "D:\Python Projects\" b:\test.txt b:\test.zip > filestruct needs at least three arguments when run from the command > line. See : > filestruct.py ? > > The python interpreter assumes that the entirely valid windows path > supplied at the command line actually contains an escaped quote..... I > may have to write a new command line parser to correct this python > 'feature'..... > Python here seems to be in complete agreement with Microft, or at least with their C compiler (not entirely suprising since that's what Python uses). The quote is indeed escaped: C:\temp>type t.c #include int main(int argc, char **argv) { int i; for (i = 0; i < argc; i++) { printf("arg %d= %s\n", i, argv[i]); } } C:\temp>t "c:\Program Files\" c:\temp arg 0= t arg 1= c:\Program Files" c:\temp C:\temp> From jacek.generowicz at cern.ch Tue Jun 29 11:04:03 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 29 Jun 2004 17:04:03 +0200 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: Ville Vainio writes: > Why do we write simple scripts to do simple things? Why do we > serialize data to flat text files in order to process them? Everything > could be so much simpler and immensely more powerful if we operated on > data *directly* - we should operate on objects, lists, dictionaries, > functions, not files. We shouldn't write scripts to perform our > routines - and way too often, we don't even try, because moving the > data between scripts is too troublesome, involving file formats, argv > parsing and other tedious stuff. http://www.scsh.net/ From jani at persian.com Mon Jun 28 17:02:09 2004 From: jani at persian.com (Jani Yusef) Date: 28 Jun 2004 14:02:09 -0700 Subject: starting/killing a process on windows? Message-ID: I am using the win32pipe module to create a process like so: self.proc_in,self.proc_out,self.proc_err=win32pipe.popen3(self.prog) How do I kill this process from within my python application? Obviously, if I exit the script itself this will kill everything but I would like to kill this subprocess and continue execution. Indeed, this subprocess is started from within a child thread of my main application. Any advice? From heikowu at ceosg.de Wed Jun 9 06:23:29 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Wed, 9 Jun 2004 12:23:29 +0200 Subject: Any good python crypto toolkit ? In-Reply-To: <001001c44e0b$271b64d0$0200a8c0@lucifer> References: <001001c44e0b$271b64d0$0200a8c0@lucifer> Message-ID: <200406091223.29932.heikowu@ceosg.de> Am Mittwoch, 9. Juni 2004 12:18 schrieb Simon Roses Femerling: > Any comments ? You won't get around installing some thirdparty libs, in case you want speedy encryption/decryption... What I can recommend: Get PyCrypto from http://www.amk.ca and install http://sourceforge.net/projects/yawpycrypto on top of it. yawPyCrypto shields you from many of the complexities of the underlying code, and offers a uniform interface to encryption using PyCrypto. Example code which demonstrates yawPyCrypto is included in the package on SourceForge. You need to install both yawPyCrypto and Flatten to have a working installation. Flatten is also found on the yawPyCrypto page at SourceForge. I'd love to get some feedback on your mileage... ;) HTH! Heiko. From kbk at shore.net Fri Jun 4 00:27:31 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 04 Jun 2004 04:27:31 GMT Subject: Idle Won't Start - Solution References: Message-ID: <87n03kc5ho.fsf@hydra.localdomain> "Batista, Facundo" writes: > Would be good if you open a bug about this. Yes, and please include a copy of the buggered config file! Thanks! -- KBK From jmeile at hotmail.com Thu Jun 17 15:05:51 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 17 Jun 2004 21:05:51 +0200 Subject: OT: Chat server In-Reply-To: References: Message-ID: <40d1d04d$1@pfaff2.ethz.ch> Hi Miki, > I'm looking for a chat (IRC) server. > Nothing fancy. It has to be free, standalone and with logging. > Python based will be ideal. I was trying to do something similar one or two years ago with zope (a python based framework), but I quit trying because my approach slowed down the server. However, on that time, I also tried to find a python chat and this is what I found: http://groups.google.com/groups?q=chat+group:comp.lang.python.*&start=170&hl=en&lr=&ie=UTF-8&selm=38FE4B4A.5987EA0A%40visionart.com&rnum=176 http://jabberpy.sourceforge.net/ http://www.nightmare.com/medusa/programming.html http://www.amk.ca/python/howto/sockets/sockets.html http://sourceforge.net/projects/pygcs/ I hope it hels. Regards, Josef From BrenBarn at aol.com Sun Jun 27 15:05:02 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 27 Jun 2004 19:05:02 GMT Subject: wxPython syntax References: <40df14b6$0$78546$a1866201@newsreader.visi.com> <40df16a4$0$78546$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > The bottom line is that un-pythonic syntax of wxPython reflects > the un-pythonic syntax of the underlying C++ library. I've noticed this, and I must say it irks me. It seems as though wxPython is simply providing a way to drop C++ code into a Python program, which is, needless to say, undesirable. (I mean, Python is NICE. I use it so I DON'T have to learn ugly C++ stuff.) I don't want to sound harsh, but why is it like this? I suppose the obvious answer is "it's easier to do it that way", but it still seems like it would be nice if there were a real PYTHON GUI library. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From mark at prothon.org Fri Jun 18 04:54:43 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 18 Jun 2004 01:54:43 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: Pierre-Fr?d?ric Caillaud wrote: >> 2) Evaluate the default expression once at each call time when the >> default >> value is needed. The default expression would be evaluated in the >> context >> of the function definition (like a closure). > > > I like Choice 2 because I've always wanted to do the following : > > def func( x, y=2*x ): It looks like you will get your wish. The voting has been pretty much unanimous for option 2. From tkpmep at hotmail.com Fri Jun 11 20:42:40 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 11 Jun 2004 17:42:40 -0700 Subject: Howegrown wordcount References: Message-ID: An embarrassing mistake on my part: I should have typed #Treat iterable inputs differently if "__iter__" in dir(input): wordList =(" ".join([str(item) for item in input])).split() else: wordList = str(input).split() I wish I knew how to treat all possible inputs in a uniform fashion, but I'm nowhere near there as yet, hence the question. That said, it addressess the situations that arise in practice fairly well, though I am sure it can be sped up substantially. Thomas Philips From howard.stearns at charter.net Sun Jun 6 20:53:05 2004 From: howard.stearns at charter.net (Howard Stearns) Date: Sun, 06 Jun 2004 19:53:05 -0500 Subject: generic functions in python In-Reply-To: <40B8DB0E.1040105@charter.net> References: <2hr9vnFfaqsjU1@uni-berlin.de> <40B8DB0E.1040105@charter.net> Message-ID: <40C3BC71.5050206@charter.net> Howard Stearns wrote: > Funny you should mention this today -- I was just sitting down to > implement generic functions myself. ... > When I finish (who knows when?), I'll try to remember to post here and > cc you, Jim. > ... > Jim Newton wrote: >> ... >> perhaps there is a standard >> mult-method-dispatch package available for use? Try this. It's only 55 lines of code plus about that many in comments. Python's pretty cool, no? """ Generic Functions and Methods >>> foo = Generic_Function() >>> foo[object, object, object] = lambda _, x, y, z: 'default' >>> foo[int, int, int] = lambda call_next, x, y, z: ['all ints'] + [call_next(x, y, z)] >>> foo[object, object] = lambda _, x, y: 'just two' >>> foo(1, 2, 3) ['all ints', 'default'] >>> foo(1, 2, 'three') 'default' >>> foo(1, 'two') 'just two' >>> foo('oops') Traceback (most recent call last): ... NoNextMethod: oops """ _AUTHOR=["Howard Stearns (stearns at alum.mit.edu)",] _COPYRIGHT=""" Use this for anything you want, at your own risk. Mistakes here are Howard's fault and no one elses. copyright 2004 As a Python newbie, I do welcome comments on style & performance, as well as on functionality. """ """ There are several simplifications here compared with, say, http://www.lisp.org/table/references.htm#mop - FIXME: Currently, no support for **key args. - No method or class metaobjects or mop. - No support for method combination, or for before/after methods: But there is a call-next-method mechanism, so you can assemble your own results as you like. - No real support for subclassing new kinds of generic functions with their own mechanisms. And there is one extension: + Instead of dispatching only on the classes of a fixed number of positional arguments, dispatch is on both the number and type of arguments. Class precence order is as defined by Python getmro(). David Mertz has a nice package at http://www-106.ibm.com/developerworks/linux/library/l-pydisp.html * This one differs in that there is only a single (powerful?) mechanism for method combination (call-next-method) instead of a built-in list option. * Generic_Function() instances here are also dict objects, and you add/replace method by setting them using the signature as a key. * This implementation builds a cache of effective methods instead of computing dispatches again for each call, so this is a lot faster. """ from UserDict import UserDict from inspect import getmro class NoNextMethod(Exception): pass def raise_NoNextMethod(*args): raise NoNextMethod, args class Generic_Function(UserDict, object): """A function that can have different method bodies separately defined. """ def __init__(self): self.data = {} # All raw methods that have been defined. self.reset() def reset(self): self.cache = {} # Combined methods that have actually been called. # Being a dict, my_func[typeA, typeB, ...] gives the method for those types. def __setitem__(self, signature, method_function): """Add or replace a method. e.g., my_func[Type1, Type2, ...] = lambda call_next, arg1, arg2, ...: body Within the body of the method, call_next is a function with the same signature as the whole generic function. It executes the next more general method that applies to the given arguments. """ self.reset() # Whenever we add a method, it invalidates the cache. UserDict.__setitem__(self, signature, method_function) def __call__(self, *dispatch_args): actual_types = tuple(map(type, dispatch_args)) effective_method = self.cache.get(actual_types) if effective_method == None: effective_method = self.compute_effective_method(actual_types) self.cache[actual_types] = effective_method return effective_method(*dispatch_args) # The next two could reasonably be changed in subclasses to provide different behavior. def compute_effective_method(self, classes): """Uses the applicable method function to produce a single effective method. A method function takes a call_next argument. See __setitem___. An effective method has the same signature as the generic function, and is suitable as a call_next argument to a method function. """ applicable_methods = self.compute_applicable_methods(classes) if applicable_methods == []: return raise_NoNextMethod else: return self.compute_effective_method_from_list(applicable_methods) def compute_applicable_methods(self, classes): pairs = [] for signature, method in self.data.iteritems(): if self.sig_applies_p(signature, classes): pairs.append((signature, method)) pairs.sort(lambda a, b: self.cmp_sigs_relative_to_arg_types(a[0], b[0], classes)) methods = [] return [pair[1] for pair in pairs] # Utilities ... def sig_applies_p(self, method_sig, arg_types): """True if each of method_sig is subclass of each of arg_types, for all of arg_types.""" return reduce((lambda r, (a, b): r and (a!=None) and (b!=None) and issubclass(a, b)), map(None, arg_types, method_sig), True) def cmp_sigs_relative_to_arg_types(self, sig_a, sig_b, arg_types): """At the first place where sig_a and sig_b differ, which comes first in the full class precedence list of the corresponding type in arg_types.""" as, bs = list(sig_a), list(sig_b) for arg_type in arg_types: a = as.pop(0) b = bs.pop(0) if a != b: class_precedence_list = list(getmro(arg_type)) return class_precedence_list.index(a) - class_precedence_list.index(b) def compute_effective_method_from_list(self, method_functions): """Converts a sequence of supplied method functions to a single effective method function.""" rest = method_functions[1:] if rest == []: call_next = raise_NoNextMethod else: more = self.compute_effective_method_from_list(rest) call_next = lambda *args: more(*args) return lambda *args: method_functions[0](call_next, *args) def _test(): import doctest, Generic_Function return doctest.testmod(Generic_Function) if __name__ == "__main__": _test() From michele.simionato at gmail.com Thu Jun 24 00:27:32 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Jun 2004 21:27:32 -0700 Subject: how to obtain its ip address ? References: <40d9c75d$0$26573$626a14ce@news.free.fr> Message-ID: <4edc17eb.0406232027.6ac67759@posting.google.com> marco wrote in message news:<40d9c75d$0$26573$626a14ce at news.free.fr>... > I'd search a lot ... but i had not found > how can i obtain my ip address (when i'm connected to the www) ?! > > thanks a lot for any tips > marco In may case on linux this worked: $ wget -q "http://ipid.shat.net/iponly" -O - |sed -n 3p This gives your address as seen from outside, which is probably what you want, whereas other solutions I tried were giving me my local address on the LAN. Michele Simionato From tomasz_widomski at o2.pl Wed Jun 30 06:54:01 2004 From: tomasz_widomski at o2.pl (Tomasz) Date: Wed, 30 Jun 2004 12:54:01 +0200 Subject: Using Python with SyBase References: <40dbbf6b$0$16984$79c14f64@nan-newsreader-04.noos.net> Message-ID: Hello Francois, Thank you for repling. I am exately interesting in old ex-wotcom sql oriented products. At the moment I still use old WatCom 4.0 but I like to transfer to new ASA products. Becouse I am not so happy with visual products (Visual Basic, Power Builder etc.), I am looking for nice languague I can easly write front-end screens in text mode. Python gives me a good fealling for that it seams it is what I am looking for. I am bit afreraid for stability of Python and for speed relaibility (it is just an interpreter only). Please let me know your opinion if any. Best Regards, Tomasz U?ytkownik "francois lepoutre" napisa? w wiadomo?ci news:40dbbf6b$0$16984$79c14f64 at nan-newsreader-04.noos.net... > Hi, > > > Does anybody expirience Python for writing user > > front-end screens for SyBase-Anyware database ? > > Sybase Anywhere ASA (ex-watcom sql) is an > odbc-orientated dbms solution from Sybase. > > We have been succssful using it from python via > mxodbc both on linux (some tweaking may be > required) and win32 (plain easy). > > I have no experience or feedback of ASA > connections through FreeTDS. > > It should work as well... I'd be glad to hear > that it does:) > > Fran?ois > > From davidf at sjsoft.com Wed Jun 30 13:05:26 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 19:05:26 +0200 Subject: setting icon using py2exe? In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2004-06-30, Thomas Heller wrote: > > >>>Never mind.... >>> >>>Further googling reveals this is a known bug when running under >>>Win98/Me: >>> >>>http://groups.google.com/groups?th=4d594c535345b98b >> >>The bug should be fixed in CVS. Since py2exe now can also be built with >>MingW32, you could try that, even if you don't have MSVC. Or you have >>to wait for the release. > > > Thanks! If I run out of things to do, I'll install MingW32 and > try to build the CVS code. Otherwise I'll wait for the next > release. > Or if you don't have time for that you could try this build which is from latest CVS: http://davidf.sjsoft.com/files/py2exe-0.5.1a1.win32-py2.3.exe Untested :-) David From indigo at bitglue.com Tue Jun 29 13:37:44 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 29 Jun 2004 13:37:44 -0400 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] In-Reply-To: References: Message-ID: <20040629173744.GA6091@unununium.org> I'm forwarding this to the Unununium mailing list. I think the two projects are solving the same problem from opposite ends. On Tue, Jun 29, 2004 at 05:03:18PM +0300, Ville Vainio wrote: > Pythonic Nirvana - towards a true Object Oriented Environment > ============================================================= > > IPython (by Francois Pinard) recently (next release - changes are > still in CVS) got the basic abilities of a system shell (like > bash). Actually, using it as a shell is rather comfortable. This all > made me think... > > ... From sridharinfinity at gmail.com Mon Jun 28 16:21:09 2004 From: sridharinfinity at gmail.com (Sridhar R) Date: 28 Jun 2004 13:21:09 -0700 Subject: python desktop References: Message-ID: <8816fcf8.0406281221.2acb51e7@posting.google.com> km wrote in message news:... > Hi all, > Are there any plans for a pure python desktop for linux ? > are there any similar projects ? > regards, > KM http://www.freenet.org.nz/python/pywm/ http://kahakai.sourceforge.net/ From peter at engcorp.com Wed Jun 16 14:59:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 14:59:50 -0400 Subject: What ought to persist after a program is run? In-Reply-To: References: Message-ID: Thomas Philips wrote: > Why does 'hero' not appear in the workspace directory when main() is > invoked and vice versa? Variables are considered local to functions unless explicitly specified otherwise. Since you don't say anything about hero, it is local and therefore does not persist after main() completes. What you might be looking for is the global keyword. If you put "global hero" anywhere in main() before you use the name hero, any references to it are treated as global to the module instead of local, and it will then appear in the "workspace directory"** after main() completes. -Peter ** By that term, I assume you mean it appears when you type dir() at an interactive prompt or something. The term has no meaning to me (perhaps because I don't use IDLE). From mxp at dynalabs.de Mon Jun 7 05:27:32 2004 From: mxp at dynalabs.de (Michael Piotrowski) Date: Mon, 07 Jun 2004 11:27:32 +0200 Subject: left-quote ( ` ) on International keyboards [Prothon] References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: "Mark Hahn" writes: > I never thought of it being used as an accent mark. I always thought of it > as a crummy left-quote. That explains why it is always drawn so high. You may want to have a look at for details. Personally, I don't think it was a good idea to define character 0x60 as GRAVE ACCENT, but that's what we have ... -- Michael Piotrowski, M.A. Public key at From rigga at hasnomail.com Fri Jun 18 15:54:59 2004 From: rigga at hasnomail.com (RiGGa) Date: Fri, 18 Jun 2004 20:54:59 +0100 Subject: Remove spaces and line wraps from html? References: Message-ID: <5MHAc.16619$NK4.2886117@stones.force9.net> Paramjit Oberoi wrote: >> I have a html file that I need to process and it contains text in this >> format: > > Try: > > http://groups.google.com/groups?q=HTMLPrinter&hl=en&lr=&ie=UTF-8&c2coff=1&selm=pan.2004.03.27.22.05.55.384482 40hotmail.com&rnum=1 > > (or search c.l.p for "HTMLPrinter") Thanks, I forgot to mention I am new to Python so I dont yet know how to use that example :( From elbertlev at hotmail.com Wed Jun 23 15:05:46 2004 From: elbertlev at hotmail.com (Lev Elblert) Date: 23 Jun 2004 12:05:46 -0700 Subject: shared file access in python References: <9418be08.0406180620.3e64be96@posting.google.com> <9418be08.0406210618.492f40d4@posting.google.com> Message-ID: <9418be08.0406231105.13e3bc9e@posting.google.com> Peter! I do not know what kind of msvcrt module you have, but here is the output of relavant commands on my machine: >>> import msvcrt >>> str(msvcrt) "" >>> print msvcrt.__doc__ None >>> dir (msvcrt) ['LK_LOCK', 'LK_NBLCK', 'LK_NBRLCK', 'LK_RLCK', 'LK_UNLCK', '__doc__', '__name__', 'get_osfhandle', 'getch', 'getche', 'heapmin', 'kbhit', 'locking', 'open_osfhandle', 'putch', 'setmode', 'ungetch'] >>> out of all functions, probably kbhit and getch are used, to control multythereaded applications from console. Peter Hansen wrote in message news:... > Lev Elblert wrote: > > > 2. msvcrt.lib does have a lot of functions, but not msvcrt module in > > Python. (correct me if I'm wrong) > > http://docs.python.org/lib/module-msvcrt.html shows there are a variety > of functions there (try typing "import msvcrt" as well), but I can't > see that they have what you need. > > -Peter From peter at engcorp.com Sat Jun 19 09:28:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 09:28:00 -0400 Subject: str() for containers In-Reply-To: References: <40d07ac6@rutgers.edu> <10d8d4696tjkf1b@news.supernews.com> Message-ID: Marcin 'Qrczak' Kowalczyk wrote: > On Sat, 19 Jun 2004 08:41:56 -0400, John Roth wrote: > > >>The only clean solution I can see is to provide a third built-in >>that provides the "right" output when a container class needs >>to turn an object into a string. > > > What is the right thing e.g. for strings? Exactly. ;-) From imbosol at aerojockey.invalid Sun Jun 6 18:36:07 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 06 Jun 2004 22:36:07 GMT Subject: Dynamically adding methods to objects? References: <29381ecf.0406052305.5b558d24@posting.google.com> <10c5u9n6mlibb55@news.supernews.com> Message-ID: John Roth wrote: > "Holger T?rk" wrote in message > news:c9um21$hca$03$1 at news.t-online.com... >> damian birchler wrote: >> > I know how to do it manually, I just define a function and assigne it >> > to f - >> > >> > def bar(): >> > pass >> > >> > f.bar = bar -, >> > but what if this should be done at runtime. How can I get the string >> > passed to f.add_function as name to be the name of a new function in >> > the function's definiton? >> >> f.bar = bar is the same as setattr (f, "bar", bar) >> >> Remember that bar does not become a method of f, but remains >> only a function which is stored in f. Is not subject of the >> binding of the "self" parameter. > > Ah, but that's what I want to do - have a ***method*** > where the self parameter works the way I expect it to. Is this what you want? def selfize(obj,func): def callfunc(*args,**kwargs): func(obj,*args,**kwargs) return callfunc f.bar = withself(f,bar) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From rogerb at rogerbinns.com Fri Jun 18 21:02:45 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 18 Jun 2004 18:02:45 -0700 Subject: Queue module and Python Documentation Rant References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: Roel Schroeven wrote: > Well, not everybody: I don't like the PHP documentation at all. Part of > the problem is precisely the user comments: You don't have to read them :-) They are clearly distinguished from the documentation itself. > if you don't. And often they contradict each other, or are written by > newbies who feel it is their duty to share their clumsy re-invention of > the wheel to the whole community. To be honest I would rather have that and ignore them, than have nothing. (That is a the cathedral vs the bazaar style situation). > What should be done is regularly incorporate the useful information from > the user comments in the documentation itself and then remove the user > comments. I believe they do that, although I don't think it is done often enough. > I also find it very confusing and impractical that the user comments are > sorted from newest to oldest: Agreed. Roger From dontaskme at doityourself.com Wed Jun 16 16:06:46 2004 From: dontaskme at doityourself.com (Meno) Date: 16 Jun 2004 13:06:46 -0700 Subject: Something simular to java's hsqldb for python?? References: <792ea523.0406160601.1b217d78@posting.google.com> Message-ID: <9c2d8268.0406161206.750c702d@posting.google.com> pet100us at yahoo.com (pet100us) wrote in message news:<792ea523.0406160601.1b217d78 at posting.google.com>... > Hi, > > Is there some program that is simular to java's hsqldb > (http://hsqldb.sourceforge.net/). It is a relational database that can > easily be used within a small java program without installing a MySQL, > Postgresql etc. It is used within the same virtual machine whitout > installing anything extra. > You can give a try to SQLite (http://www.sqlite.org/) using PySQLite (http://sourceforge.net/projects/pysqlite/). Meno. From nospam at here.com Wed Jun 16 09:59:05 2004 From: nospam at here.com (Matt Feinstein) Date: Wed, 16 Jun 2004 09:59:05 -0400 Subject: Rationale for core Python numeric types Message-ID: Hi all-- I'm new to Python, and was somewhat taken aback to discover that the core language lacks some basic numerical types (e.g., single-precision float, short integers). I realize that there are extensions that add these types-- But what's the rationale for leaving them out? Have I wandered into a zone in the space/time continuum where people never have to read binary data files? Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From donn at u.washington.edu Wed Jun 16 15:22:41 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 16 Jun 2004 12:22:41 -0700 Subject: What ought to persist after a program is run? References: Message-ID: In article , tkpmep at hotmail.com (Thomas Philips) wrote: > Here's a very simple program with an odd twist: > class Player(object): > def __init__(self,name): > self.name = name > > hero = Player("A") > print "hero",hero > > If I run it in IDLE and then type dir() at the prompt, I get > >>>['Player', '__builtins__', '__doc__', '__name__', 'hero'] > > However, if I modify the program as follows > class Player(object): > def __init__(self,name): > self.name = name > def main(): > hero = Player("A") > print "hero=",hero > main() > > and then run it in IDLE and type dir at the prompt, I get > >>>['Player', '__builtins__', '__doc__', '__name__'] > > Why does 'hero' not appear in the workspace directory when main() is > invoked and vice versa? Because main(), like any function, binds the object to its local namespace, not the "global" (module) namespace. Each function has its own, separate namespace, every time it's invoked. Ordinarily, the module namespace is mostly populated with functions, classes etc. defined in the module source (or typed in at the keyboard in your case.) Functions use their own namespaces for scratch space, and "return" the results of their computation, or modify input parameters. This isolation simplifies interdependencies between functions, so they're easier to manage as code gets rewritten. Donn Cave, donn at u.washington.edu From vincent at visualtrans.de Wed Jun 30 05:02:23 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 30 Jun 2004 11:02:23 +0200 Subject: making mpegs with python? In-Reply-To: References: Message-ID: Darren Dale wrote: > I am trying to make the switch from Matlab, which I use to create plots > and images, grab those images, and put them together in a movie format. > Are there Python tools that can do this? > > Thanks, > Darren openvip perhaps? (http://openvip.sourceforge.net/) -- Vincent Wehren From vincent at visualtrans.de Wed Jun 30 05:10:57 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 30 Jun 2004 11:10:57 +0200 Subject: UnboundLocalError on shadowed import In-Reply-To: References: Message-ID: Peter Hansen wrote: > It "has to" raise an exception. The use of "sys" inside the function > is local (because you assign to it, because "import sys" is effectively > an assignment). Locals are not handled quite the same as other names, > as you know -- they are turned into index lookups in a list instead of > hash lookups in a dictionary. The interpreter can't know that your use > of sys.exit(0) is supposed to refer to the global sys, because all uses > of "sys" are really just "local variable number 3" or something like > that inside the function. > > Basically, "don't do that" is about the best you'll get, I think. Well, just for the sake of it, there still is the obvious option of adding the line "global sys" before sys.exit(0) to tell the interpreter to use the "globally imported sys". -- Vincent Wehren From peter at engcorp.com Tue Jun 8 07:06:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jun 2004 07:06:48 -0400 Subject: Catching a traceback In-Reply-To: <10cae3gsob80jb2@corp.supernews.com> References: <10cae3gsob80jb2@corp.supernews.com> Message-ID: Michael Geary wrote: > import traceback, win32ui > > def main(): > print unknown > > class TraceLog: > def __init__( self ): > self.text = '' > > def write( self, text ): > self.text += text > > try: > main() > except: > log = TraceLog() > traceback.print_exc( file=log ) > win32ui.MessageBox( log.text, 'Error' ) Simpler to use format_exception() and not do all that stuff with TraceLog, unless you already had it around for something else: except: tb = traceback.format_exception(*sys.exc_info()) win32ui.MessageBox(''.join(tb), 'Error') -Peter From holger at butschek.com Fri Jun 4 06:21:04 2004 From: holger at butschek.com (Holger Butschek) Date: Fri, 04 Jun 2004 12:21:04 +0200 Subject: DTML Zope (element of list?) Message-ID: Hy folks, I have a problem in Zope (DTML). I know, that it's a very simple problem, but I'm quite new to Zope. I want to check, if a sequence-item of a sql-statement is in a list called groupsSW (this list might or might not be given by URL from a previous window). Therefor, I have following code designed. I know that it doesn't work this way: bgcolor="#CCCCCC">
    checked
    - keine Eintr?ge vorhanden -
    If the element is in the list, then I want it CHECKED. Please help me. Holger Butschek -- Erstellt mit M2, Operas revolution?rem E-Mail-Modul: http://www.opera.com/m2/ From tim.peters at gmail.com Tue Jun 22 21:45:49 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 22 Jun 2004 21:45:49 -0400 Subject: [python] using try: finally: except In-Reply-To: <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> Message-ID: <1f7befae0406221845f79210a@mail.gmail.com> [Peter Hansen, on mixing 'except' with 'finally' clauses] > I recall differently. I recall reading several times that since > it is completely ambiguous what the programmer meant if both are > specified together, Guido deliberately kept them separate so that > one had to be very explicit about whether the finally was inside > or outside the except. It's more that Guido deliberately separated them. Before Python 0.9.6, you could attach both 'except' and 'finally' clauses to the same 'try' structure (see Misc/HISTORY in a Python source distribution). I don't remember the semantics, and that was indeed the problem: nobody could remember, and half the time guessed wrong. From newsgroups at jhrothjr.com Sat Jun 19 08:41:56 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 19 Jun 2004 08:41:56 -0400 Subject: str() for containers References: <40d07ac6@rutgers.edu> Message-ID: <10d8d4696tjkf1b@news.supernews.com> "George Sakkis" wrote in message news:40d07ac6 at rutgers.edu... > Hi all, > > I find the string representation behaviour of builtin containers > (tuples,lists,dicts) unintuitive in that they don't call recursively str() > on their contents (e.g. as in Java) : > It's even more cumbersome for containers of containers (e.g. lists of dicts, > etc.). Of course one can (or should) encapsulate such stuctures in a class > and define __str__ to behave as expected, but why not having it by default ? > Is there a good reason for this ? I don't think there's a ***good*** reason. The root of the issue is that the str() / repr() distinction is too simplistic for containers. The output of str() is supposed to be human readable, and the output of repr() is supposed to be able to round-trip through exec/eval (which is not always possible, but should be maintained if it is.) Human readable output from a container, however, needs to be very clear on the distinction between the container and the objects that are contained. It isn't always obvious whether using str() or repr() on the contained object is the best policy, and in some cases I suspect that something different from either would be helpful. The only clean solution I can see is to provide a third built-in that provides the "right" output when a container class needs to turn an object into a string. However, someone else is going to have to do the work of writing up the use cases and the PEP - I don't care enough. John Roth > > George > > From myaltkey at msn.com Sat Jun 26 11:27:33 2004 From: myaltkey at msn.com (altkey) Date: Sat, 26 Jun 2004 23:27:33 +0800 Subject: new to this References: Message-ID: <40dd961e@funnel.arach.net.au> pearsoneric wrote: > I have never tried to program before but I'm starting a class and I > was wondering if anyone knew the best way to get started learning > about python?? Any help would be very much welcomed because I have > no idea what I'm doing.. Are there any good books out there? The is a very good book for beginners called "The complete beginners guide to Python". It will teach you both about python and about programming. Get a copy from either your library or from a bookstore. I think it will help you a lot. cheers, Phil From nemesis at nowhere.invalid Fri Jun 18 14:13:47 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Fri, 18 Jun 2004 18:13:47 GMT Subject: [ANN] XPN 0.3.0 released Message-ID: XPN is a newsreader fully written in python with pygtk+gtk2. It is an online newsreader with unicode support. Major changes in this release: * v0.3.0: now headers are collected with XOVER command. * v0.3.0: added scoring system, with a simple rules editor/viewer (see xpn.html for the details). * v0.3.0: little changes in the header encoding. Now the encoding used for the header is not linked to the encoding used for the body. * v0.3.0: fixed a bug in the custom headers support. * v0.3.0: little changes in the rot13 support. * v0.3.0: added "find in the body" feature. * v0.3.0: added regular expressions support whe you search a group in the Groups Window. * v0.3.0: added article search feature. Now you can search an article in the threads pane, also with regular expressions. You can search in From, Subject, Msg-id and References headers and in the body (only for read articles), and combine the results with AND or OR logic. * v0.3.0: a lot of little changes and fixes. You can get it on: http://sf.net/projects/xpn Here you can find a source versione and a win32 binary installer version. -- Confucius say...If chain still swinging seat will be warm. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From kyleroot at gmail.com Sat Jun 26 10:34:30 2004 From: kyleroot at gmail.com (Kyle Root) Date: Sat, 26 Jun 2004 14:34:30 GMT Subject: what editor do you use? In-Reply-To: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. vim of course. :) From p_s_oberoi at hotmail.com Wed Jun 30 21:48:45 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Wed, 30 Jun 2004 20:48:45 -0500 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <23891c90.0406290244.74c4ce2b@posting.google.com> <87isd8hh22.fsf@pobox.com> <7xfz8cttu3.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 30 Jun 2004 18:11:16 -0700, Paul Rubin wrote: > programs. That means using BSD turns off a certain subset of > potential volunteer contributors. Microsoft already gives me enough > > Using GPL may also turn off some contributors; whether that number is > higher or lower, I can't know for certain. But I do notice that the I can't claim to speak for others, but the few contributions that I have made to open source software projects have been because the software didn't do what I wanted it to do, and I was simply implementing that functionality for myself. The exact license probably doesn't affect people with this motivation... we do what we have to do, despite the license. -param From lbates at swamisoft.com Tue Jun 15 09:26:41 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 15 Jun 2004 08:26:41 -0500 Subject: attribute access and comparisons of two different objects References: <2418de8e.0406150420.1c1bde76@posting.google.com> Message-ID: 1) In Python 2.3 there is a new __slots__ methodology that does what you want with class attributes. One must wonder how everyone got by without it for so many years. I'm not sure I understand the "overhead" issue. Some code must be executed to determine if an attribute exists or not, why shouldn't it be up to the programmer to write it by overriding __setattr__ method? 2) Why don't these programming languages do what I mean instead of what I tell them to do? ;-) HTH, Larry Bates Syscon, Inc. "Chris..." wrote in message news:2418de8e.0406150420.1c1bde76 at posting.google.com... > Two simple questions regarding future of Python: > > 1) Is there already a "fix" to avoid writing to an attribute that > isn't defined yet? I remember this being an often discussed problem, > but didn't see any changes. The only way I can think of is overriding > __setattr__, but this is huge overhead. While I like the idea of > being able to add new attributes on the fly, in great projects I'd > like to restrict some classes not to do so. > > 2) This is driving me nuts: I do not want to compare apples and peas. > I can say that they are not equal, but I cannot say that one is great > than the other (speaking not of greater taste ;-). Just ran into a > problem caused by comparing a string with a number ("1" > 10) -- I > simply forgot to convert the string to an integer. Since I cannot add > "1" + 10 which makes sense, I do not want to compare them. Any > development regarding this? Any """from __future__ import"""? > > - Chris From tdelaney at avaya.com Tue Jun 8 17:40:57 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 9 Jun 2004 07:40:57 +1000 Subject: Python Speed Question and Opinion Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE018F09F0@au3010avexu1.global.avaya.com> > Irmen de Jong wrote in message > news:<40c1e793$0$563$e4fe514c at news.xs4all.nl>... >> Maboroshi wrote: >> >> I have taken the liberty of taking a few of the comments made >> in this thread and writing them down here: >> http://www.razorvine.net/python/PythonSpeed >> I've added a few other things related to Python's performance, >> such as a short reference to Psyco. Can't find your original post here Irmen ... Might be an idea to mention that `list.sort` will include built-in support for DSU in Python 2.4. Cheers. Tim Delaney From sholden at holdenweb.com Sat Jun 26 01:02:36 2004 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 26 Jun 2004 01:02:36 -0400 Subject: question about cx_Oracle .thanks In-Reply-To: References: <2k2eq0F17aa0uU1@uni-berlin.de> Message-ID: <40DD036C.5060101@holdenweb.com> Peter Hansen wrote: [...] > Since it has a limited number of binary digits available, it can't > store precisely 42055.66, so 42055.6600000whatever is the next > closest. To demonstrate, the nearest neighbours that can be > represented accurately are these (binary value one higher or lower): > > >>> struct.unpack('>d', binascii.unhexlify('40e488f51eb851ed')) > (42055.660000000011,) > >>> struct.unpack('>d', binascii.unhexlify('40e488f51eb851eb')) > (42055.659999999996,) > > So clearly the binary can capture only increments of about > 0.000000000007 or 0.000000000008 at a time, and all of these > values must be treated as approximations... unless one was > trying to store 42055.660000000003 in the first place! > Just to make things even more complicated, of course, we must also remember that the delta between two adjacent floating-point numbers isn't constant, but will vary according to the magnitude of the numbers. >> - this is an accurate decimal representation of the binary value: >> >> >>> print repr(42055.66) >> 42055.660000000003 > > > All very true. ;-) > And it just goes to show that floating-point is quite confusing enough to make many a beginner run away in fright! regards Steve From chuck at smtl.co.uk Mon Jun 7 12:15:06 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Mon, 07 Jun 2004 17:15:06 +0100 Subject: simple script to read and parse mailbox In-Reply-To: Your message of "Mon, 07 Jun 2004 02:53:02 GMT." References: Message-ID: <200406071615.i57GF6eb030232@sevenofnine.smtl.co.uk> Sorry to bovver you again (again) here's script. I still can't see why the get_payload() doesn't produce the plain text message body of an emails in the testwwws users mailbox. AS you can see I have tried a few things but no joy what am I missing. Cheers Chuck ds9:[pythonScriptMail] % cat getSurveyMail.py ############################################################### ## This script will open and parse email messages body content. ## This Python script will reside on Mail Server on ds9: ## Emails are all plain/text you could just write the following ## Which will leave a list of strings , each one a message body. ## The Survey User is testwws and the .procmailrc file folder is ## Survey . i.e /home/testwws/Mail/inbox/Survey . ############################################################### ## file:getSurveyMail.py Created : 06/06/04 Amended date: 07/06/04 ############################################################### #The following line makes it run itself(executable script on UN*X) #!/usr/bin/env python import sys import os import email import mailbox # Open the testwws user mailbox (tmp user chuck) # fp denotes factory paraemeter # mode can be 'r' when the file will only be read, 'w' for only writing #(an existing file with the same name will be erased), and 'a' opens the file # for appending; any data written to the file is automatically added to the end. # 'r+' opens the file for both reading and writing. The mode. output =("/tmp/SurveyResults", "w+a") #output =('/tmp/SurveyResults','w') # open() returns a file object, and is most commonly used with two arguments: # "open(filename, mode)". # /home/testwwws/Mail/work # #fp The file or file-like object passed at instantiation time. This can be used to read the message content. fp = open("/var/spool/mail/testwwws") #fp = open("/home/testwwws/Mail/work") # message_from_file returns a message object struct tree from an # open file object. mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] msg = email.message_from_file(fp) # for loop iterates through the msg in the mbox(mailbox). # Subparts of messages can be accessed via the - # get_payload() method will return a string object. # If it is multipart, use the "walk" method to iterate through each part and the # get the payload.In our case it's not multipart So ignore. # for part in msg.walk(): # msg = part.get_payload() # # do something(print) for msg in mbox: body = msg.get_payload() bodies.append(body) # output.close() to close it and free up any system resources taken up by the open file. # After calling output.close(), attempts to use the file object will automatically fail. #print bodies print fp print msg print msg['body'] # print body - NameError: name 'msg' is not defined # #print >> output,bodies #output.close() #print the bodies list of the messages. print bodies From david at rebirthing.co.nz Fri Jun 18 23:11:32 2004 From: david at rebirthing.co.nz (David McNab) Date: Sat, 19 Jun 2004 15:11:32 +1200 Subject: test if PyObject * points to real python object Message-ID: <40D3AEE4.5010307@rebirthing.co.nz> Hi, With the Python/C API, how do i test if a given PyObject * actually points to a real/valid python object? -- Cheers David From balaji at email.arizona.edu Wed Jun 16 18:30:47 2004 From: balaji at email.arizona.edu (Balaji) Date: 16 Jun 2004 15:30:47 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> <494182a9.0406141915.7061d0f6@posting.google.com> Message-ID: <494182a9.0406160853.3c3546fe@posting.google.com> Dear Dan, What I'm trying to do in my application is preserve the order in which the user wrote an expression. If a user writes e1=100>=x, python treats it as e1= x<=100. Both are same mathematically but semantically they are not. If a user prints this expression he will get e1= x<=100, which is different than e1=100<=x. In my application both the <= and >= have totally different meaning. They are not just used for comparisson. Regards Balaji From python at quixs.com Thu Jun 24 08:15:02 2004 From: python at quixs.com (Lars Heuer) Date: Thu, 24 Jun 2004 14:15:02 +0200 Subject: Mozilla, XUL and the snake In-Reply-To: References: <6ld6bc.5b3.ln@news1.interplanet.it> Message-ID: <169234104.20040624141502@quixs.com> Hi Jakub, >> yeah, theoretically is it possible by using PyXPCOM: >> >> > Isn't using JavaScript the only way to call XPCOM objects from XUL? I No, pyXPCOM does it, too. > was aware of PyXPCOM, I was just wondering whether it was possible to > get rid of JavaScript altogether... Currently you'll have to use JavaScript to let the XUL forms react to user's input etc., it's not possible to replace JavaScript with Python (currently). Best regards, Lars From guettli at thomas-guettler.de Mon Jun 21 03:03:17 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 21 Jun 2004 09:03:17 +0200 Subject: DocumentationTools (docstring --> html) Message-ID: Hi, I want to create documentation in html from docstrings. According to this URL, there are many projects: http://www.python.org/cgi-bin/moinmoin/DocumentationTools * PyDoc, http://web.pydoc.org/ * DocUtils, http://docutils.sourceforge.net/ ReStructuredText processing engine * EpyDoc, http://epydoc.sourceforge.net/ * HappyDoc, http://happydoc.sourceforge.net/ * PythonDoc - uses ReStructuredText input format, and can produce HTML and XML output. It uses XML as an intermediate representation, to simplify the addition of new output formats. http://starship.python.net/crew/danilo/pythondoc/ * Crystal - produces output that is similar to [Wiki]JavaDoc. * EasyDoc - uses an HTML-like markup language, similar to the language used by [Wiki]JavaDoc; and produces HTML output (http://htmltmpl.sourceforge.net/easydoc.html) * Teud, [EfnetPythonWiki]TeudProject Can someone give me an advice which one to choose? Thomas From kkto at csis.hku.hk Fri Jun 18 06:52:36 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 18 Jun 2004 18:52:36 +0800 Subject: does python have useless destructors? References: <7ifz8udxp2.fsf@enark.csis.hku.hk> Message-ID: <7ik6y5f897.fsf@enark.csis.hku.hk> >>>>> "Marcin" == Marcin 'Qrczak' Kowalczyk writes: Marcin> What would happen when you store a reference to such object in Marcin> another object? Depending on the answer, it's either severely Marcin> limited (you can introduce no abstractions which deal with files Marcin> somewhere inside), or as inefficient as reference counting. Marcin> The only way is to somehow distinguish variables for which Marcin> objects they point to should be finalized, from plain Marcin> variables. Not objects but variables. try...finally and with are Marcin> examples of that. If I understand it correctly, PEP 310 doesn't deal with that use case at all. In my opinion the language shouldn't try it. Just let the program fail. Treat programmers as grown men who will not try to break things on purpose. You can always close a file and then continue to read it. All the system do is to give you an exception. If we can accept this, why we worry that much if the construct close the file too early if a reference remains when the function close? An "auto" or "function scoped" object is simply a means to simplify functions, i.e., let you write auto myvar = new file line = myvar.readline() ... # ignore the difficulty of closing it rather than myvar = None try: myvar = new file line = myvar.readline() ... finally: if myvar: myvar.close() The only purpose is to simplify the program. We shouldn't (and actually won't be able to) add extra responsibility to it, e.g., make sure it is reference counted so that the file is closed only when no more reference remains. If the second program above doesn't do that, we shouldn't expect it either in the first program. Just throw an exception whenever somebody wants to exceed the capability of the construct. Regards, Isaac. From FBatista at uniFON.com.ar Tue Jun 22 09:06:54 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 22 Jun 2004 10:06:54 -0300 Subject: RV: How to make an immutable instance Message-ID: Thank you for your assistance. I'll go in Decimal with a solution with property() and *single* underscore: class C(object): __slots__ = ('_x',) def __init__(self, value): self._x = value def getx(self): return self._x x = property(getx) This implies good security against accidental changes and saves me from a *lot* (a lot!) of code changing in Decimal.py Thanks again. Facundo Batista Desarrollo de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5097 5024 -----Mensaje original----- De: Batista, Facundo Enviado el: Jueves 17 de Junio de 2004 2:52 PM Para: Python-List (E-mail) Asunto: How to make an immutable instance I'm working on Decimal, and one of the PEP requests is Decimal to be immutable. The closer I got to that is (in short): class C(object): __slots__ = ('__x',) def __init__(self, value): self.__x = value def getx(self): return self.__x x = property(getx) This way, you can not modify the instance: >>> import imm >>> c = C(4) >>> c.x 4 >>> c.x = 3 Traceback (most recent call last): File "", line 1, in -toplevel- c.x = 3 AttributeError: can't set attribute >>> c.a = 3 Traceback (most recent call last): File "", line 1, in -toplevel- c.a = 3 AttributeError: 'C' object has no attribute 'a' >>> hash(c) 10777424 The problem is that you actually could, if you take the effort, to rebind the __x name. So, if you use this "immutable" class in a dict, and then you (on purpose) modify it, you'll have different hashes. Said that, how safer is this approach? Is there a better way? Thank you all! . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. From ergin_aytac at yahoo.de Fri Jun 25 18:13:23 2004 From: ergin_aytac at yahoo.de (Ergin Aytac) Date: Fri, 25 Jun 2004 22:13:23 GMT Subject: SocketServer Problem Message-ID: <7s1Dc.126130$vP.103291@news.chello.at> I'm trying to run a script written in python and have some socket connection problems. I cutted the origin script (more than 1000 lines) so it is only the part of the connection and there is no functionalty but connecting to a server. I have no idea about programming with python so every hint is a present for me :) ------------------------------------ import SocketServer import os nntp_hostname = 'news.chello.at' nntp_port = 119 if os.name == 'posix': class NNTPServer(SocketServer.ForkingTCPServer): allow_reuse_address = 1 max_children = 20 else: class NNTPServer(SocketServer.ThreadingTCPServer): allow_reuse_address = 1 class NNTPRequestHandler(SocketServer.StreamRequestHandler): # this is the list of supported commands def handle(self): self.input = self.rfile.read(1024) print self.input print os.name print nntp_hostname print nntp_port server = NNTPServer((nntp_hostname, nntp_port), NNTPRequestHandler) ------------------------------------- I get the following error on windows: File "D:\tmp\test\test.py", line 27, in ? server = NNTPServer((nntp_hostname, nntp_port), NNTPRequestHandler) File "D:\PYTHON23\lib\SocketServer.py", line 330, in __init__ self.server_bind() File "D:\PYTHON23\lib\SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "", line 1, in bind socket.error: (10049, "Can't assign requested address") On Linux I get the same message but the error number is 99, "Can't assign requested address" - I tried with python 2.3.2 on windows and linux - I tried with python 2.3.4 on windows and linux - I tried with other servers and ports .. - I tried without firewall .. - I tried with user root on linux .. - I tried with ip instead of domain name ... - I tried on 7 other boxes with 3 other isp with and without firewall ... - I also tried the original script ... ... but nothing changed. telnet works fine with every server and port I used for the tests. The script above worked without any error message on a box of friend. If you have any idea please let me know. thanx Ergin From michele.simionato at poste.it Wed Jun 16 00:08:22 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Jun 2004 21:08:22 -0700 Subject: attribute access and comparisons of two different objects References: <2418de8e.0406150420.1c1bde76@posting.google.com> Message-ID: <95aa1afa.0406152008.2d2ddaf8@posting.google.com> "Larry Bates" wrote in message news:... > 1) In Python 2.3 there is a new __slots__ methodology that > does what you want with class attributes. One must wonder > how everyone got by without it for so many years. I'm not > sure I understand the "overhead" issue. Some code must be > executed to determine if an attribute exists or not, why > shouldn't it be up to the programmer to write it by > overriding __setattr__ method? __slots__ should never be used to restrict attribute access; they are just a memory saving optimization; you are better off not using it if you can. See this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Yes, overriding __setattr__ has a performance overhaud, so just do not freeze your attributes! That's the Pythonic solution. Michele Simionato From irmen at -nospam-remove-this-xs4all.nl Sat Jun 5 13:13:06 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 05 Jun 2004 19:13:06 +0200 Subject: Python Speed Question and Opinion In-Reply-To: References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> Message-ID: <40c1ff22$0$15440$e4fe514c@news.xs4all.nl> djw wrote: >> http://www.razorvine.net/python/PythonSpeed > I don't think I agree with your statement at the bottom that says "if > all else fails, try Psyco." Since using Psyco is so effortless and may > produce dramatic speedups, I would recommend to people that they try it > before resorting to writing extension modules in C/C++. Sending people > that are new to Python down the extension writing path may turn them off > to Python altogether. I think you're right. So I changed the order a bit and removed the "if all else fails" :) Feel free to add other suggestions to the page. It's a WIKI page after all. --Irmen From zen19725 at zen.co.uk Sat Jun 19 19:09:01 2004 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 20 Jun 2004 00:09:01 +0100 Subject: Game - Map data structures References: Message-ID: On 18 Jun 2004 23:08:27 -0700, Dan Bishop wrote: >Innocence wrote in message news:... >> Hi >> >> I've been considering how to optimize map data structures for a tile >> based Python game. However, since I'm a Python newbie I lack >> experience with Pythons 'exotic' data types like lists and tuples, and >> thus I'm unsure whether such types could solve my problem. >> >> My basic thought is this: If my world map consists of 80% water and >> 20% land, then why reserve full data-structures for all the water >> tiles? >> >> I'm looking for a way to do the following: >> >> My World Map object should likely be a standard (x,y) array of Tiles >> (unless there's a better way?) >> Each Tile has a boolean/one-bit value: 0 or False for Water, 1 or True >> for Land. > >A better way is to have the class hierarchy like > >class Tile(object): > def __init__(self, ...): > # data that any Tile can contain > self.armies = ... > ... > >class WaterTile(Tile): > pass > >class LandTile(Tile): > def __init__(self, ...): > Tile.__init__(self, ...) > # data specific to land tiles > self.building = ... I think you are confusing two separate concepts here: the concept of a terrain type, and the concept of a location. A terrain type is something like "water", or "hill", or perhaps "hill with coal resource". You can ask a terrain type questions like "how many movement points does it costto move onto / off of a square of this terrain type?" A location is something like "grid reference (x=20, y=32) on the map". You can ask a location things like "what armies are on this location?", or "return a reference to the location to the north of this one". -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: zen19725 at zen dot co dot uk) From indigo at bitglue.com Tue Jun 29 13:47:04 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 29 Jun 2004 13:47:04 -0400 Subject: embedded python? In-Reply-To: References: Message-ID: <20040629174704.GC6091@unununium.org> If you prototype in Python and find the performance to be inadaquate, a good option might be Pyrex . On Tue, Jun 29, 2004 at 03:20:45PM +0000, Alexander May wrote: > Hi, > > I love Python! I've been using it for a couple of years now and have found > it to be a highly productive language. I evangelize it to my developer > friends and am probably responsible for the sale of at least 10 Alex > Martelli books. I am now in the fortunate position of being able to use > Python for a large project, and as such I have a question. > > We are developing a distributed application running on approximately six > thousand nodes with somewhat limited hardware resources. Our hardware > target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected > specific hardware yet; the hardware target is what we are trying to fit into > based on price constraints. Each device needs to be able to handle about 2 > kbs (yes kilo, not mega) worth of network traffic. > > ... > > In short, is embedding python realistic? > > Thoughts and comments are greatly appreciated! > > Thanks, > Alex From rzantow at ntelos.net Wed Jun 2 13:47:15 2004 From: rzantow at ntelos.net (rzed) Date: Wed, 02 Jun 2004 17:47:15 GMT Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> <3ngrb0le5g1l08li3rmbl3258i5e0pt731@4ax.com> Message-ID: Peter Hansen wrote in news:k8SdnetrrZQBkCPdRVn-hQ at powergate.ca: > rzed wrote: > >> This thread reminds me of my favorite highly-insecure >> encryption method. It does give a moment's pause to those >> intent on decoding such things, and works far better with >> longer messages than short, but it can bring a smile at least, >> and will completely fool a child of six for several hours. >> Here's an example of some encoded text: >> >> *[ >> Thgi snia lpn itxetht iw tpyrcedtp yrcn ednasdn ei rfruoy >> ezamaye. Ko nse ri uqer dn alair et amlautxet sedo. Ce ddnas >> edoc nehto (1853, 1927), bmargo rpemase ($315.23) hty lfeht >> noe-docedot reikc, irteltti lasi ta h thguoh tlaffuts la utxetn >> on reh tod. Nas tnuo marallo dset adhtiws kro wtimrof detpyrc >> neronial, pni daerebna ct ire. Doced laut canatuo hti >> wnevede/tpyrced ebyl idae rn actxe tsiht! >> ]* > > And, perhaps most remarkably for an encryption algorithm, it > happens to have the exact same letter-distribution frequency > as regular English! ;-) > > -Peter > Ah yes, another feature! Although, if the message is written in French, for instance, the distributions would dynamically adjust to compensate. -- rzed From agriff at tin.it Tue Jun 29 02:20:31 2004 From: agriff at tin.it (Andrea Griffini) Date: Tue, 29 Jun 2004 06:20:31 GMT Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <9v02e0hacphbvlevb127g33e06uudvoqmc@4ax.com> On Mon, 28 Jun 2004 17:37:23 -0300, alejandro david weil wrote: >It seems that no one has read my last post :-) Newsfeeding isn't synchronous by itself. News reading is even less deterministic :-) ... >And, another improvment is add the 's' to the >slen array :-) and..: Original version 1.640 My version 0.782 Improved with slen[] 0.687 What however I find depressing is thinking that in so many places the python runtime is wasting time looking for something I'd never do (like replacing "len" or "str"). And for a function like the one the OP posted looks like we're talking about more than 50% of the time being spent doing those pointless searches. It's IMO true that python is "fast enough" for most situations... but ... what if I get sued from the association for the rights of CPUs ? :-) I didn't check python sources, is there a timestamping for namespaces making it possible to cache lookups ? Was this tried and didn't pay off ? Andrea PS: Sorry if all this is hyper-naive... From squirrel at WPI.EDU Mon Jun 28 14:31:32 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 14:31:32 -0400 Subject: what editor do you use? In-Reply-To: References: Message-ID: On 28 Jun 2004, Heather Coppersmith wrote: > At the risk of starting/entering a holy war, emacs has a > rectangular selection mode. > > Perhaps the best test of editors is how productive/useful the help > system is. ;-) Part of the reason I first started using JOE was because of its simple help interface: its entire command set is summed up in a few well-organized help pages that sit at the top of your screen. EMACS's info-page-within-a-buffer interface is quite confusing for new users. (Though admittedly, you have to dig through the options menu to find rectangle selection.) Perhaps a good way for a newbie to learn EMACS is to start with JOE's EMACS mode :P From __peter__ at web.de Fri Jun 18 12:38:01 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jun 2004 18:38:01 +0200 Subject: Subclassing array.array References: Message-ID: Gus Tabares wrote: > I'm trying to subclass array.array but having problems with a default > parameter in the init constructor. Example: > > import array > > class TestClass(array.array): > def __init__(self, array_type = "B"): > array.array(array_type) > > >>>> temp = TestClass() > Traceback (most recent call last): > File "", line 1, in ? > temp = TestClass() > TypeError: array() takes at least 1 argument (0 given) > > I think there is something that I'm not understanding here. Any help > is appreciated. Seems like the argument check happens in __new__(). Try overriding that instead: >>> class Array(array.array): ... def __new__(cls, tc="B"): ... return array.array.__new__(cls, tc) ... >>> a = Array() >>> a array('B') >>> type(a) >>> Peter From tjreedy at udel.edu Tue Jun 8 09:52:23 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 09:52:23 -0400 Subject: Callbacks to generators References: Message-ID: "Terry Reedy" wrote in message news:ca49lu$r31$1 at sea.gmane.org... > #select one on following depending on Python version > > def on_token(): # modified traditional call_back > token = > return > > def on_token_gen(): # generator version for 2.2+ > while 1: > token = > yield > on_token = on_token_gen().next > > process(text, on_token) > > where process puts token in token_stash before calling on_token() If doing lots of callbacks, repeating anything like the above for each would get pretty tedious. So after getting the pattern correct, if the above does indeed work, I might try to factor out the common portion and write a callback factory function that inserts the variable code into the version-appropriate template, compiles it, and returns the version-apprieate callback. Terry J. Reedy From winexpert at hotmail.com Thu Jun 17 13:47:04 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 17 Jun 2004 17:47:04 +0000 Subject: [python] using try: finally: except Message-ID: In referring to my copy of the python bible, it tells me I can't use all three items 'try' except and finally. I can use the t/f or t/e combinations though What combination can i use if i want to catch the exception and still have a finally block? This is a fictional example of what I want.... try: x = 'hello' except Exception, e: print "oops" finally: y = 'world' print x," ", y So I surmise one way to guarantee this does what I need would be to do this: try: x = 'hello' except Exception, e: print "oops" y = 'world' print x," ", y Wouldn't that guarantee y and the print gets executed no matter what? My exception catches miscellaneous errors and then processing continues.... I suspect that wouldn't hold for a complex case where the action in the try block causes a fatal error of some sort.... David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From fumanchu at amor.org Sun Jun 6 16:03:58 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 6 Jun 2004 13:03:58 -0700 Subject: Problem with Python xrange Message-ID: Christian Neumann wrote: > I use Python 2.3.4 (final) and i think there is a bug > in the built-in function xrange(). > > An example is: > > x = xrange(2, 11, 2) ## [2, 4, 6, 8, 10] > > I get an TypeError if i use it with SliceType: > > x[1:4] ## It should be return an xrange object with length 3 > > Here is the error message: > > "TypeError: sequence index must be integer". Hm. I never noticed this either: >>> x = xrange(2, 11, 2) >>> x xrange(2, 12, 2) But back to your question. Anytime you use the word "should" in a bug report, you might guess it's really a feature request, not a bug. ;) Simply put, the "xrange type" doesn't support slicing like that. From the docs: http://docs.python.org/lib/typesseq.html "Xrange objects are similar to buffers in that there is no specific syntax to create them, but they are created using the xrange() function. They don't support slicing, concatenation or repetition, and using in, not in, min() or max() on them is inefficient." Robert Brewer MIS Amor Ministries fumanchu at amor.org From eppstein at ics.uci.edu Wed Jun 2 23:44:45 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 02 Jun 2004 20:44:45 -0700 Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: In article , Matt wrote: > Rusty Shackleford wrote: > > > All help is welcome. > > For quicksort, you should see ((n log(n))/runtime(n)) approach some > constant as you increase n. Well, except that he's not using random pivots. For the quicksort code he listed, if the input is already sorted, the behavior should be Theta(n^2). -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From me at privacy.net Wed Jun 2 12:18:32 2004 From: me at privacy.net (Duncan Booth) Date: 2 Jun 2004 16:18:32 GMT Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: Rusty Shackleford wrote in news:slrncbrudt.995.rs at frank.overlook.homelinux.net: > Here's my clumsy attempt to implement this: > > def qsort(ll): > try: > global n > n += len(ll) > print "adding %d to %d." % (len(ll), n) > print "incrementing up n to %d." % n > except: > pass > if len(ll) == 0: > return [] > p = ll[0] > left = [x for x in ll if x < p] > mid = [x for x in ll if x == p] > right = [x for x in ll if x > p] > return qsort(left) + mid + qsort(right) > > I'm not getting the results I hoped for. I expected that after the > program is finished, I would get results near > > len(ll) * math.log(len(ll), 2) > > since the big O for quicksort is nlogn for all but the worst case. You don't say what sort of objects you are passing in the list ll. Nor do you say how large a value of 'n' you tried. Nor have you said how you ensured that you weren't hitting the worst case performance. Python may not be the best language to demonstrate this sort of effect. Two things affect sorting speed in most languages: the number of comparisons, and the number of times you copy data items, but other factors can come into play when they are slow compared to the comparisons and moves. It may well be that here your comparisons are comparatively fast (especially if you just used integers as the input data), and the time is being swamped by the function call overhead and creating all those intermediate lists. In that case you may just need to increase the length of the list. A lot. Most quicksort implementations sort the data in-place. You are creating new lists for left, mid, right, and then again creating new lists by concatenating the results of your recursive calls. Both of these involve memory allocation, and the lists may need to be moved around in memory as they grow. All of this complicates the order calculation. Also, remember that if your lists are too long you are likely to start swapping virtual memory, so all your times go out the window at that point. Not to mention garbage collection. If you want to get a result that matches your expectations, then I think you would be best to operate on the data inplace, and probably also get rid of the recursion. From peufeu at free.fr Wed Jun 23 10:21:17 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Wed, 23 Jun 2004 16:21:17 +0200 Subject: String concatenation References: Message-ID: Let's try this : def test_concat(): s = '' for i in xrange( test_len ): s += str( i ) return s def test_join(): s = [] for i in xrange( test_len ): s.append( str( i )) return ''.join(s) def test_join2(): return ''.join( map( str, range( test_len ) )) Results, with and without psyco : test_len = 1000 String concatenation (normal) 4.85290050507 ms. [] append + join (normal) 4.27646517754 ms. map + join (normal) 2.37970948219 ms. String concatenation (psyco) 2.0838675499 ms. [] append + join (psyco) 2.29129695892 ms. map + join (psyco) 2.21130692959 ms. test_len = 5000 String concatenation (normal) 40.3251230717 ms. [] append + join (normal) 23.3911275864 ms. map + join (normal) 13.844203949 ms. String concatenation (psyco) 9.65108215809 ms. [] append + join (psyco) 13.0564379692 ms. map + join (psyco) 13.342962265 ms. test_len = 10000 String concatenation (normal) 163.02690506 ms. [] append + join (normal) 47.6168513298 ms. map + join (normal) 28.5276055336 ms. String concatenation (psyco) 19.6494650841 ms. [] append + join (psyco) 26.637775898 ms. map + join (psyco) 26.7823898792 ms. test_len = 20000 String concatenation (normal) 4556.57429695 ms. [] append + join (normal) 92.0199871063 ms. map + join (normal) 56.7145824432 ms. String concatenation (psyco) 42.247030735 ms. [] append + join (psyco) 58.3201909065 ms. map + join (psyco) 53.8239884377 ms. Conclusion : - join is faster but worth the annoyance only if you join 1000s of strings - map is useful - psyco makes join useless if you can use it (depends on which web framework you use) - python is really pretty fast even without psyco (it runs about one mips !) Note : Did I mention psyco has a special optimization for string concatenation ? From peufeu at free.fr Thu Jun 24 02:33:47 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Thu, 24 Jun 2004 08:33:47 +0200 Subject: mysql vs sqlite vs hsql References: Message-ID: Level 1: - have you optimized your database design ? - have you cleaned your tables ? OPTIMIZE TABLE blah; Level 2: - Send several inserts per query (you save on IPC time) - Use block inserts (inserts many rows at a time) => much much faster Read the mysql dox Subsidiary: What's this doing on the python mailing list ? On 23 Jun 2004 23:02:23 -0700, stan k. wrote: > First of all i'm on a win32 platform using java. I also have mysql > installed. My question isabout benchmarks and multiple inserts & > selects > SQLITE: http://www.sqlite.org/ > HSQL: http://hsqldb.sourceforge.net > I current have a mysql database of approx. 80mb. > Each day I Insert approx .5mb of new records into this table, > and I might also run mutiple Update, Delete, and Select queries as > well. > I'm trying to get an idea of how fast a sql database engine will run > given that is is inside of the JVM. I know it's going to be slower > than a db engine written in C and that's a trade off for being > portable to different operating systems. > What I want to know is how much of a trade off though - I don't want > to have to wait 10 mins or deal with screen freezing... Right > now on a windows platform using mysql things move really fast. > Can anyone give me an idea of the time delay needed to do these > Inserts in HSQL (ie: how much does the jvm slow things down).. > Thanks in advance -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From luis_ at iname.com Tue Jun 29 12:19:15 2004 From: luis_ at iname.com (Luis P. Mendes) Date: Tue, 29 Jun 2004 17:19:15 +0100 Subject: creating graphs from lists Message-ID: I'm developing a program in Python, with no gui, and now I've reached a point where I would need to plot list of elements on a graph. How can I do it? preferably in a simple way? Luis From secun at yahoo.com Mon Jun 7 15:18:38 2004 From: secun at yahoo.com (ChrisH) Date: Mon, 07 Jun 2004 19:18:38 GMT Subject: ideas Python / Network Admin References: Message-ID: Most of my python admin scripts focus around Windows. Typically they involve - group management - searching the domain for different files or registry entries - modifying said files or registry entries In article , norm at norm.com says... > I was wondering if you would give me some examples (not code, but general > ideas) of what you are using Python for in Network Administration / Security > ? > > Thanks > Norm > > > From jjl at pobox.com Mon Jun 28 10:44:10 2004 From: jjl at pobox.com (John J. Lee) Date: 28 Jun 2004 15:44:10 +0100 Subject: html POST in python References: Message-ID: "Mark Light" writes: > Hi I am trying to "post" a file to a webpage and save the output as a > file. I have looked at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 > > which seems to have several suggestions - my problem is my lack of > knowledge of html forms. > > The active part of the webpage form in question is below - how would I > feed this information into one of the python scripts from the cookbook > examples. Also would I need to do something about handling the result? > > I have a plain text file in a location say "c:\temp\file.cif" > Try ClientForm (http://wwwsearch.sf.net/ClientForm). Untested: import urllib2, StringIO import ClientForm url = 'http://blah.com/wherever/your/form/page/lives.html' r = urllib2.urlopen('http://blah.com/wherever/your/form/page/lives.html') forms = ClientForm.ParseResponse(r) r.close() form = forms[0] filename = 'c:\temp\file.cif' f = open(filename) form.add_file(f, 'application/octet-stream', filename) r2 = urllib2.urlopen(form.click()) print r2.info() print "********************************" print r2.read() r.close() John From kenneth.m.mcdonald at sbcglobal.net Tue Jun 1 20:22:46 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 02 Jun 2004 00:22:46 GMT Subject: Any Python modules for manipulating JFIF file contents? Message-ID: Warning: this post may display my utter ignorance of image file format facts. As part of a photo album program I'm working on, I'd like to be able to work with the metadata in JPEG files, which I understand are really JFIF files holding jpg data. Do any Python modules permit me to do this? I looked at PIL, but it seemed to operatre at a higher level, i.e. hiding the file-level implementation details. At the least I'd like to be able to : 1) Extract the metadata (comments, thumbnails, etc) 2) Extract the raw JPEG data (since I want to experiment with combining multiple images into a single 'album' file using gdbm file.) Writing would be nice, but is not necessary. Failing a Python module, can anyone suggest the best library to look at to wrap in a module? Thanks, Ken McDonald From claudio.grondi at freenet.de Wed Jun 9 20:00:16 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 10 Jun 2004 00:00:16 -0000 Subject: Python Scripting in Windows MSIE 6.0 Message-ID: <2ipfiaFphmh5U2@uni-berlin.de> I wonder why the subject (Python scripting within HTML) is not occuring in any past postings - do I miss something very obvious? I try to run Pythons scripting in Windows MSIE 6.0 in the section, but it doesn't work at all. \Python23\Lib\site-packages\win32comext\axscript\client\pyscript_rexec.py runs ok, registry entries seems also be ok. I have the latest Python 2.3.4 installed. What do I wrong? Runs anyone of you (inspite of the security concerns) successfully Python as scripting language in Windows MSIE 6.0 HTML pages using it like JavaScript or VBScript ? Thank you in advance for any help. Claudio From zathras at thwackety.com Fri Jun 4 20:29:18 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 5 Jun 2004 01:29:18 +0100 (BST) Subject: Why did no one invent Python before? In-Reply-To: <6ee58e07.0406041003.25e359fc@posting.google.com> Message-ID: On 4 Jun 2004, Lothar Scholz wrote: > Michael Sparks wrote... > > At that point, someone might come along and say "I can't believe how much > > more productive I am with [random flippant examples] ... > That already happened: the language is called Eiffel. > > Checking all pre- and postconditions and invariants on each call was > terrible slow when i started my project with a PIV 400 MHz. It was > mostly impossible to use on normal size data sets. Now i use a PIV > 2800 and give away my product (http://www.ruby-ide.com :-) with all > runtime checks enabled. This makes my programming style much much > better. Never suggested that the specific examples weren't possible today - in a way, you've demonstrated the point I was trying to make. After all, Eiffel was around 15 years ago as well, but the aspects you mention weren't practical for realtime, but as you demonstrate it is possible now :-) On the flipside though, I'm not aware of a language that does the other example I suggested as a "realtime" language construct ;-) Michael. From irmen at -nospam-remove-this-xs4all.nl Thu Jun 24 17:09:21 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 24 Jun 2004 23:09:21 +0200 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: <40db4300$0$48959$e4fe514c@news.xs4all.nl> Tim Golden wrote: [...] > s.start () > while 1: > try: > try: > pass > except KeyboardInterrupt: > break > finally: > s.stop () That's not a very good way of doing that. This will eat 100% CPU time, it's a busy wait loop... You should use time.sleep or something else to avoid busy waiting. But since you used the 'regular' Scheduler class from Kronos, it will loop inside the s.start() by itself ... ;-) --Irmen From wweston at att.net Tue Jun 15 12:32:12 2004 From: wweston at att.net (wes weston) Date: Tue, 15 Jun 2004 16:32:12 GMT Subject: Help with parsing web page In-Reply-To: References: Message-ID: RiGGa wrote: > Hi, > > I want to parse a web page in Python and have it write certain values out to > a mysql database. I really dont know where to start with parsing the html > code ( I can work out the database part ). I have had a look at htmllib > but I need more info. Can anyone point me in the right direction , a > tutorial or something would be great. > > Many thanks > > RiGga > RiGga, If you want something, hopefully, not too simple. Frequently, you can strip out the html and the resulting list will have a label followed by the piece of data you want to save. Do you need mysql code? wes def RemoveLessThanGreaterThanSectionsTokenize( s ): state = 0 str = "" list = [] for ch in s: #grabbing good chars state if state == 0: # s always starts with '<' if ch == '<': state = 1 if len(str) > 0: list.append(str) str = "" else: str += ch #dumping bad chars state elif state == 1: # looking for '>' if ch == '>': state = 0 return list From brian at sweetapp.com Fri Jun 4 16:15:21 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 04 Jun 2004 22:15:21 +0200 Subject: ANN: Vancouver Python Workshop - Speaker incentives In-Reply-To: <40C0C152.2060603@sweetapp.com> References: <40AD0CD4.1090804@sweetapp.com> <40C0C152.2060603@sweetapp.com> Message-ID: <40C0D859.1030208@sweetapp.com> What's new? =========== Thanks to the generosity of our hosts and sponsors, the first five people to submit talks will receive a free book package when they attend the conference. The package will consist of: 1. Andy McKay's "The Definitive Guide to Plone" (1) 2. Charles F. Goldfarb and Paul Prescod's the "XML Handbook, Fifth Edition" 3. Mark Lutz and David Ascher's "Learning Python, 2nd Edition" They will also receive a free license for Komodo, ActiveState's IDE for open source languages. To submit a talk, see: http://www.vanpyz.org/conference/registration/submissions.html For general conference information, see: http://www.vanpyz.org/conference The deadline for talk submission is June 15th. About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (2). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Talk submissions: until June 15th Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) If this book is not available at the time of the conference, it will be shipped to the recipient (2) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From bill.ramsay at clear.net.nz Thu Jun 3 07:15:18 2004 From: bill.ramsay at clear.net.nz (bill ramsay) Date: Thu, 03 Jun 2004 23:15:18 +1200 Subject: two silly questions References: Message-ID: On Thu, 3 Jun 2004 09:25:20 +0100, Tim Golden wrote: >| I have written a program that polls an email account, then pulls down >| the email >| >| I am using win2k. >| >| the two questions are: >| >| 1. when i want the program to run in a loop, ie. poll the pop3 >| account every 60 seconds, it runs the first time, then it goes into >| 'not responding mode' thereafter, sometimes. Any thoughts? I was >| using sleep(60) but it just hangs, as i said before, it does not >| always do that either! > >We really could do with a code fragment here. For example, >the following (entirely artificial) example runs fine in >the Python interpreter on my win2k machine. (I don't use >the PythonWin or any other Python shell): > > >import time >while 1: > print "Still waiting..." > time.sleep (10) > thanks for getting back to me I had two versions of python on my machine, it would seem that this was causing the difficulty a la running in a windows frame, if that is what you call it. remove the earlier version and it is ok. likewise the issue with the sleep problem kind regards bill > >I realise that your program is more complex than this, but >I wanted to illustrate that (a) time.sleep works as expected >on Win2K and that (b) some code examples could help. > >| 2. I wish to use this program at work, I took in an earlier version >| yesterday that just wrote the data to a text file, I wanted to make >| sure the polling thing worked. on microsoft exchange [i know that it >| should, but you never know!!] and it does . When i was there, i >| managed to get the code to run just by double clicking on the code >| ICON, seem to remember doing something with 'open with' can't seem to >| do it here at home. >| >| Both systems run win2k. did i do something sublimilally without >| realising it? what did i do i cannot remember, i have tried opening >| with etc. when i do this all get is a burst of the 'black windows >| box' just in the same way as putting in 'cmd' on the run thing, > >Have a look at the Python FAQ for Windows: > >http://www.mirror.ac.uk/sites/ftp.python.org/pub/www.python.org/doc/faq/wind >ows.html > >which I think answers your question. If not, then post again and see if >someone >can't help you out. > >TJG > > >________________________________________________________________________ >This e-mail has been scanned for all viruses by Star Internet. The >service is powered by MessageLabs. For more information on a proactive >anti-virus service working around the clock, around the globe, visit: >http://www.star.net.uk >________________________________________________________________________ From michael.anckaert at pi.be Mon Jun 28 11:47:34 2004 From: michael.anckaert at pi.be (Michael Anckaert) Date: Mon, 28 Jun 2004 17:47:34 +0200 Subject: what editor do you use? In-Reply-To: <40e0241e_2@newsfeed.slurp.net> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <40e0241e_2@newsfeed.slurp.net> Message-ID: Steven Rumbalski wrote: > Michael Anckaert wrote: > > >>A friend of mine uses emacs and we held a 'speedcontest', we had >>to edit a file with our editors and write some code. Me and vim were >>about 50% faster than him and emacs. >>But I don't want to start any vim vs. emacs flamewar :-) >> > > I suspect you would be 50% faster even if you both used notepad. This > comparison is meaningless without a baseline comparison in an unfamiliar > editor. Perhaps you are simply a faster typist. Perhaps code flows more > quickly from your brain. Perhaps you were more familiar with the file to > be edited and the problem domain. We cannot know the reason that you > performed this particular test more quickly. > > I too use vim. > I wasn't more familiar with that file, we just did some basic editing. Removing lines, adding words, navigating to a certain point, etc. But it is true that I'm a better typist than him ;-) -- Met vriendelijke groeten, Kind regards, Michael Anckaert michael.anckaert at pi.be From theller at python.net Wed Jun 23 14:41:01 2004 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jun 2004 20:41:01 +0200 Subject: Can anyone confirm this modulefinder bug? References: Message-ID: <8yeet8w2.fsf@python.net> Thomas Heller writes: > "Roger Binns" writes: > >> - Create foo.py >> >> # -*- coding: mbcs -*- >> "string" >> var1="1.2.3.4" >> var2=0x123345 >> >> - Do this at a python prompt >> >>> > > import modulefinder >>> > > m=modulefinder.ModuleFinder() >>> > > m.run_script("foo.py") >> >> You then get a traceback with a MemoryError (sorry I can't paste >> the traceback due to this being via display protocol that doesn't >> support the clipboard). >> >> I get this on Linux for sure and believe it is also being seen on Mac. >> The issue does not occur on Windows. > > Yes, I can confirm this (Python 2.3+, linux x86). > The problem appears to be this: > >>>> compile("# -*- coding: mbcs -*-", "", "exec") > Traceback (most recent call last): > File "", line 1, in ? > MemoryError >>>> For Windows, it's possible to also trigger it: >>> compile("# -*- encoding: abc -*-", "", "exec") Traceback (most recent call last): File "", line 1, in ? MemoryError >>> Who files the bug? Thomas From skip at pobox.com Thu Jun 24 12:53:57 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jun 2004 11:53:57 -0500 Subject: python-list to news gateway down? In-Reply-To: References: Message-ID: <16603.1829.531599.73881@montanaro.dyndns.org> Brad> I have not seen any new posts in gmane.comp.python.general since Brad> 6/18/2004.... Does anyone know if its a gmane problem, or a Brad> general news to python-list problem? It's probably more a mail.python.org problem. There are several of us working on the problem, but our time is limited. Skip From squirrel at WPI.EDU Fri Jun 25 15:33:42 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Fri, 25 Jun 2004 15:33:42 -0400 Subject: Parameterized Functions without Classes In-Reply-To: References: <2k35g4F14l1o0U1@uni-berlin.de> Message-ID: On Fri, 25 Jun 2004, Christian Tismer wrote: > Lambdas were not the topic, since they are a deprecated > feature, but sure it works. Since when are lambdas deprecated? And if so, why? IMHO, the best way to parameterize functions is with 2.4's proposed partial() function: def converter(factor,val): return val*factor inchtocm=partial(converter,2.54) cmtoinch=partial(converter,1/2.54) where a handy pre-2.4 definition of partial is: def partial(func,*args,**kw): return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items())) From pekka.niiranen at wlanmail.com Thu Jun 17 08:33:12 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Thu, 17 Jun 2004 12:33:12 GMT Subject: Unnatural behaviour in Pickling Message-ID: Hi there, why must file be opened in "r" -mode, before loading works with Pickling? This forces me to close the file between pickle.dump and pickle.load. :( Example: -----************------ a = {'pekka': 1, 'jussi': 2} fh = open('c:\temp\log.log', "wb") pickle.dump(a,fh) fh.close() **** now: fh = open('c:\temp\log.log', "wb") b = pickle.load(fh) **** gives error: IOError: (0, 'Error') **** however: fh = open('c:\temp\loglog', "rb") b = pickle.load(fh) **** works. -pekka- From lbates at swamisoft.com Fri Jun 11 14:17:03 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 13:17:03 -0500 Subject: class.print method illegal Message-ID: I just ran into something I've not seen before: class foo: def print(self): ...do something... creates a syntax error. Why can't a class have a method called "print"? Doesn't seem to be any way it could be confused with the reserved print statement, or am I missing something? Regards, Larry Bates From jcarlson at uci.edu Thu Jun 10 02:08:16 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 09 Jun 2004 23:08:16 -0700 Subject: Passing file descriptors In-Reply-To: References: Message-ID: I forgot to post the script... - Josiah -----clip here----- #!/usr/pd/bin/python # # fdpass.py # # Example of passing an open filedescriptor with Python. Will only work # on UNIX dialects that support the I_SENDFD and I_RECVFD ioctl() calls. # import fcntl, os, sys, struct, socket # # fork() off! # (pRead, pWrite) = os.pipe() pid = os.fork() if pid != 0: # We're in the parent. # Open a file for passing along to child. Use own source code, # which is guaranteed to exist. :) fileObj = open('./fdpass.py', 'r') # ioctl() will only pass raw filedescriptors. Find fd of fileObj. fd = fileObj.fileno() # Send to the child using ioctl(). try: retval = fcntl.ioctl(pWrite, 1, fd) # Should probably check retval rather than just printing it. :) print "Parent ioctl() returned %d" % retval except Exception, e: print e # Wait for child to terminate, then exit. os.waitpid(pid, 0) sys.exit(0) else: import time time.sleep(1) # We're in the child. # Create a string representing the strrecvfd structure that ioctl() # will return. s = struct.pack('iii', 0, 0, 0) # Receive filedescriptor. Will block until descriptor is sent. ret = fcntl.ioctl(pRead, 1, s) # Unpack the strrecvfd-structure that ioctl() should return. # fd is the filedescriptor, uid/gid the user/group id of the # sending stream. (fd, uid, gid) = struct.unpack('iii', ret) # Reopen the filedescriptor as a Python File-object. fileObj = os.fdopen(fd, 'r') # Example usage: Read file, print the first line. lines = fileObj.readlines() print lines[0], sys.exit(0) From jimka at rdrop.com Tue Jun 8 02:08:04 2004 From: jimka at rdrop.com (Jim Newton) Date: Tue, 08 Jun 2004 08:08:04 +0200 Subject: how to use __str__ and __repr__? In-Reply-To: <40C4FF56.F81105B@alcyone.com> References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9hjFnvcsbU1@uni-berlin.de> <40C4FF56.F81105B@alcyone.com> Message-ID: <2il6llFo4tkpU1@uni-berlin.de> if that is the case then why does the following fail class another: pass another.__str__() I would think that would return a string such as "<__main__.another instance at 0x8132b64>" but it does not seem to. Erik Max Francis wrote: > Jim Newton wrote: > > >>thanks for responding, >>i was expecting class().__str__() >>to evaluate to the string "<__main__.another instance at 0x8132b64>" >>because that what print does with class(). >>but alas it does not. >> >>why does print class() not give me the same error as >>class().__str__()? >>that's what i do not understand. > > > In the example you gave, your class is derived from list, so it uses > list.__str__. It's doing exactly what an object-oriented system should > do; defer to the base class. Why do you think that's wrong? > From winexpert at hotmail.com Fri Jun 4 10:56:49 2004 From: winexpert at hotmail.com (David Stockwell) Date: Fri, 04 Jun 2004 14:56:49 +0000 Subject: I got the mail portion working [python] Message-ID: Thanks for the help in breaking the problem down into manageable pieces This is the code snippet I ended up using: (I'm decoding excel formatted files) the file is an email i created with pine that has an excel file in it and also a csv file in it, both as MIME attachments. I'm only keeping the excel data, but fwiw I also found 3 other MIME types in the email: ~/mymail/test] python test.py from[ Jerome plugh ] reply to[ Jerome plugh ] Id[ None ] multipart[>] partition type[multipart/mixed] Partition #[ 1 ] partition Name[ None ] partition type[text/plain] Partition #[ 2 ] partition Name[ None ] partition type[application/vnd.ms-excel] Partition #[ 3 ] partition Name[sample.xls ] partition type[text/tab-separated-values] Partition #[ 4 ] partition Name[ sample.tsv ] total part count 4 ----- payload = {} text = open('/tmp/test/it').read() message = email.message_from_string(text) hdr = dict(message._headers) addressFrom = hdr["From"] addressReply = hdr.get("Reply-To", addressFrom) messageId = hdr.get("Message-Id") print "\tfrom[", addressFrom, "]\n\treply to[", addressReply, "]\n\tId[", messageId, "]" print "multipart[%s]" % message.is_multipart count = 0 for partition in message.walk(): pType = partition.get_type() print "partition type[%s]" % pType count += 1 print "\tPartition #[", count, "]" fName = partition.get_filename() print "\t\tpartition Name[", fName , "]" if pType == "application/vnd.ms-excel": part = partition.get_payload(decode=1) print "\t\tpart Info[", part, "]" payload[fName] = part print "total part count", count David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Looking to buy a house? Get informed with the Home Buying Guide from MSN House & Home. http://coldwellbanker.msn.com/ From jbperez808 at wahoo.com Mon Jun 14 07:57:37 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Mon, 14 Jun 2004 19:57:37 +0800 Subject: dropping into the debugger on an exception In-Reply-To: <40cc99ee@news.bezeqint.net> References: <2inqlrFp53m5U1@uni-berlin.de> <2j3cp3Ft3dpdU1@uni-berlin.de> <40cc99ee@news.bezeqint.net> Message-ID: <2j5i4bFsqcq0U1@uni-berlin.de> ziaran wrote: > Jon, I think rpdb does that, > http://rpdb.digitalpeers.com/ Excellent! From newsgroups at jhrothjr.com Wed Jun 9 06:53:30 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 9 Jun 2004 06:53:30 -0400 Subject: Constructor overloading References: Message-ID: <10cdr2fgc5ueo60@news.supernews.com> "Sergey Krushinsky" wrote in message news:mailman.746.1086771964.6949.python-list at python.org... > Hello all, > > Is there a common way to emulate constructor overloading in Python class? > > For instanse, I have 3 classes: > 1/ Polar - to hold polar coordinates; > 2/ Cartesian - to hold cartesian coordinates; > 3/ Coordinates3D, which holds synchronized instances of the both in > __p__ and __c__ fields respectively. > > I want to design Coordinates3D so that when instantiated with Polar > argument, self.__p__=argument passed to constructor, and self.__c__ is > calculated. When argument is Cartesian, self.__c__=argument, and > self.__p__ is calculated. Runtime type checking works, but maybe there > is a better way? Depends on what you think is "better." Checking the paramter types at run time is the clearest way of doing it. The only other way I know is to use a static method as a constructor, instantiate an instance of object(), change its class and initialize it to suit yourself. The biggest problem with that is that it's totally non-obvious unless your team does it a lot, and you've got decent naming conventions so you know what's happening. John Roth > > Thanks in advance, > Sergey > From nhodgson at bigpond.net.au Fri Jun 11 21:06:12 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 12 Jun 2004 01:06:12 GMT Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfihFq4aunU1@uni-berlin.de> Message-ID: <8Gsyc.5231$sj4.4584@news-server.bigpond.net.au> Claudio Grondi: > I have the latest Python 2.3.4 installed. > What do I wrong? > Runs anyone of you (inspite of the security concerns) successfully > Python as scripting language in Windows MSIE 6.0 HTML pages > using it like JavaScript or VBScript ? The Python Extensions for Windows supported use of client side Python in web pages for several years but this is now disabled because of security. You could try finding an older version of win32all or modifying the current version: I expect Mark Hammond has not deleted the code, just turned it off. http://sourceforge.net/projects/pywin32/ There is a mailing list for Win32 issues: http://mail.python.org/mailman/listinfo/python-win32 Neil From dmq at gain.com Sat Jun 12 09:36:46 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 12 Jun 2004 06:36:46 -0700 Subject: Doc error on super(cls,self) References: <95aa1afa.0406112004.5a74464a@posting.google.com> Message-ID: <1u0mc0tkfuor8gikiu5lg5lr0h6in7astb@4ax.com> On 11 Jun 2004 21:04:40 -0700, michele.simionato at poste.it (Michele Simionato) wrote: >David MacQuigg wrote in message news:... >> I think there is a documentation error in both the Library Reference >> section 2.1 and the Python 2.2 Quick Reference page 19. The >> explanation for this function is: >> >> super( type[, object-or-type]) >> Returns the superclass of type. > >Aha! Now I see why for a while in the past I thought 'super' was returning >the superclass: I had read the documentation! > >The sentence you report here is clearly WRONG and misleading, since 'super' >returns a 'super object' which is a descriptor acting more or less as a proxy >to the methods in the MRO. 'super' by no means is returning the superclass. >So please submit the documentation bug. If nobody has already done that, >I will volunteer to write a tutorial on 'super', since it is rather tricky >and terribly documented in the standard docs. I will submit the bug report. I think a tutorial would be very helpful. The only clear (but lengthy) explanation I have found is GvR's paper at http://python.org/2.2.3/descrintro.html#cooperation (see "Cooperative methods and super" pp.14-18 in the printed version) I've tried to condense this into a brief summary in my OOP chapter at http://ece.arizona.edu/~edatools/Python/PythonOOP.doc (see "Super Calls" on p.14-15). I could add your tutorial as an example or exercise, or link to your website, if you have a relatively permanent place. -- Dave From fishboy at spamspamspam.com Fri Jun 4 01:15:07 2004 From: fishboy at spamspamspam.com (fishboy) Date: Fri, 04 Jun 2004 05:15:07 GMT Subject: walking a MIME encoded multipart email [python] References: Message-ID: <3600c0t96ceeqcm04fspldp168u0adndg0@4ax.com> On Thu, 03 Jun 2004 18:31:54 +0000, "David Stockwell" wrote: >snippet [snippet] >I've wrote the above segment but haven't tried running it yet because I'm >unclear about the api for message. Ok, let's stop here. What?! Has Ernst Stavro Blofeld attached some doomsday device to your stack trace? You've got an interpreter, use it! Go man! Go! Anyway, I'll poke around a little for you. I put your post into a file named message.txt headers and all. $ python Python 2.3.3 (#1, Apr 30 2004, 08:54:23) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import email >>> m = email.message_from_file(file('message.txt')) >>> m.keys() ['Path', 'From', 'Newsgroups', 'Subject', 'Date', 'Organization', 'Lines', 'Message-ID', 'NNTP-Posting-Host', 'Mime-Version', 'Content-Type', 'X-Trace', 'X-Complaints-To', 'NNTP-Posting-Date', 'To', 'X-Originating-IP', 'X-Originating-Email', 'X-Sender', 'X-OriginalArrivalTime', 'X-Spam-Status', 'X-BeenThere', 'X-Mailman-Version', 'Precedence', 'List-Id', 'List-Unsubscribe', 'List-Archive', 'List-Post', 'List-Help', 'List-Subscribe', 'Xref'] >>> m['Date'] 'Thu, 03 Jun 2004 18:31:54 +0000' >>> m.get_content_type() 'text/plain' >>> s = m.get_payload() >>> print s snippet payload = {} try: message = email.message_from_string(message) messageHeader = dict(message._headers) [... etc...] >>> type(s) >>> for p in m.walk(): ... print p.get_content_type() ... text/plain >>> >>> dir(m) ['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__len__', '__module__', '__setitem__', '__str__', '_charset', '_default_type', '_get_params_preserve', '_headers', '_payload', '_unixfrom', 'add_header', 'add_payload', 'as_string', 'attach', 'del_param', 'epilogue', 'get', 'get_all', 'get_boundary', 'get_charset', 'get_charsets', 'get_content_charset', 'get_content_maintype', 'get_content_subtype', 'get_content_type', 'get_default_type', 'get_filename', 'get_main_type', 'get_param', 'get_params', 'get_payload', 'get_subtype', 'get_type', 'get_unixfrom', 'has_key', 'is_multipart', 'items', 'keys', 'preamble', 'replace_header', 'set_boundary', 'set_charset', 'set_default_type', 'set_param', 'set_payload', 'set_type', 'set_unixfrom', 'values', 'walk'] >>> etc.. etc... That should answer a few of your questions. Do not fear the stack trace, it is your friend. ><{{{*> From eric_brunel at despammed.com Tue Jun 22 06:12:06 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 22 Jun 2004 12:12:06 +0200 Subject: "RuntimeError: Calling Tcl from different appartment" References: Message-ID: Peter Saffrey wrote: > aahz at pythoncraft.com (Aahz) wrote in message news:... > >>In article , >>Peter Saffrey wrote: >> >>No clue why it used to work. Why do you need to call Tk from multiple >>threads? > > > I'm writing an MP3 jukebox (don't laugh, it's just for fun). One > thread controls the interface that shows the next few songs to be > played and allows you to add to the list. The other thread plays the > songs, removing them from the list in the process. To control this > with one thread, I'd have to have the interface thread constantly > listening for when the last song has finished so that it can remove it > from the list and play the next one. No you don't. There's one thing you can do in secondary threads wrt to Tkinter: posting events in Tkinter event queue via the event_generate method. Here is an example: --tkinterNThreads.py----------------------------------------- import threading, time from Tkinter import * root = Tk() def ping(): while 1: time.sleep(1) root.event_generate('<>', when='tail') v = BooleanVar() v.set(0) Checkbutton(root, variable=v, text='Ping!').pack(side=TOP) Button(root, text='Quit', command=root.quit).pack(side=TOP) def gotPing(event): v.set(not v.get()) root.bind('<>', gotPing) th = threading.Thread(target=ping) th.setDaemon(1) th.start() root.mainloop() ------------------------------------------------------------- The secondary thread make the check-button blink by generating custom <> events in Tkinter event queue. Note the option when='tail' in event_generate is mandatory: if you don't set it, there's a chance that the event is treated immediatly without switching threads. The code above works on Linux and Windows (there are other issues on Solaris, but I assume it won't be your target platform...) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From 0gk500b4gd0888 at cougar.noc.ucla.edu Thu Jun 17 03:40:08 2004 From: 0gk500b4gd0888 at cougar.noc.ucla.edu (0gk500b4gd0888 at cougar.noc.ucla.edu) Date: Thu, 17 Jun 2004 08:40:08 +0100 Subject: Document Message-ID: Important bill! -------------- next part -------------- A non-text attachment was scrubbed... Name: Bill.zip Type: application/octet-stream Size: 22404 bytes Desc: not available URL: From maney at pobox.com Fri Jun 25 22:02:59 2004 From: maney at pobox.com (Martin Maney) Date: Sat, 26 Jun 2004 02:02:59 +0000 (UTC) Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: Leif K-Brooks wrote: > Mediocre Person wrote: >> So, what pitfalls should I look out for in introducing Python to >> students who have had a year of Visual BASIC? > I was a Visual Basic programmer for a few months in 2002. It took me > almost a year to recover. It is vaguely object-oriented, but its > definition of objects are horribly warped; going to a genuine OO > language after VB is a complete nightmare. 'way late, as usual, but I can't resist pointing out that IME it's a complete nightmare going the other way - coming to a project in VB after having used C++ for some years (with some exposure to other, purer OO languages, chiefly Smalltalk). I let myself get talked into that once; now I know better. Actually, now I know better than to let myself be talked into doing time in C++. :-) -- During much of that epoch [the thirties and early forties], I gained my livelihood writing for the silver screen, an occupation which, like herding swine, makes the vocabulary pungent but contributes little to one's prose style. -- S J Perelman From jacek.generowicz at cern.ch Thu Jun 3 10:55:19 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 03 Jun 2004 16:55:19 +0200 Subject: Optimizing multiple dispatch References: Message-ID: Jeff Epler writes: > Avoding map() may help: > tuple([type(a) for a in args]) Nonononononooooo! :-) > You could write a small extension to perform this operation without all > the Python function calls. [... Pyrex ...] > 100000 loops, best of 3: 2.41 usec per loop [... List comprehension ...] > 10000 loops, best of 3: 25.3 usec per loop [... map ...] > 100000 loops, best of 3: 17 usec per loop (I'm pretty sure that should be 10**5 loops in the list comp case) Hmm, ok, the extension seems to be significantly faster. This surprises me, because everything that executes in "tuple(map(type,args))" is coded in C already, so I don't see where the gain is coming from. I've never got around to trying Pyrex ... and I won't be allowed to depend on it formally. Would it be feasible to use Pyrex to generate the extension source code and paste[*] that into my extension module? IOW, is there a run-time dependence on Pyrex? [*] Ugh, I shudder at the thought, putting the products of code generators into CVS really goes against my fundamental principles. From piedmontbiz at aol.com Sun Jun 13 17:16:58 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 13 Jun 2004 21:16:58 GMT Subject: using shelve module to create web databases....problems? Message-ID: <20040613171658.12072.00000928@mb-m19.aol.com> I am finishing up a simple survey for a web site. I am creating a server-side data base using the shelve module. I am a relative python newcomer. I began with anydbm, but found that shelve uses anydbm and pickle so it is a bit easier for me to do what I want. The database I am testing list 4 candidates for president. A web form ( I use javascript to validate the data before sending it on ) posts the users survey data to a server-side python program which simply entesr the data into the database. The user can then go to another page to see the cumulative results of the survey. This is generated by another python cgi program. This all works fine on my home system with Apache and Python 2.3(Win 2k) Question. Do I need to worry about contention for the single database file if more than one user is trying to post his/her vote? If so, should I write a routine which randomly waits a while then retries the write? How do I write the exceptions to control this? Allen From squirrel at WPI.EDU Mon Jun 28 14:40:41 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 14:40:41 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: On Mon, 28 Jun 2004, Lothar Scholz wrote: > Hello i want to write a commerical small tool that must access a MySQL > database but i can't afford the License Fee for the original MySQL > driver. In the Ruby world there exist a small but working pure ruby > library that can be used without buying a license or putting your > application under the GPL. > > Is there anything like this in the Python world ? Libraries licensed under the GPL can be used without GPLing the code that uses them - you only have to GPL any extensions you make to the library. Assuming that works for you, you can use (GPLed) mysql-python: http://sourceforge.net/projects/mysql-python/ From skip at pobox.com Wed Jun 9 11:16:59 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 9 Jun 2004 10:16:59 -0500 Subject: division bug? In-Reply-To: <964246.0406090655.7e190def@posting.google.com> References: <964246.0406090655.7e190def@posting.google.com> Message-ID: <16583.10731.859586.839991@montanaro.dyndns.org> Milan> a program: Milan> a=10 Milan> b=5 Milan> print a/b Milan> and its result: 0. If you run the program, you see always a sero Milan> (0), but 10/5 is 2. Who can help me? Works for me: % python Python 2.4a0 (#25, May 22 2004, 15:16:21) [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a=10 >>> b=5 >>> print a/b 2 I think you'll need to give more details (platform, version, actual interpreter output, etc) to get any more useful help. Skip From peter at engcorp.com Wed Jun 23 16:36:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 16:36:01 -0400 Subject: how to obtain its ip address ? In-Reply-To: <40d9c75d$0$26573$626a14ce@news.free.fr> References: <40d9c75d$0$26573$626a14ce@news.free.fr> Message-ID: marco wrote: > I'd search a lot ... but i had not found > how can i obtain my ip address (when i'm connected to the www) ?! You can probably search the archives for this list/newsgroup to find more complete answers (and hints about how else to solve it), but the short answer is "you can't". The longer answer is that (a) machines can have multiple addresses so you have to take that into account in the general case, (b) there is no portable way to do it (and you didn't specify what platform you are on), and (c) it's generally not necessary anyway, though there are a few valid usecases... you might even have one. On Windows you would have to parse the output of the "ipconfig" command using os.popen or something like that. On Linux the command is "ifconfig", but the output is totally different. Provide a little more info about your situation and needs and you might get a more useful answer. -Peter From arjun.babu at soc-soft.com Thu Jun 3 06:38:14 2004 From: arjun.babu at soc-soft.com (Arjun A.A. Babu) Date: Thu, 3 Jun 2004 16:08:14 +0530 Subject: instantiation inside __init__ Message-ID: Hi All, The following program became an endless loop. I have instantiated inside the constructor. Can somebody explain me why? class C: def __init__(a): print "initialized" myInstacne2 = C() myInstance1 = C() The information contained in this e-mail message and in any annexure is confidential to the recipient and may contain privileged information. If you are not the intended recipient, please notify the sender and delete the message along with any annexure. You should not disclose, copy or otherwise use the information contained in the message or any annexure. Any views expressed in this e-mail are those of the individual sender except where the sender specifically states them to be the views of SoCrates Software India Pvt Ltd., Bangalore. From lbates at swamisoft.com Thu Jun 3 19:12:20 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 18:12:20 -0500 Subject: simplify printing of a list References: <3064b51d.0406031408.1b676379@posting.google.com> Message-ID: How about: print ''.join(["%6d" % j for j in [0,1,2]]) or print reduce(lambda x,y: x+"%6d" % y, [0,1,2], '') or t=[sys.stdout.write("%6d" % j for j in [0,1,2]] (note: the t assignment is so the list comprehension results don't print) all work and are pythonic in nature. I didn't test, but I'll be the last one is the most efficient. HTH, Larry Bates Syscon, Inc. wrote in message news:3064b51d.0406031408.1b676379 at posting.google.com... > To print a list with a specified format one can write (for example) > > for j in [0,1,2]: > print "%6d"%j, > print > > The code > > print "%6d"%[0,1,2] > > currently produces a syntax error, but it would be convenient if it > had the same meaning as the loop above. > > One can write a function to print a list, for example > > def print_list(x,fmt_x="%6d"): > """ print a list on one line """ > for y in x: print fmt_x % y, > > print_list([0,1,2]) > > but it gets messy to print several lists on the same line. > > In Fortran 90/95 one can write > > print "(100i6)",(/0,1,2/) > > where the format (100i6) means that UP TO 100 integers are printed > using 6 columns. An alternative suggestion I have for Python is to > allow > > print "100%6d"%[0,1,2] > > with the same meaning. > > I realize that what I am asking for is just a convenience, but it is > one that I could use in almost every program I write. From lard at tardis.ed.ac.molar.uk Thu Jun 3 09:23:01 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Thu, 03 Jun 2004 14:23:01 +0100 Subject: printing something without a newline OR a space after it? Message-ID: <10bu9hm1e03cved@corp.supernews.com> Very very simple problem here, can't find out how to do it... I want to print something without a new line after it, so I can later output something right after it on the same line. If I do: print "stuff here", print "more" .. it doesn't output a newline, but it does output a space: stuff here, more .. whereas I want no newline and no space: stuff here,more How is this done? thanks alex From dkturner at telkomsa.net Thu Jun 10 04:22:36 2004 From: dkturner at telkomsa.net (David Turner) Date: 10 Jun 2004 01:22:36 -0700 Subject: Destructors and exceptions References: <5155aad2.0406090311.6a275231@posting.google.com> Message-ID: kveretennicov at yahoo.com (Konstantin Veretennicov) wrote in message news:<5155aad2.0406090311.6a275231 at posting.google.com>... > dkturner at telkomsa.net (David Turner) wrote in message news:... > > using (Font f1 = new Font("Arial", 10), f2 = new Font("Arial", 12)) { > // use f1 and f2... > } // compiler will call Dispose on f1 and f2 either on exit or on exception; > // not sure about order of disposal, but you can nest "using" anyway > > This saves you from trouble of coding try+finally+Dispose. > BTW, does anybody know whether MS borrowed or invented this construct? > It still leaves the clean-up onus in the wrong place. The "using" concept has been kicking around for a while. I think it's a natural evolution of Lisp's with-foo-do idiom. Regards David Turner From peter at engcorp.com Wed Jun 16 10:03:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 10:03:05 -0400 Subject: list to dict In-Reply-To: References: Message-ID: Bart Nessux wrote: > What is the easiest/fastest way to build a dictionary from a list? The > list contains 100,000 entries. A dictionary has key/value pairs. How do you want to map the elements of your list to this format? In pairs, or are you using them all as keys, or something else? -Peter From has.temp2 at virgin.net Tue Jun 22 04:23:27 2004 From: has.temp2 at virgin.net (has) Date: 22 Jun 2004 01:23:27 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> <69cbbef2.0406210114.439f4ee@posting.google.com> Message-ID: <69cbbef2.0406220023.d7242de@posting.google.com> Paramjit Oberoi wrote in message news:... > > - The advantage of separating the two is very designer-friendly markup > > and complete freedom in how you design and implement the logic. (i.e. > > easier maintainance) > > You are right: there are three pieces to be managed (1)application logic, > (2)presentation logic, and (3)markup. MY understanding of HTMLTemplate is > that it enforces the separation of markup and all logic (both presentation > and application), which is certainly very designer friendly. > > The problem is that: > > (1)presentation logic is often trivial, which means it is often not > separated from application logic. As with desktop application development, it's up to the developer to separate/not separate the View's Controller from the Model layer. Nobody's forcing them to combine the two. I think you're worrying unnecessarily - folk developing desktop apps seem to manage just fine. > (2)markup and presentation logic are often quite closely coupled (i.e. > significant changes to the markup often require changes to the > presentation logic), but they are in different places Having the HTML and code in different places isn't in itself a bad thing. There is coupling between the two, but it doesn't have to be as tight as it is in macro-style systems. > (and even worse, the > presentation logic may even be mixed with the application logic). Again, if the programmer wants to write spaghetti then that's their choice. Not my place to dictate/save them from themselves. > The second point above is why I don't understand your claim that the > separation of presentation logic and markup would be easier to maintain. I can work on the HTML using all my favourite standard HTML tools, and the code using all my favourite standard Python tools. I can deal with each half individually without having the other getting in my way and spoiling my view. I can hash around the HTML as much as I like with, at most, minimal breakage - the only stuff in the HTML to break is the name bindings that tie it to the Controller code, and those are quickly and easily replaced. The API is very small and simple. How I structure my code is not dictated by the structure of my template. The implementation can be as granular as you like, so should be easy to test and profile right down to the atomic level. I can hand the HTML half to one developer to take care of and the code half to another. > Ideally all three, application logic, presentation logic, and markup would > be separate, but I think it's more important to separate application logic > from presentation+markup than markup from application+presentation. DOM-style templating engines provide the three-way separation you describe. > But, my views are also colored by the fact that I've never dealt with > large and complicated templates. In that case it would probably be a good > idea to separate the template from presentation code just to keep the > complexity under control. You can find an example of complex use (~100-line template, ~200 LOC) in the appscript project on my site. See the appscript.htmldoc.Renderer module. And yes, the clear separation of code from markup really comes into its own. Mind you, I find it quite pleasant in simple use too even though the heavy decoupling tends to make it a little more verbose than equivalent TAL/Cheetah code. > >> Cheetah-like systems are much more flexible (and simple > >> substitution-only templates are very limiting). > > > > DOM-style templating systems aren't 'substitution-only', and can > > easily match or surpass macro-style systems for power and flexibility > > at a fraction of the size and complexity. > > By flexibility I meant flexibility in what you can do by modifying the > template alone (since presentation logic can be added to the template). > In the case of 'DOM-style' systems you may have to edit the template as > well as the presentation logic (which would mean modifying the > 'program', not just the template). You're making a false distinction here. The template and the presentation logic are as much a part of the "program" as the business layer they sit on top of. Editing the template markup is modifying the application. Editing the template logic is modifying the program. Editing the business logic is modifying the program too. DOM-style templating systems allow you to work on the first and/or second without touching the first, just as macro-style systems do. Now, if you believe that it's the templating system's job to impose and enforce a certain kind of architecture upon the developer - one that makes it impossible to mix presentation and business logic together - then you can certainly make that argument. The popularity of BDSM languages like Java would indicate there's plenty of folk around who like working within restrictive tools and environments. I come from the other school of thought - the one that says that tools should be small, simple, extensible and as free of built-in limitations as possible, and assumes the developer is smart enough to make their own informed decisions as to how they use them. The popularity of highly dynamic languages from Python and Perl right back to Lisp suggests there's also plenty of folk who prefer extremely flexible, malleable tools. But this is a different debate Anyway, if you want to compare DOM-style templating systems to something else, try a modern desktop GUI development system such as OS X's AppKit framework + Interface Builder. They're far closer conceptually to this type of system than to PHP et-al, which have their roots in command line macro pre-processors, and it might help you see where they're coming from a bit better. HTH has From chuck at smtl.co.uk Fri Jun 4 09:12:48 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Fri, 04 Jun 2004 14:12:48 +0100 Subject: python-list@python.org Message-ID: <200406041312.i54DCmeb021835@sevenofnine.smtl.co.uk> Has anyone got a simple python script that will parse a linux mbox and create a large file to view . I need to write a python program the grabs mail from a standard linux mail folder and processes it to file to eventually be transfered to a database. Im having problems at the moment can someone post a exmaple or no if a similar script exists to hack. Not to good with Python and I have'nt got alot of time to get to grips with writing my own. Cheers Chuck From maschio_77 at hotmail.com Fri Jun 25 10:32:04 2004 From: maschio_77 at hotmail.com (Federico) Date: Fri, 25 Jun 2004 16:32:04 +0200 Subject: static compile frozen file for i386 Message-ID: I need to put on a web server that run only static compiled for i386 binary files a python script that use PIL, so I used the freeze utility to have an executable file that works on my pc but doesn't work on the server... How can I have a static compiling for i386 ? hve I to edit the makefile generated by freeze? how? Thanks From selwyn at aotearoa.is.home.nz Mon Jun 28 02:35:05 2004 From: selwyn at aotearoa.is.home.nz (selwyn) Date: Mon, 28 Jun 2004 18:35:05 +1200 Subject: string concatenation In-Reply-To: References: Message-ID: you can += strings, but you need to create the variable first: i.e. for name in contextForm.keys(): context = '' context += "Input: " + name + " value: " + contextForm[name].value + "
    " concatenating a string like this is supposed to be substantially slower than using ''.join(sequence), where you can replace the blank string with the separator of your choice. using your example: for name in contextForm.keys(): sequence = ["Input: ",name, " value: ", contextForm[name].value, "
    "] context = ' '.join(sequence) HTH Ajay wrote: > hi! > > i am going through a for loop and want to add the strings together > i am doing this currently > > for name in contextForm.keys(): > context += "Input: " + name + " value: " + contextForm[name].value + > "
    " > > context is meant to hold all the form values in the paper. > however the code above doesn't work > > being new to Python, i dont know whether you can do += > > can you? > > cheers > -- > Ajay Brar, > CS Honours 2004 > Smart Internet Technology Research Group > > > > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. > From peter at engcorp.com Tue Jun 29 10:36:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 10:36:30 -0400 Subject: sending of mail (smtp) - connection refused - but smtp server is In-Reply-To: <10e2v1446n95e4b@corp.supernews.com> References: <10e2v1446n95e4b@corp.supernews.com> Message-ID: Alex Hunsley wrote: > I am failing with "connection refused" error, even though we definitely > have an smtp server running on port 25! ... > any ideas what the problem could be? this usually happens when someone > is not aware they have to run an SMTP server, but we do have one > running, as can be seen above! Not sure, but please try this at the interactive prompt and report (or analyze) what it returns: >>> from socket import * >>> getaddrinfo('192.168.1.105', 25, 0, SOCK_STREAM) This is something that smtplib.py is actually doing to get the host:port combination that it uses to connect. It seems that the only possible source for the failure you see is if it does not return the expected values. -Peter From peter at engcorp.com Sat Jun 26 07:41:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Jun 2004 07:41:41 -0400 Subject: eZ80 - correction [z80 vs Python thread] In-Reply-To: References: <7xllib8f66.fsf@ruckus.brouhaha.com> Message-ID: Janusz U. wrote: >>I think Python is too large a language for such a small processor. > > I know that Z80 or eZ80 aren't so powerfull like other 32-bit processors. > But eZ80 can have eg. 1MB flash memory and 512kB RAM (it has 16MB memory/IO > space!). Speed in my application isn't critical. One megabyte, eh? Python will _fill_ that up nicely. ;-) (Actually, we were able to get a limited form down to a few hundred kilobytes on an embedded device. Testing showed, however, that even if speed wasn't critical, Python's speed _can_ be too slow for certain older hardware and we gave it up. For reference, it was a 33MHz 386-compatible processor...) -Peter From ptmcg at austin.rr._bogus_.com Fri Jun 18 17:50:01 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 18 Jun 2004 21:50:01 GMT Subject: Saving search results in a dictionary - why is pyparsing better than regexp? References: Message-ID: "Lukas Holcik" wrote in message news:Pine.LNX.4.60.0406181448190.19022 at nymfe30.fi.muni.cz... > Hi Paul and thanks for reply, > > Why is the pyparsing module better than re? Just a question I must ask > before I can use it. Meant with no offense. I found an extra pdf howto on > python.org about regexps and found out, that there is an object called > finditer, which could accomplish this task quite easily: > > regexp = re.compile("
    .*?)\">(?P.*?)", \ > re.I) > iterator = regexp.finditer(text) > for match in iterator: > dict[match.group("pcdata")] = match.group("href") > > ---------------------------------------_.)-- > | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* > ----------------------------------------''-- > Lukas - A reasonable question, no offense taken. :) Well, I'm not sure I'd say pyparsing was "better" than re - maybe "easier" or "easier to read" or "easier to maintain" or "easier for those who don't do regexp's frequently enough to have all the re symbols memorized". And I'd be the first to admit that pyparsing is slow at runtime. I would also tell you that I am far from being a regexp expert, having had to delve into them only 3 or 4 times in the past 10 years (and consequently re-learn them each time). On the other hand, pyparsing does do some things to simplify your life. For instance, there are a number of valid HTML anchors that the re you listed above would miss. First of all, whitespace has a funny way of cropping up in unexpected places, such as between 'href' and '=', or between '=' and the leading ", or in the closing /a tag as "< /a >". What often starts out as a fairly clean-looking regexp such as you posted quickly becomes mangled with markers for optional whitespace. (Although I guess there *is* a magic re tag to indicate that whitespace between tokens may or may not be there...) Comments are another element that can confound well-intentioned regexp efforts. The pyparsing example that I gave earlier did not handle HTML comments, but to do so, you would define an HTML comment element, and then add the statement: link.ignore( htmlComment ) (pyparsing includes a comment definition for C-style block comments of the /* */ variety - maybe adding an HTML comment definition would be useful?) What would the above regexp look like to handle embedded HTML comments? In the sample I posted earlier, extracting URL refs from www.yahoo.com, a number of href's were *not* inside quoted strings - how quickly could the above regexp be modified to handle this? Doesn't the .* only match non-white characters? Does the above regexp handle hrefs that are quoted strings with embedded spaces? What about pcdata with embedded spaces? (Sorry if my re ignorance is showing here.) Lastly, pyparsing does handle some problems that regexp's can't, most notable those that have some recursive definition, such as algebraic infix notation, or EBNF. Working samples of both of these are included in the sample that come with pyparsing. (There are other parsers out there other than pyparsing, too, that can do this same job.) pyparsing's runtime performance is pretty slow, positively glacial compared to compiled regexp's or string splits. I've warned away some potential pyparsing users who had *very*clean input data (no hand-edited input text, very stable and simple input format) that used string split() to run 50X faster than pyparsing. This was a good exercise for me, I used the hotshot profiler to remove 30-40% of the runtime, but I was still far shy of the much-speedier string splitting algorithm. But again, this application had *very* clean input data, with a straightforward format. He also had a very demanding runtime performance criterion, having to read and process about 50,000 data records at startup - string.split() took about 0.08 seconds, pyparsing took about 5 seconds. My recommendation was to *not* use pyparsing in this case. On the other hand, for simple one-off's, or for functions that are not time- critical parts of a program, or if it doesn't matter if the program takes 10 minutes to write and 30 seconds to run (with say, pyparsing) vs. 15 minutes to write and 0.5 seconds to run (with say, regexp's), I'd say pyparsing was a good choice. And when you find you need to add or extend a given parsing construct, it is usually a very straightforward process with pyparsing. I've had a number of e-mails telling me how pleasant and intuitive it is to work with pyparsing, in some ways reminiscent of the "I like coding in Python, even if it is slower than C at runtime" comments we read in c.l.py every week (along with many expositions on how raw runtime performance is not always the best indicator of what solution is the "best"). Just as David Mertz describes in his Text Processing with Python book, each of these are just one of many tools in our toolkits. Don't get more complicated in your solution than you need to be. The person who, in 6 months, needs to try to figure out just how the heck your code works, just might be you. Sorry for the length of response, hope some of you are still awake... -- Paul From fishboy at spamspamspam.com Mon Jun 7 01:12:14 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 07 Jun 2004 05:12:14 GMT Subject: Misunderstanding about closures References: Message-ID: <36t7c011s3qpaqq2mkk0fk4p5rnvovthck@4ax.com> On Mon, 07 Jun 2004 03:27:22 GMT, "Alexander May" wrote: >When I define a function in the body of a loop, why doesn't the function >"close" on the loop vairable? See example below. > Hmmm, I'm having a hard time phrasing the answer to this in a form besides, "Because the function doesn't 'close' on a loop variable" Hrmmm ..... Ok, how about this x = 'a' for x in range(10): foo(x) bar(x) What value do you expect 'x' to be in bar(x)? Because it sounds like you were expecting it to be bar('a') instead of bar(9). Hrmm, I just remembered. That's a C thing, isn't it? The loop variable being only defined inside the loop. God that makes to happy. Forgetting stuff like that. Maybe in another 20 years I'll forget everything I ever knew about static typed languages and pass into hacker Nirvana. ><{{{*> From psheer at icon.co.za Mon Jun 21 13:15:19 2004 From: psheer at icon.co.za (Paul Sheer) Date: 21 Jun 2004 10:15:19 -0700 Subject: Compiling the Python sources with a C++ compiler (aCC) References: <10dai1qekcb7ce@corp.supernews.com> Message-ID: <9ec0d967.0406210915.4cdac6ee@posting.google.com> > > If that pattern is used a lot, it would be cleaner to use a macro and avoid > the duplication. > there are many other pointer casts that are missing. malloc is only one. -paul From p_s_oberoi at hotmail.com Tue Jun 29 12:36:36 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 29 Jun 2004 11:36:36 -0500 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <40E0C8EA.20305@rogers.com> Message-ID: >> If you like simplicity, take a look at the Boost license: >> >> http://www.boost.org/LICENSE_1_0.txt > > Not bad... sort of like the MIT license I linked to above, only, > uh, slightly less simple, eh? Yeah, I hadn't looked at the MIT license for a long time, and I didn't realise it was even shorter. The only difference between the two seems to be that the Boost license does not require any copyright notices to be present in binary redistributions. From connellybarnes at yahoo.com Fri Jun 18 01:35:55 2004 From: connellybarnes at yahoo.com (Connelly Barnes) Date: 17 Jun 2004 22:35:55 -0700 Subject: String buffer Message-ID: <32e4319c.0406172135.71c279d5@posting.google.com> Yet another useful code snippet! This StringBuffer class is a FIFO for character data. Example: B = StringBuffer('Hello W') B.append('orld!') print B.read(5) # 'Hello' print B.read() # 'World!' The append method appends a string to the end of the string buffer. The read(n) method reads and removes n characters from the beginning of the buffer. If n is omitted, it reads the entire buffer. To view the first n characters of the string buffer, use peek: print B.peek(5) # View first 5 characters Or cast as a string to get the entire contents: print str(B) # View entire buffer The append and read methods are O(k), where k is the number of characters appended or read. # ------------------------------------------------------- # StringBuffer: A FIFO for string data. # ------------------------------------------------------- class Deque: """A double-ended queue.""" def __init__(self): self.a = [] self.b = [] def push_last(self, obj): self.b.append(obj) def push_first(self, obj): self.a.append(obj) def partition(self): if len(self) > 1: self.a.reverse() all = self.a + self.b n = len(all) / 2 self.a = all[:n] self.b = all[n:] self.a.reverse() def pop_last(self): if not self.b: self.partition() try: return self.b.pop() except: return self.a.pop() def pop_first(self): if not self.a: self.partition() try: return self.a.pop() except: return self.b.pop() def __len__(self): return len(self.b) + len(self.a) class StringBuffer(Deque): """A FIFO for characters. Strings can be efficiently appended to the end, and read from the beginning. Example: B = StringBuffer('Hello W') B.append('orld!') print B.read(5) # 'Hello' print B.read() # 'World!' """ def __init__(self, s=''): Deque.__init__(self) self.length = 0 self.append(s) def append(self, s): n = 128 for block in [s[i:i+n] for i in range(0,len(s),n)]: self.push_last(block) self.length += len(s) def prepend(self, s): n = 128 blocks = [s[i:i+n] for i in range(0,len(s),n)] blocks.reverse() for block in blocks: self.push_first(block) self.length += len(s) def read(self, n=None): if n == None or n > len(self): n = len(self) destlen = len(self) - n ans = [] while len(self) > destlen: ans += [self.pop_first()] self.length -= len(ans[-1]) ans = ''.join(ans) self.prepend(ans[n:]) ans = ans[:n] return ans def peek(self, n=None): ans = self.read(n) self.prepend(ans) return ans def __len__(self): return self.length def __str__(self): return self.peek() def __repr__(self): return 'StringBuffer(' + str(self) + ')' - Connelly Barnes From miki.tebeka at zoran.com Sun Jun 6 09:49:35 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 6 Jun 2004 15:49:35 +0200 Subject: C compiler written in Python In-Reply-To: <10bujgn6m8bnfb0@corp.supernews.com> References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <7x4qpsvdfg.fsf@ruckus.brouhaha.com> <10bujgn6m8bnfb0@corp.supernews.com> Message-ID: <20040606134935.GH1836@zoran.com> Hello Paul, > >Um, if you want to program in Lisp, why just program in Lisp directly > >instead of messing with C and Python? Around here people write for embedded devices. As much as we'd like to program in Python it's not possible with 2-6k of program RAM. What we *can* do is make writing Assembly/C more tolerable task. I think in this area Python (Lisp, ...) has very much to offer. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From __peter__ at web.de Wed Jun 16 09:22:20 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Jun 2004 15:22:20 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Jacek Generowicz wrote: > Peter Otten <__peter__ at web.de> writes: > >> Note, however, that dynamically inserting variables is not the best >> programming practice. When you don't know the variable name in >> advance, what would be the benefit of being able to access the >> object via its identifier? > > When _who_ doesn't know the variable name in advance of _what_ ? I may be fighting with the english language here - and lose... >>>> dir() > [ ] >>>> from foo import * >>>> dir(foo) > [ , 'hello'] >>>> hello() > 'Hello, World!' > > Here we dynamically inserted variables not known beforehand to the > user, even if they were known beforehand to the module writer. I've taken to avoid the * import, but at least I would hope that you - had a quick look at the foo documentation before you chose to import it - follow the convention of placing import statements at the beginning of the module, and therefore can write your own help() function with some confidence that it will not be inadvertently replaced by foo.help > Not convinced? You guessed it. > OK ... > >>>> from treebuilder import build_structure_from_xml_tree >>>> dir() > [ ] >>>> build_structure_from_xml_tree('fubar.xml') >>>> dir() > [ , 'root' ] >>>> dir(root) > ['branch1', 'branch2'] > > > Here we dynamically inserted variables not known beforehand to the > author of the module, which may or may not have been known to the > user. If the user were the author of fubar.xml then, presumably he > would know the variable names; if he were not, then he may well not > know them beforehand. Either way he is likely to want to access them by > name. OK. Now show me the demo again with an XML document along the lines of In principle I have no problem with the dynamically chosen attribute names - just hope my example would *not* result in the creation of fileN attributes - but why can't your function_with_a_long_name() just return the root *object* and let the user decide about the appropriate name - or at least take a namespace as its second argument? > ... still not convinced ? This is even worse. > I have a program which parses C++ header files and creates Python > proxies for the stuff found therein, allowing you to interact with > objects in C++ libraries. You load something we call a dictionary > (which describes the library) and the program uses that information to > create, dynamically, Python objects with the same names and structures > as the C++ classes in the library. > > The author of the program certainly does not know the names of the > objects the program is going to create in the future. The client may > know them (he might be wanting to rewrite some C++ code in Python), or > not (he might be wanting to use Python's introspection capabilities to > poke around the C++ library). As far as I can judge from the description, this is perfectly OK with me. The recommendation to avoid dynamic manipulations of the global namespace was not meant as a rule carved in stone, but rather a means to write cleaner code and avoid errors that may be hard to reproduce. Peter PS: I'm glad I didn't also warn the OP against using metaclasses with as little information as his code snippets and lack of knowledge of the globals() function. I admit I was tempted... From peufeu at free.fr Fri Jun 25 02:38:05 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 08:38:05 +0200 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> <889cbba0.0406240650.35ebf730@posting.google.com> <889cbba0.0406241734.14667b79@posting.google.com> Message-ID: > You know, as I was writing stuff like fn(**args.__dict__) yesterday > (which for me is pretty advanced!), it occurred to me that Python is > not 'simpler than C' In the case of variable number of args, C gives you neither the number of arguments, not their types, nor their names, so you have to send the number as a parameter or append a null at the end which... sucks ! From newsgroups at jhrothjr.com Sat Jun 26 07:36:39 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 26 Jun 2004 07:36:39 -0400 Subject: any trick to allow anonymous code blocks in python? References: <10dphkp78g6ne9d@news.supernews.com> Message-ID: <10dqntplp6v67bf@news.supernews.com> "Doug Holton" wrote in message news:ROydndnd54-eYUHdRVn_iw at comcast.com... > John Roth wrote: > >>Is there any metaclass trick or something similar to allow anonymous > >>code blocks? > >> > ... > > No. If you're looking for GUI callbacks, there's a significant > > gap between lambdas and bound methods. You could > > use something like (not tested): > > > > b.OnClick = (lambda : sys.stdout("You clicked me")) > > Yeah, I didn't mention the lambda option. I was thinking about > designing a framework meant for beginners, and I'd rather stay away from > lambdas. I'm surprised no one is even proposing support for anonymous > code blocks in Python that support multiple lines, similar to what Ruby, > Java, and other languages have. It's been proposed a number of times, and you can find the discussions (some of which amount to flame wars) by searching Google Groups. IIRC, there are two fundamental issues. One is syntax: it's not easy to find a decent syntax that looks good, lets you shift back to statement level from expression level, and handles blocks for each parameter of a method. The other issue is that blocks themselves don't do all that much. Ruby's facility with blocks actually comes from the very nice intersection of several features, including the pervasive implementation of the visitor pattern in all collection objects and the provision of a block as a special parameter. There are a couple of other features that also help. Blocks without those other features wouldn't do what Ruby does. The same thing is true of, for example, Smalltalk. Blocks have to be seen in the context of the entire language. John Roth From till at score.is.tsukuba.ac.jp Thu Jun 24 12:10:23 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Fri, 25 Jun 2004 01:10:23 +0900 Subject: Encryption with Python In-Reply-To: References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: <20040624161023.GA19038%till@score.is.tsukuba.ac.jp> On Wed, Jun 23, 2004 at 12:50:39AM -0400, Peter Hansen wrote: > Kamilche wrote: > ... > >I've written an encryption algorithm in pure Python that can process > >22 megs of data a second. I know it's not secure, but it should be > >enough to ward off casual hacking. Does someone know of something > >speedier? > > In addition to Erik and Paul's comments: if you don't specify > what machine you ran your benchmark on, the number "22MB/s" is > completely meaningless... > > Besides, what you say is not possible. On my machine, > which is about a P4 2500MHz, scanning an array.array('c') with > 22MB of data in it, doing nothing but reading each byte and > ignoring it, takes about 8 seconds. > So does converting the > array to a list, which is pretty much all C code. are you sure it takes 8s? >>> from array import array >>> from time import time >>> f=file("xxx").read() >>> len(f) 22000000 >>> s=time();A=array("c",f);t=time(); print t-s 0.0371170043945 >>> s=time();l=list(A);t=time(); print t-s 0.681946992874 That is over ten times faster than your machine. I cannot believe that. I use Python 2.3.4 (#2, Jun 24 2004, 13:32:58) [GCC 3.3.3 [FreeBSD] 20031106] on freebsd5 CPU: AMD Opteron(tm) Processor 248 (2205.01-MHz K8-class CPU) >>> s=time();A=array("L",f);t=time(); print t-s 0.0372500419617 >>> r=range(22000000/8) >>> if 1: ... s=time() ... for i in r: ... A[i]^=7877854 ... t=time() ... print t-s ... 1.80496907234 >>> So with a 4Ghz Opteron (or better) he should be able to xor a 22MB array in one second with some constant. - Till From phleum_nospam at chello.se Thu Jun 17 09:44:03 2004 From: phleum_nospam at chello.se (Carl) Date: Thu, 17 Jun 2004 15:44:03 +0200 Subject: Using Fortran libraries from Python? Message-ID: I have experimented with f2c and swig-generated wrappers to create python modules from Fortran files. I think I'm missing something when I'm building the Python module, because when I import the built module the Python interpreter returns the following: >>> import LDSsobol Traceback (most recent call last): File "", line 1, in ? File "LDSsobol.py", line 4, in ? import _LDSsobol ImportError: /usr/lib/libf2c.so.0: undefined symbol: MAIN__ This is how I built LDSsobol: > gcc -c LDSsobol.c > gcc -c LDSsobol_wrap.c -I/usr/include/python > gcc -shared LDSsobol.o LDSsobol_wrap.o -l f2c -o _LDSsobol.so Any help is appreciated! Carl From brian at sweetapp.com Sun Jun 20 14:21:14 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Sun, 20 Jun 2004 20:21:14 +0200 Subject: ANN: Vancouver Python Workshop - Talk deadline reminder In-Reply-To: <40CF1521.5040901@sweetapp.com> References: <40CF1521.5040901@sweetapp.com> Message-ID: <40D5D59A.4060004@sweetapp.com> This is a reminder that the deadline for submitting talks for the Vancouver Python Workshop is June 22nd. To submit a talk, see: http://www.vanpyz.org/conference/registration/submissions.html For general conference information, see: http://www.vanpyz.org/conference About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Talk submissions: until June 22nd Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From tismer at stackless.com Fri Jun 25 13:46:25 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 25 Jun 2004 19:46:25 +0200 Subject: Parameterized Functions without Classes In-Reply-To: <2k35g4F14l1o0U1@uni-berlin.de> References: <2k35g4F14l1o0U1@uni-berlin.de> Message-ID: <40DC64F1.3020404@stackless.com> Oliver Fromme wrote: > Christian Tismer wrote: > > just as a small comment on the side-effects of the > > rather new concept of local functions with access to > > their scope: > > [...] > > def _converter(scale): > > def convert(arg): > > return scale * arg > > return convert > > In what way is that different from using an ordinary lambda > function? i.e.: There is no difference than the existing differences between lambdas and def'ed functions. The scope rules are the same. > Of course, the use of lambda functions is very limited > because (unfortunately) they can contain only one single > expression. But other than that, it's pretty much the > same concept, isn't it? Lambdas were not the topic, since they are a deprecated feature, but sure it works. The intent of my post was to show a "clean" way to do things classless, directed to newcomers. It was not about showing all possible (and unrecommended) ways to do it. That would have filled 5 pages :-) ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From gerson.kurz at t-online.de Mon Jun 14 10:22:17 2004 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Mon, 14 Jun 2004 14:22:17 GMT Subject: setattr using invalid attribute names - bug or feature? Message-ID: <40cdb3d5.2146906@news.t-online.de> I stumbled across this (while using my homebrewn enum class): class test: pass instance = test() setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) I would've expected some kind of error message here when calling setattr(); after all, its not a regular attribute? Plus, documentation says " Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. " and you cannot write this: instance.THIS :*2+~# IS OBVIOUSLY INVALID = 123 (oh, and its: PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32.) From rogerb at rogerbinns.com Wed Jun 9 21:43:52 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 9 Jun 2004 18:43:52 -0700 Subject: Doc strings for a standalone app?? References: Message-ID: j_mckitrick wrote: > Does it make sense to use doc strings rather than #-comments for a > standalone Python app? If the classes aren't going to be re-used or > imported, do they need them? Doc strings are useful for documenting your app :-) For example if you run epydoc on the code you will get a very good overview of what is going on. That is then very useful to other programmers, or yourself several months later. And if you ever sell the code, you'll get a lot more for it :-) Roger From a.d.schapira at worldnet.att.net Sun Jun 6 21:02:17 2004 From: a.d.schapira at worldnet.att.net (Al Schapira) Date: Mon, 07 Jun 2004 01:02:17 GMT Subject: This is very simple question In-Reply-To: References: Message-ID: <40C3BEE1.8000400@worldnet.att.net> Eric wrote: > I would want to obtain a list of factors (multiples of 2) given a > prime number in python. > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > I would appreciate a fuction which would do this. > > Eric What you seem to want are the powers of 2 that add up to the given number. These are the powers of two that correspond to 1's in the binary representation of the given number (integer). $ cat foo.py powerlist = [1 << (30-i) for i in range(31)] # [... 32, 16, 8, 4, 2, 1] for x in [13,5,7,15,17,33]: print x, [x & i for i in powerlist if x & i] $ python < foo.py 13 [8, 4, 1] 5 [4, 1] 7 [4, 2, 1] 15 [8, 4, 2, 1] 17 [16, 1] 33 [32, 1] Is this horse dead yet? -Al Schapira, a.d.schapira at worldnet.att.net From imbosol at aerojockey.invalid Mon Jun 14 17:02:02 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 14 Jun 2004 21:02:02 GMT Subject: does python have useless destructors? References: <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: David Turner wrote: >> I assumed that you knew this, and I assumed that you were aware of the >> limitations of reference counting (in particular, that you cannot rely >> on a reference count ever going to zero). That is why I took your >> statement to mean something else. > > The limitations you refer to occur extremely infrequently in practice. 1. That's not my experience at all (it's not the the objects are involved reference cycles; it's that it's a member of some other object that's reference cycled). 2. Your claim of robustness is out the window. What you ask for does not free the programmer from having to worry about when the resource will be freed. It merely changes the question to, "Is it ok if there are cases when this resource totally fails to be freed?". If that's all you want, and if doesn't adversely affect other concerns (say, performance) too much, then I don't object to it, but it better come with a disclaimer in big letters, because, unlike in C++, it doesn't guarnatee anything. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From p_s_oberoi at hotmail.com Fri Jun 18 14:38:34 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Fri, 18 Jun 2004 13:38:34 -0500 Subject: Attention, hyperlinkers: inference of active text References: <10d6bln988rmne6@corp.supernews.com> Message-ID: > The design breaks down more annoyingly by the time we get to > the "file" scheme, though. How do the rest of you handle this? > Do you begin to make end-users quote, as in > The secret is in "file:\My Download Folder\dont_look.txt". Some thoughts: 1. The quoting certainly seems like a good idea, and one that is applicable even if other other approaches are also used. Plus, it is consistent with how most shells handle this problem. 2. You can special case common filenames like "Program Files", "Documents and Settings", "My Music", etc., (the precise list would depend on your environment & usage). 3. You could conceivably look in the filesystem (or even on the web) to check which names/URLs are valid... but I think this could be a bad idea because the program's behavior become non-deterministic. It might confuse users. -param PS: I've never encountered this problem myself, so this could all be wrong. From export at hope.cz Wed Jun 16 17:19:37 2004 From: export at hope.cz (Lad) Date: 16 Jun 2004 14:19:37 -0700 Subject: Robot Message-ID: <81a41dd.0406161319.1ec68dbb@posting.google.com> Does anyone know about a script that can walk through webpages and extract an information from these web sites according to given keyword(s)? Thanks for reply From reply.in.the.newsgroup at my.address.is.invalid Sat Jun 19 06:43:16 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 19 Jun 2004 12:43:16 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <35m6d0dejkk88urvkvvfs4fslk9e8900vm@4ax.com> <2jhh7pF11m1q4U1@uni-berlin.de> Message-ID: Leif K-Brooks: >Rene Pijlman: >> I've used Cheetah with mod_python and it worked fine: >> http://www.cheetahtemplate.org/ > >Looks interesting, but the last update was over six months ago. Any idea >what might be going on with it? The mailing list is still active with people using the software. There's nothing wrong with it as far as I can tell. What particular functionality or fix seems to be lacking? Well, I can think of one: I don't like the explicit compilation model. I'd prefer some sort of automatic compilation, based on the timestamp of the source file. So that it can be used more easily, like PHP. -- Ren? Pijlman From peter at engcorp.com Wed Jun 23 16:40:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 16:40:51 -0400 Subject: shared file access in python In-Reply-To: <9418be08.0406231105.13e3bc9e@posting.google.com> References: <9418be08.0406180620.3e64be96@posting.google.com> <9418be08.0406210618.492f40d4@posting.google.com> <9418be08.0406231105.13e3bc9e@posting.google.com> Message-ID: Lev Elblert wrote: > Peter! > > I do not know what kind of msvcrt module you have, but here is the > output of relavant commands on my machine: [snip] You misread the message below, I believe. You seem to think I was the one saying that the msvcrt module did not have lots of functions... Also, please don't top-post. Thank you. -Peter > Peter Hansen wrote in message news:... >>Lev Elblert wrote: >>>2. msvcrt.lib does have a lot of functions, but not msvcrt module in >>>Python. (correct me if I'm wrong) >> >>http://docs.python.org/lib/module-msvcrt.html shows there are a variety >>of functions there (try typing "import msvcrt" as well), but I can't >>see that they have what you need. From llothar at web.de Mon Jun 14 04:04:53 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Jun 2004 01:04:53 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <6ee58e07.0406140004.3d7c35c4@posting.google.com> rmb25612 at yahoo.com (Richard James) wrote in message news:<2c60f0e0.0406131234.49b485ec at posting.google.com>... > Needless to say, the Ruby site was Slashdot-ed today. This has nothing to do with ./ The site was hacked and corrupted two weeks ago and since this time one a stub is online. From claird at lairds.com Wed Jun 23 09:15:38 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 23 Jun 2004 13:15:38 -0000 Subject: Python intro questions (was: ) References: <2D1DF9BA9166D61188F30002B3A6E1530E68E2F0@ROSEEXCHMA> Message-ID: <10dj0jq3b1q6u2c@corp.supernews.com> In article , Skip Montanaro wrote: . . . >department behind it. Nobody gets paid to write articles about Python, so >its growth has been somewhat more measured. The growth isn't due to an . . . On an industrial scale, yes, pay for Python articles is essentially zero. Please do note, though, that develop- erWorks, O'Reilly, *Linux Journal*, *Linux Magazine*, and at least a few other outlets have been surprisingly generous in their support of Python-focused content. Just yesterday, UnixReview.com ran . There's even a slim chance for a Python-oriented magazine. It's slim, of course, precisely because it's so hard to figure out who'd want to advertise in such a publication, and because advertising is so crucial. -- Cameron Laird Business: http://www.Phaseit.net From lbates at swamisoft.com Wed Jun 16 10:50:26 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 16 Jun 2004 09:50:26 -0500 Subject: A little help with child processes. References: Message-ID: Unless you are going to start more than one child process in parallel and there is enough I/O to make it worthwhile, there's no reason for using child processes at all. Just program the application as a single loop. You can't speed up CPU bound applications with child processes. HTH, Larry Bates Syscon, Inc. "Rech" wrote in message news:rech-D3F585.16050416062004 at individual.net... > Hi, > I need a little help here managing child processes in Python. I'm not so > skilled in system programming so I hope you can give me some good > suggestions. > > I have a very CPU and memory intensive task that has to be repeated many > times (with different input parameters). So I've thought to write a > Python script that create a child process, wait for it to finish and > then starts again another child with different parameters. > > The children processes will save all the results to the disk (using > cPickle module), so the parent process has to wait each child only and > then starts the next one. The problem is that I can't work out a > solution. Sorry, but system programming is not my job. > > Any suggestions about how to realize that? A skeleton of the script will > just suffice. > > > Thanks in advance, > Andrea. From guettli at thomas-guettler.de Wed Jun 9 06:22:54 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 09 Jun 2004 12:22:54 +0200 Subject: fast list search? References: Message-ID: Am Wed, 09 Jun 2004 11:49:19 +0200 schrieb ramon aragues: > Hi, > > I?ve got a list with more than 500,000 ints. Before inserting new ints, > I have to check that it doesn?t exist already in the list. > > Currently, I am doing the standard: > > if new_int not in long_list: > long_list.append(new_int) > > > but it is extremely slow... is there a faster way of doing this in python? Hi, Use a dictionary instead of the list: if not long_dict.has_key(new_int): long_dict[new_int]=1 Thomas From __peter__ at web.de Wed Jun 30 10:14:48 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jun 2004 16:14:48 +0200 Subject: sort accented string References: Message-ID: Laurent wrote: > Peter what about using this kind of tip with cmp() built-in ?? > > def myCompare(self,a,b): > cmp(a,b) > > with a and b being french accented chars ??? > > Any idea ?? >From the documentation of the locale module: """ strxfrm(string) Transforms a string to one that can be used for the built-in function cmp(), and still returns locale-aware results. This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings. """ Peter From __peter__ at web.de Sat Jun 12 04:01:31 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jun 2004 10:01:31 +0200 Subject: Exec Multiple Lines? References: Message-ID: Chris S. wrote: > I'd like to dynamically execute multiple lines of indented code from > within a script, but I can't seem to find a suitable function. Exec only > works with unindented code, and execfile only works with files. I > suppose I could write my string to a temporary file and then use > execfile, but that seems like a hack. Is there an easier way? Any help > is appreciated. Either dedent or trick Python into expecting indented code: >>> s = """ ... print "and I say hello" ... print "hello, hello" ... """ >>> exec s Traceback (most recent call last): File "", line 1, in ? File "", line 2 print "and I say hello" ^ SyntaxError: invalid syntax >>> exec "if 1:\n%s" % s and I say hello hello, hello >>> Peter From kirk at strauser.com Wed Jun 2 17:55:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Wed, 02 Jun 2004 21:55:06 GMT Subject: file fragmentation project References: Message-ID: <87ise9tykr.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-06-02T21:10:02Z, Bart Nessux writes: > In particular, I'd like to write a file fragmentor in Python that will > randomly fragment x% of files on a NTFS filesystem into y number of > fragments. You may or may not be able to do so, depending on how smart your exact version of NTFS decides to be on that given day. Still, the standard algorithm to fragment a file m bytes long into n pieces is: 1) Create n * 2 files, each (m/n) bytes long. 2) Delete every other file. 3) Write the file to be fragmented, and hope that the filesystem naively shoves it into the empty holes. 4) Delete the remaining "pad" files. A similar algorithm is to replace step 1 with: 1) Fill the entire drive with files (m/n) bytes long. If the filesystem isn't smart enough to rearrange empty blocks, then that should to the trick. > Anyway, would Python be acceptable for this type of project? Speed is > somewhat important, but not extremely. You bet. Filesystem speed will be the limiting factor. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAvky35sRg+Y0CpvERAkm9AKCOeYJZ3aEbgcFERo8Iy5dxAKD6aQCeMWEO bnwx/bkTjkWo+JE/pCrMjvU= =CmhE -----END PGP SIGNATURE----- From jjl at pobox.com Sun Jun 27 17:28:07 2004 From: jjl at pobox.com (John J. Lee) Date: 27 Jun 2004 22:28:07 +0100 Subject: Delphi extension References: <10dloooa4p9hade@corp.supernews.com> Message-ID: <87oen4g07s.fsf@pobox.com> Jarek Zgoda writes: > Christopher T King pisze: > > > I don't know anything about Delphi; it may use a different calling > > convention than C (unlikely). If that's the case, however, you're out of > > luck unless you can find a Delphi-C or Delphi-Python interface module. > > Register is default call convention for libraries written in Delphi, but > one may use any other at will. A bit of a Delphic utterance... Googling, it seems 'Register' is what MSVC calls __fastcall. Not sure how you tell which Delphi functions obey which calling convention, but (in the absence of a more polished method) I think I'd attempt to find that out, then write a thin wrapper of the Delphi interface in C, with explicit calling convention declarations (eg. __fastcall), then wrap *that* with SWIG. John From a at a.invalid Mon Jun 7 04:11:22 2004 From: a at a.invalid (Timo Virkkala) Date: Mon, 07 Jun 2004 08:11:22 GMT Subject: left-quote ( ` ) on International keyboards [Prothon] In-Reply-To: References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: Mark Hahn wrote: > We are thinking of using it as a marker for "symbols" in Prothon. They are > like strings but can only be legal variable labels: `var, `init_, `x, > `account_balance, etc. I think in our application they look good and won't > be mistaken for quotes since they don't come in pairs. They are readable > and distinquishable in this context. Also, symbols won't be used that > frequently so typing won't be too much of a pain. Why not use something like $ or something? I'm not familiar with Prothon, so I don't know if $ is already used for something, but it's a character normally used with symbols/placeholders/etc. -- Timo "WT" Virkkala From alloydflanagan at comcast.net Tue Jun 22 11:01:38 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 22 Jun 2004 08:01:38 -0700 Subject: Interfacing with clipboard (from Tkinter or whatever) - newbie quetion References: <56cfb0e3.0406161520.7cc223f8@posting.google.com> Message-ID: Mark 'Kamikaze' Hughes wrote in message news:... > Porky Pig Jr > wrote on 16 Jun 2004 16:20:13 -0700: > I don't use Emacs, but probably you selected and copied that text with > the keyboard, so it never got in PRIMARY, and Emacs only uses PRIMARY. > Actually, this is Emacs we're talking about, which means it isn't that simple. Emacs uses its own buffer by default, but (of course) you can customize it. In particular, there's an option "X Select Enable Clipboard" in the customization group "Editing/Killing" which causes emacs to use the X selection in addition to its private buffer. If you get really ambitious, you can tell emacs which X selection to use, but you don't want to go there if you can help it. :) From ptmcg at austin.rr._bogus_.com Sat Jun 5 23:27:26 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 06 Jun 2004 03:27:26 GMT Subject: write a bitmap using python References: Message-ID: "lyuan" wrote in message news:c9tpn5$rrt$1 at woodrow.ucdavis.edu... > Hi, Paul, > Thanks for your help. The code is indeed clear and illustrative. > > I wonder under what license is your code distributed? Do you mind if I > include part of your code into my code? I'm not writing anything > commercial, but instead a scientific data analysis program. > > > thanks > Lihua > Lihua - Re-download the .py file - it now includes an MIT open source license header. I'm glad it could help. -- Paul From nun at meyl.com Wed Jun 16 03:17:48 2004 From: nun at meyl.com (Mitja) Date: Wed, 16 Jun 2004 09:17:48 +0200 Subject: Just testing References: Message-ID: Michael Lauzon (news:mailman.25.1087341507.21521.python-list at python.org) wrote: > I am just testing, as I need to create a filter. Use alt.test, then From skip at pobox.com Tue Jun 22 15:34:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 22 Jun 2004 14:34:07 -0500 Subject: Queue module and Python Documentation Rant In-Reply-To: References: <6bl9q1-e98.ln1@home.rogerbinns.com> <40D240E9.6070801@hotmail.com> <451aq1-qaa.ln1@home.rogerbinns.com> Message-ID: <16600.35247.114829.897928@montanaro.dyndns.org> Peter> Roger Binns wrote: >> Unfortunately I don't see what you could have done to spot the >> following page other than looking at the bottom. Peter> Reading the docs more often would help. There are many different Peter> pages that have such subsection links at the bottom, so one Peter> should be used to it. It's perhaps worth noting that there are basically two types of module doc structures. Let's call them the Fred way (such as the docs for the Queue module) and the Greg way (such as the docs for the optparse module). There's nothing wrong with the way Greg wrote his docs, but they seem much less like reference material to me and more like a normal user's manual, emphasizing the important stuff but without being 100% comprehensive. That makes it more challenging than I think it ought to be to answer a simple question like, "what methods do OptionParser objects implement?" You can fall back to pydoc but that requires that most/all methods have doc strings to be useful. I have a particularly hard time finding information in the distutils section of the libref manual. I should probably pay more attention to the various submodule docs. Skip From davidf at sjsoft.com Wed Jun 2 16:50:32 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 22:50:32 +0200 Subject: distutils sdist and MANIFEST files In-Reply-To: <40be1b9a$0$12508$9b622d9e@news.freenet.de> References: <40be1b9a$0$12508$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > David Fraser wrote: > >> Does anyone else find it annoying that the sdist command for distutils >> relies on MANIFEST.in and MANIFEST files? >> I would really like to be able to do everything in the setup script ; >> if I don't, the MANIFEST files get created automatically (with >> warnings) and any new scripts added are forgotten. >> >> Any alternative approaches to this? > > > You can derive from the sdist command and override the read_template > function. > > Regards, > Martin > Thanks, I'll have a look at this... David From donn at u.washington.edu Mon Jun 7 19:13:44 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Jun 2004 16:13:44 -0700 Subject: How to get process info from python References: Message-ID: In article , "Gardner Pomper" wrote: > Thanks for the suggestion, but I have already looked at those modules. Do > you have a command in mind? I can only find process information about the > python process and its parents and children.. if I want to see a list of all > processes on the system, or all processes for the current user, I don't see > any way to get that. There isn't any support for this in Python. Normally when saying something like that, I could half expect someone to pop up with a module or something, but in this case I feel relatively confident that no such module is widely supported. On Linux and *BSD platforms, you can get this information from the /proc filesystem instead of "ps", but it's still fairly platform dependent. Of course that won't work on AIX. Donn Cave, donn at u.washington.edu From sholden at holdenweb.com Fri Jun 25 08:35:16 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 25 Jun 2004 08:35:16 -0400 Subject: String concatenation In-Reply-To: References: Message-ID: <40DC1C04.6060408@holdenweb.com> Duncan Booth wrote: [...] > Finally, a method call on a bare string (''.join, or '\n'.join) looks > sufficiently bad that if, for some reason, you don't want to give it a name > as above, I would suggest using the alternative form for calling it: > > str.join('\n', aList) > > rather than: > > '\n'.join(aList) This is, of course, pure prejudice. Not that there's anything wrong with that ... regards Steve From tismer at stackless.com Fri Jun 25 22:32:21 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 26 Jun 2004 04:32:21 +0200 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: References: Message-ID: <40DCE035.7050104@stackless.com> Tyler Eaves wrote: > lambda? Looks like, since it does not put a name on the function. But there is anyway a function object created, not just a code object. The similar to using an unnamed lambda is defining a function, bindin it into some context, and deleting it immediately. There is no difference, in principle. -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From indigo at bitglue.com Thu Jun 24 18:37:54 2004 From: indigo at bitglue.com (Phil Frost) Date: Thu, 24 Jun 2004 18:37:54 -0400 Subject: Obtaining Webpage Source with Python In-Reply-To: <6962d028.0406232103.6f5d9f7f@posting.google.com> References: <6962d028.0406232103.6f5d9f7f@posting.google.com> Message-ID: <20040624223754.GA31531@unununium.org> Take a look at the urllib module: http://python.org/doc/2.3.3/lib/module-urllib.html On Wed, Jun 23, 2004 at 10:03:04PM -0700, Ryan Kaskel wrote: > How can I obtain the source of a remote webpage (e.g. > http://www.python.org/index.html) using Python? > > Something like: > > pyPage = open('http://www.python.org/index.html',r).read() > > Obviously that won't work but how can I do something to that effect? > Thanks, > Ryan Kaskel > > --I posed this before but it seems it is not showing up... From phil at dspfactory.com Wed Jun 30 16:39:55 2004 From: phil at dspfactory.com (Philip Rittenhouse) Date: Wed, 30 Jun 2004 16:39:55 -0400 Subject: Python exceptions through COM custom interface Message-ID: I have one last issue with pywin32 to report. The problem occurs with Python COM servers raising COM exceptions across a custom interface. Using the dispatch interface works fine, but in the custom interface the exception's error information is lost. The problem appears to be in PyGatewayBase::InterfaceSupportsErrorInfo() in PyGatewayBase.cpp. It is called to determine whether the GetErrorInfo API should be used to extract an error after an error HRESULT is returned from an interface. The function is passed an IID of an interface, the code compares this to the return value of GetIID() which is always IID_IUnknown. The comparison fails, so the function returns S_FALSE and no error info is extracted. The comment above the definition of GetIID() says: // Currently this is used only for ISupportErrorInfo, // so hopefully this will never be called in this base class. // (however, this is not a rule, so we wont assert or anything!) But it appears that it is called in the base class (or at least not overloaded by anyone inheriting from it). Everything seems to work fine if you just change InterfaceSupportsErrorInfo() to always return S_OK. Can anyone tell me how this code is meant to work? Why is the check against GetIID() in there at all? Thanks! Phil From secun at yahoo.com Mon Jun 7 14:53:20 2004 From: secun at yahoo.com (ChrisH) Date: Mon, 07 Jun 2004 18:53:20 GMT Subject: win32all - determine wrkstn vs. server Message-ID: Does anyone know of a way to determine whether the current computer running a python script is a workstation or server? I've used the following code, but it only tells me the version of Windows. (majVer,minVer,buildNum,platID,osInfo) = win32api.GetVersionEx() Thanks, Chris From rogerb at rogerbinns.com Wed Jun 16 03:52:49 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 16 Jun 2004 00:52:49 -0700 Subject: how to become a really good Python programmer? References: Message-ID: Randall Smith wrote: > Following Guido around would be ideal, but I will settle for > a good book. Any recommendations for learning resources? Becoming really good generally means also making your own mistakes and/or learning from the mistakes of others. The Python cookbook is full of excellent ways of doing things you may not have stumbled upon by just reading the doc or in your day to day work. I prefer the book, but the content is all on the website as well. I would recommend programming in the "open". Find an open source project and do some code for it. That will give the chance for others to critique what you have coded, as well as you seeing what others code all out in the open. You also get an appreciation for other issues if you want such as release engineering, documentation, configuration management which are all part of programming. Here is a list of over 3,300 Python projects at SourceForge: http://sof.net/softwaremap/trove_list.php?form_cat=178 The first page alone has a wide variety of areas so you should be able to find some areas that interest you. It also makes good resume filler :-) Roger From fishboy at spamspamspam.com Tue Jun 8 00:39:19 2004 From: fishboy at spamspamspam.com (fishboy) Date: Tue, 08 Jun 2004 04:39:19 GMT Subject: Calling Python Script from MS Excel? References: <40c51309$0$2944$61fed72c@news.rcn.com> Message-ID: On Mon, 07 Jun 2004 21:14:49 -0400, "Kevin T. Ryan" wrote: >Hi Group - > >I have written a "semi-program" in MS Excel related to running a football >pool. I've updated it over the past two years or so, to the point where it >is getting pretty advanced. Only, there are a few tricks that I want to >add that I could not do in Excel - so I did them in Python :) Except as it >stands, the current python scripts have to be run via the command line. >Does anyone know how to allow interaction between Excel and Python via >EXCEL? > >I've looked on Mark Hammond's page, and I've figured out how to interact >with Python and Excel from PYTHON, but I can't seem to find the right info >for making the calls from the other end (i.e. from Excel). Any advice >would be GREATLY appreciated! > >PS - If anyone has any interest in this type of program, please let me know >- I'd be more than willing to release via the GPL or something to that >effect. Thanks Again... You can use COM to go both ways. Just create a COM server in Python and register it so that Excel can find it. Check out "Quick Start to Server side COM and Python" in the win32 documents. You will have to write a little VBScript on the excel side to interface, I think. ><{{{*> From klachemin at home.com Fri Jun 4 19:11:57 2004 From: klachemin at home.com (Kamilche) Date: 4 Jun 2004 16:11:57 -0700 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> <40c0b153$1_1@127.0.0.1> Message-ID: <889cbba0.0406041511.6f0eb10d@posting.google.com> "beliavsky at aol.com" wrote in message news:<40c0b153$1_1 at 127.0.0.1>... > I am no C++ expert, to put it mildly, but couldn't some of your problems > have been solved by using C++ instead of C? Uh. Yeah. I know C++ sort of, I redid all my base code in preparation for using it... and it decidedly DIDN'T mesh with my programming style! :-O I gave it up after finding one too many complexities and oddities in the language. I've used quite a few languages... C, C++, Fortran, Pascal, Assembler, COBOL, Basic, Visual Basic (6), Python, Javascript, and Hypercard. The ones I used most heavily were COBOL, HyperCard, Visual Basic, and C. The top 4 faves were VB, Python, HyperCard, and C, in that order. HyperCard is dead now, but it had its day. Of the remaining 3, I'm mainly using Python and C, since MS killed VB6. They all had their glories. Note the marked lack of C++ in the top 4. :-D You have to be superhuman, or maybe just supertwisted, to be productive in that language. :-O --Kamilche From beans at bedford.net Sun Jun 13 08:45:40 2004 From: beans at bedford.net (TomH) Date: 13 Jun 2004 05:45:40 -0700 Subject: Newbie array question References: <2d7af4f8.0406112032.4cb4438a@posting.google.com> Message-ID: <7135e36e.0406130445.7e7831e@posting.google.com> nhirsh2 at ieee.org (Neale) wrote in message news:<2d7af4f8.0406112032.4cb4438a at posting.google.com>... > My first task with Python is to scan multiple small text files and > "batch together" those records with a "5" or "6" in column 2, and then > save as a new file. The records are 256 characters. I know it sounds > like a homework problem, but it's not. > > My math brain wants to dump all the records into a big 2-D array and > sort on the second column. Then "compress out" all the records whose > second character isn't "5" or "6". Easy to say. > > Is this the right strategy for using Python? Does it even have a > "compress out" function? I must be missing something. Isn't this simply: read the records and write the ones you want: outf = open('of', 'w') for f in ['a','b']: d = open(f, 'r') for ln in d: if ln[1] == '5' or ln[0] == '6': outf.write (ln) From davidf at sjsoft.com Wed Jun 23 03:52:41 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 09:52:41 +0200 Subject: Using metaclasses to play with decorators. In-Reply-To: References: Message-ID: David MacQuigg wrote: > On Sun, 20 Jun 2004 14:48:23 -0400, "Colin J. Williams" > wrote: > > >>I have yet to wrap my mind around decorators. > > > Decorators are very simple. They are just a way to provide different > forms of methods, without introducing a new keyword, or some other > more awkward syntax. > > Say you wanted to define a method that didn't have 'self' as its first > argument. You could add a new keyword to the language: > > noself methodA(x,y): > return x + y > > Or you could add a "decorator" to the existing syntax: > > def methodA(x,y) [noself]: > return x + y > > Change 'noself' to 'staticmethod' and you have one of the current > proposals in PEP318. > > Don't get distracted by 'staticmethod' and other mumbo-jumbo > terminology, and you should have no problem with decorators. Aren't there other people around who would find staticmethod methodA(x,y): return x+y a clearer and more helpful syntax than def methodA(x,y) [staticmethod]: return x + y I've always wanted a method A(x,y): self.var += x*y which automatically declared self as an initial parameter... David From roeder at berg.net Fri Jun 11 08:16:54 2004 From: roeder at berg.net (=?ISO-8859-1?Q?Maik_R=F6der?=) Date: Fri, 11 Jun 2004 14:16:54 +0200 Subject: split In-Reply-To: <40C99CBD.6010707@struktur.de> References: <20040612151044.GA9619@mrna.tn.nic.in> <40C99B86.8060201@geochemsource.com> <40C99CBD.6010707@struktur.de> Message-ID: <40C9A2B6.9080907@berg.net> Hi! Joachim Bauch wrote: > an even faster way would be > > |>> s = 'another string' > |>> l = [ch for ch in s] > |>> l > ['a', 'n', 'o', 't', 'h', 'e', 'r', ' ', 's', 't', 'r', 'i', 'n', 'g'] Or shorter: >> s = 'some string' >> l = list(s) >> l >> ['s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'] Best regards, Maik R?der From hungjunglu at yahoo.com Wed Jun 9 18:57:45 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 9 Jun 2004 15:57:45 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> Message-ID: <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Alexander Schmolck wrote: > How do younger languages like IO make this point more forcefully than lisp, > smalltalk etc -- languages which have been around for decades? Double checked with Lisp just now. And Lisp did not allow me to redefine "if", "setq", "t", etc. In a sense, Lisp is not keywordless, whereas Io is truly keywordless. As I said, in Io even "if" and "while" are implemented as regular functions. In Lisp, you cannot intercept "if", "setq", etc. In Io, everything is interceptible. Therefore, Lisp seems not nearly as flexible as Io. If there are tricks in Lisp to intercept "if", "setq", etc. I'd like to know. Same if these limitations are specific to some particular implementations of Lisp. I greatly suspect that these limitations of Lisp are general, since Lisp does not naturally have prototype-based scopes like onion-skins, and overriding things like "if" could more easily create havoc. regards, Hung Jung From askari at addressNonValide.com Tue Jun 15 17:04:53 2004 From: askari at addressNonValide.com (Askari) Date: Tue, 15 Jun 2004 21:04:53 GMT Subject: Unbind initial bind on basic widget (text) References: Message-ID: Peter Otten <__peter__ at web.de> wrote in news:caevni$b0i$07$1 at news.t-online.com: > Askari wrote: > >> Do I can unbind the initial bind on basic widget? (ex.: the basic >> widget >> Text have the bind "" for the return to the first caracter >> of the line; but me I don't want this!) >> I try 'myText.unbind("")' but the bind is not >> remove. >> :-( > > I see two options. > > 1. Prevent the event from being propagated to the class. > > def breaker(*args): > return "break" > > mytext.bind("", breaker) > > 2. Unbind the event on the class level. > > mytext.unbind_class("Text", "") > >> N.B. I wan't disabled ALL initial bind (not just the "") > > Maybe you should just disable the widget? > > mytext["state"] = "disabled" > > Peter > > Thanks!! :-) From lbates at swamisoft.com Tue Jun 15 09:35:30 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 15 Jun 2004 08:35:30 -0500 Subject: searching strings using variables References: Message-ID: Your first attempt is searching for the characters '16' in a list of integers, which will never be found and you don't need regular expression overhead to do this. You might try. # list of items to search... mylist = ['5', '6', '16', '17', '18', '19', '20', '21'] # my variable I want to search with... myvar = '16' print mylist.index(myvar) or # list of items to search... mylist = [5, 6, 16, 17, 18, 19, 20, 21] # my variable I want to search with... myvar = 16 print mylist.index(myvar) on the second example you are searching for the characters 'myvar' in the same list of integers, which will never be found, unless you have something like: # list of items to search... mylist = ['5', '6', '16', '17', '18', '19', '20', '21', 'myvar'] print mylist.index('myvar') HTH, Larry Bates Syscon, Inc. "tgiles" wrote in message news:WNxzc.22798$Fd.18743 at twister.rdc-kc.rr.com... > Hi, all. Another bewildered newbie struggling with Python goodness. This > time it's searching strings. The goal is to search a string for a value. > The string is a variable I assigned the name 'myvar'. however, it > doesn't seem to be seeing it... Here's a snippet. > > import re > > # list of items to search... > mylist = [ 5 , 6 , 16 , 17 , 18 , 19 , 20 , 21 ] > # my variable I want to search with... > myvar = '16' > print re.search('myvar','mylist') > > ... just returns none. Tried it also with... > > mylist.index('myvar') > > to see if I could spook it out but I get a ValueError (not in list) so > it looks like it won't see it either. I did vague permutations trying to > make it work but no go. I'm thinking it may be one of those "forest for > the trees" things, i've been looking at it too hard. Any ideas? > > many thanks in advance! > > tom From Mike at DeleteThis.Geary.com Fri Jun 4 11:41:42 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 4 Jun 2004 08:41:42 -0700 Subject: heredoc and variables References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> Message-ID: <10c161nfembfq14@corp.supernews.com> flupke wrote: > 2) Consider following heredoc > > end_html=""" > """ > > I have to write it like this to avoid having an empty line added > above AND below the actual string when using it. > So this would produce the extra empty lines > > end_html=""" > > > """ > > I actually think that the last piece of code is more readable. Is > there a way to stop that behaviour or is there a kind of trim > function i can apply to get rid of the 2 extra lines? If you can live with the newline at the end of the text (which in most cases is what you want anyway), this is the cleanest way to do it: end_html = """\ """ Or, you can get rid of both newlines this way: end_html = """ """[1:-1] -Mike From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 16:42:56 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 22:42:56 +0200 Subject: if statement In-Reply-To: <3bv0e0torae2fmsb03ts3s47vpdhgbo9ve@4ax.com> References: <3bv0e0torae2fmsb03ts3s47vpdhgbo9ve@4ax.com> Message-ID: <2kbdr0Fd8iuU1@uni-berlin.de> Andrea Griffini wrote: > On Mon, 28 Jun 2004 22:59:30 +1000, "Ajay Brar" > wrote: > >>its the first time i amusing python and coming from a {} environment, tabs >>is a little hard to get used to. > > I come from {} too, but found moving to indentation really > a no problem except that one of the python editors I tried > messed up my code badly, probably because it was written > with a two space indent instead of the common 4. > > I abandoned tabs long ago: when it was standard (8) there > could be some use for the tab char, now it's just another > way to add *completely pointless* confusion. > > Anyway I forced myself to change to 4 space indent (even > if indeed seems to me a bit too much), and I abandoned > fancy editors so I'm back to the trustable VIM :-) ... it > may go eventually wrong when guessing the indent for next > line; but it will never ever dare to mess up my code. > > Actually my problem is that now I sometimes forget ";" > when working in C++ :-) The good thing about Python is that the semicolon an experienced C programmer mindlessly inserts does not produce an error ;) Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From grey at despair.dmiyu.org Thu Jun 3 22:35:23 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 02:35:23 GMT Subject: Why did no one invent Python before? References: Message-ID: On 2004-06-04, Hans Nowak wrote: > I would. Turbo Pascal, that is, not Perl. Of course, back then I didn't know > any better... :-) All I remember from those days was getting stuck on casting. Everything up until that point was easy but after that I just couldn't figure out how to make "1" into 1. Seemed, obvious to me. *sigh* Then again, I was 11 at the time so maybe my experience with the language is colored. I do know I still prefer Pascal (in general) to C (in general) but find tcc really neat! :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From hungjunglu at yahoo.com Wed Jun 9 21:45:56 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 9 Jun 2004 18:45:56 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> Message-ID: <8ef9bea6.0406091745.5f9e0aa3@posting.google.com> Jacek Generowicz wrote: > Python has many qualities, but let's stop kidding ourselves that its > current state is some sort of global optimum in the space of > programming languages. > > In spite of its many qualities, Python has a number of > shortcomings. Let's stop kidding ourselves that its shorcomings are > features. ---------- Totally agree. Two years ago or so, the Perl newsgroup/mailing-list overshadowed Python's newsgroup/mailing-list. Today, the opposite is true. When I started with Python, there was one single book, and it was not even available in most bookstore. Python has come a long way in popularity. However, some bad habits of Perl Mongers have been transplanted into the Python community. In particular, blind advocacy/worship, and refusal to hear/learn/see better features from other languages. In term of smartness or powerfulness, Python is only about average. Python is good because it kind of sits in the middle of many possible technological directions. But when you see comments from people that are bilingual in Python and other languages like Self/Io, Haskell, Lisp, etc., it's easy to see that Python is frankly kind of second-tier player, full of limitations and problems. regards, Hung Jung From peter at engcorp.com Fri Jun 18 20:57:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 20:57:12 -0400 Subject: Parse ASCII log ; sort and keep most recent entries In-Reply-To: References: Message-ID: Nova's Taylor wrote: > This is what I wound up using: Could I suggest part of my suggestion again? See below: > piddict = {} > for line in sourceFile: > pid,username,date,time = line.split() > piddict[pid] = (username,date,time) Here you are splitting the whole thing, and storing a Python tuple rather than the original "line" contents... > pidlist = piddict.keys() > pidlist.sort() > for pid in pidlist: > username,date,time = piddict[pid] > # next line seems amateurish, but that is what I am! > logFile.write(pid + " " + username + " " + date + "" + time + > "\n") Here you are writing out something that is exactly equal (if I read this all correctly) to the original line, but having to split the tuple and append lots of strings together again with spaces, the newline, etc. Why not just store the original line and use it at the end: for line in sourceFile: pid, _ = line.split(' ', 1) piddict[pid] = line and later, use writelines as Christos suggested, without even needing a loop: logFile.writelines(piddict.values()) The difference in the writing part is that you are sorting by pid, though I'm not clear why or if it's required. If it is, you could still loop, but more simply: for pid in pidlist: logFile.write(piddict[pid]) No splitting, no concatenating... -Peter From escalation746 at yahoo.com Thu Jun 17 13:45:21 2004 From: escalation746 at yahoo.com (robin) Date: Thu, 17 Jun 2004 18:45:21 +0100 Subject: very large dictionaries References: <2jbm1vFvh88vU1@uni-berlin.de> Message-ID: Matteo Dell'Amico wrote: >If you just need fast lookup, maybe cdb >(http://pilcrow.madison.wi.us/#pycdb) can be of use: two disk accesses >per lookup. I see that this allows duplicate keys and so may be exactly what is needed. I will check it out further. Thank you! -- robin From johng2001 at rediffmail.com Mon Jun 21 22:05:30 2004 From: johng2001 at rediffmail.com (John) Date: Mon, 21 Jun 2004 19:05:30 -0700 Subject: Spellcheck an application (from below) In-Reply-To: <40d74d9a$1@newsfeed.netlojix.com> References: <40d74d9a$1@newsfeed.netlojix.com> Message-ID: Evan McPeters wrote: > It is a database application that has a window where the user can write > letters to patients. > That is the area that I want to spellcheck. Any ideas how I can do this? > > Thanks again. > >> >>>I need to develop a program that will spell check a word processing > window >>>that is open in another application. I do not have access to the the API > or >>>any other code for this application, so I was hoping that the spell > checker >>>could simply do it's job on whatever the user's active window is. >>>Does this make sense. Does anyone have an idea about how to start this. >>What is this 'other application' ? Try http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117221 http://www.scriptfoundry.com/snake/snakespell/snakespell/ You could use COM if you are on Windows and the users will have MS Word installed on their system. There are other ActiveX components available on the web that you can try if users do not have MS Word installed. From 1048094008 at newsfeeds.com Wed Jun 23 23:16:49 2004 From: 1048094008 at newsfeeds.com (Nugget) Date: Wed, 23 Jun 2004 22:16:49 -0500 Subject: Getting the source of a remote webpage References: <6962d028.0406231847.48b00a0b@posting.google.com> Message-ID: On Wed, 23 Jun 2004 19:47:02 -0700, Ryan Kaskel wrote: > Is it possible to get the source of a remote webpage (just the > straight HTML) without anything too complicated (like COM, I just want > to write a simple script if possible) and write it to a file? For > example, is it possible to do something like os.system(....run > iexplorer.exe command....) with another command that automatically > opens the page? Thanks. import urllib f = urllib.urlopen(url) s = site.read() ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From me at here.there.nowhere Wed Jun 16 11:20:54 2004 From: me at here.there.nowhere (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 16 Jun 2004 17:20:54 +0200 Subject: Something simular to java's hsqldb for python?? References: <792ea523.0406160601.1b217d78@posting.google.com> Message-ID: <40d06556@news.mt.net.mk> > Is there some program that is simular to java's hsqldb > (http://hsqldb.sourceforge.net/). It is a relational database that can > easily be used within a small java program without installing a MySQL, > Postgresql etc. It is used within the same virtual machine whitout > installing anything extra. > > Is there somthing similar for python? sqllite has Python bindings, and you can access the DB from other languages also. -- ?????? The three Rs of Microsoft support: Retry, Reboot, Reinstall. From peter at engcorp.com Mon Jun 14 19:01:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 19:01:28 -0400 Subject: Searching for the best scripting language In-Reply-To: References: Message-ID: Lothar Scholz wrote: > On Mon, 14 Jun 2004 11:15:01 -0700 (PDT), Adelein and Jeremy > wrote: > > >>The answer to this search is not sh, its vastly improved younger >>brother Perl, nor even the OO-capable Ruby. The answer is a new >>language I am developing, called fortytwo. fortytwo is completely > > > > > A lot of text, but no url ? No url, and not even a smiley! (Hint hint) See also "The Hitchhiker's Guide to the Universe" and the answer to the problem of life, the universe, and everything. Lothar, read Jeremy's last paragraph again and then reconsider what he was saying in the first paragraph in light of that. :-) -Peter From fperez528 at yahoo.com Thu Jun 24 21:23:09 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 24 Jun 2004 19:23:09 -0600 Subject: Python Color Printing References: <889cbba0.0406240136.3a735356@posting.google.com> <40daabc1$0$10280$afc38c87@news.easynet.co.uk> <889cbba0.0406240637.17b7c3e0@posting.google.com> Message-ID: Kamilche wrote: > Peter Hickman wrote in message > news:<40daabc1$0$10280$afc38c87 at news.easynet.co.uk>... > >> There is a GNU tool called source-highlight that handles python. It will >> create a html file with the colour coding. You could then print the html >> file. > > Thanks, I've got one of those. But then, how do I handle adding > headers, footers, changing the window title to get rid of 'Microsoft > Internet Explorer', and automatically printing? That's the part where > it falls down on. > > If someone knew how to do that via Python, that'd work! :-) Sometimes, simple, old tools can be very handy: haar[~]> which codeps codeps: aliased to enscript -G2rjE --color -o !*.ps !*; gv !*.ps haar[~]> which codeprint codeprint: aliased to enscript -G2rjE --color !* This gives 2-up output, just remove the 2 option for single-page output. enscript is a wonderful tool, I use this all the time to print code (and it highlights many languages, not just python). Cheers, f From mrmakent at cox.net Thu Jun 10 10:12:24 2004 From: mrmakent at cox.net (Michael Kent) Date: 10 Jun 2004 07:12:24 -0700 Subject: Q: Making Python use no shared extension modules? Message-ID: I need to deploy Python 'frozen' apps to machine without a Python installation. I want to be able to deploy just the app's executable, without having to also ship/install any shared-library extensions for Python. To do this, I need to be able to build and install Python on my development machines (AIX 4.3, HPUX, Unixware, Linux) such that Python is one monolithic executable, without dependency on any shared libraries (other than standard OS shared libraries). In other words, no shared libraries for Python extension modules, I need all extension modules to be linked in via libpython*.a. I've been fighting with this for some time. There does not seem to be a clean/simple way of doing this short of hacking the Modules/Setup* files. What is the accepted way of doing this? Is there no configure command-line option to do this that works on all platforms? I'm aware of '--disable-shared'; it seems to only partially/unreliably work. From __peter__ at web.de Fri Jun 11 08:14:39 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 14:14:39 +0200 Subject: split References: <20040612151044.GA9619@mrna.tn.nic.in> <40C99B86.8060201@geochemsource.com> Message-ID: Joachim Bauch wrote: > Gandalf wrote: > | > | This way: > | > | >>> s = 'some string' > | >>> l = [] > | >>> for c in s: > | ... l.append(c) > | ... > | >>> l > | ['s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'] > | >>> > > an even faster way would be > > |>> s = 'another string' > |>> l = [ch for ch in s] > |>> l > ['a', 'n', 'o', 't', 'h', 'e', 'r', ' ', 's', 't', 'r', 'i', 'n', 'g'] >>> list("or even") ['o', 'r', ' ', 'e', 'v', 'e', 'n'] >>> Peter From kkto at csis.hku.hk Tue Jun 1 02:45:09 2004 From: kkto at csis.hku.hk (Isaac To) Date: Tue, 01 Jun 2004 14:45:09 +0800 Subject: API : constness ? References: Message-ID: <7ismdfydxm.fsf@enark.csis.hku.hk> >>>>> "Tim" == Tim Roberts writes: >>>> static const char * const kwlist[] = { "uri", "open_mode", >>>> "exclusive", "perm", NULL }; >>> Does this give any performance or size improvement? Tim> The data MAY be in a read-only segment, The strings like "uri", "open_mode", etc., are in read-only segment anyway, whether you add the "const" or not. On the other hand, kwlist cannot be in read-only segment, no matter you add "const" or not, since they are initialized not when you compile the module, but instead when you load the module (see below). Initialization at load time means modification of the memory location. Since the memory need to be modified (once, at load time), they cannot be mapped to memory from file directly, and accordingly they cannot be in read-only memory. Tim> but even assuming that it is, that doesn't do anything to reduce Tim> relocation or load time. This is absolutely correct. It is simply impossible to make relocations unnecessary, because the char* pointers stored in kwlist must point to the absolute addresses of the static strings, which cannot be determined until the python program actually loads the module (because, until then, we won't be able to tell what part of the address space is available). Regards, Isaac. From richie at entrian.com Wed Jun 23 06:50:40 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 23 Jun 2004 11:50:40 +0100 Subject: on TDD (was Re: how to become a really good Python programmer?) In-Reply-To: References: <8a6ba1da.0406180017.1948543f@posting.google.com> Message-ID: [Richie] > My suspicion is that 75% of the design of the module's API will > fall out of the way the tests are written [Peter] > I think it depends [...] but sometimes I've found nearly 100% > of the API and design falls out of the tests. Thanks for confirming. It's a bigger mind-shift than it first appears. -- Richie Hindle richie at entrian.com From chris.cavalaria at free.fr Sat Jun 5 06:03:27 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sat, 05 Jun 2004 12:03:27 +0200 Subject: Can python control complicated classes/objects written in C++ References: Message-ID: <40c19a6f$0$7954$626a14ce@news.free.fr> Bo Peng wrote: > Dear Python group: > > I am planning on an application that involves several complicated C++ > classes. Basically, there will be one or two big data objects and some > "action" objects that can act on the data. I would like to use a script > language to control the interaction between these c++ objects. > > I become interested in Python since it can load C++ objects and can even > extend C++ classes. However, I am not quite sure to what extent can > python do this. Ideally, I would like to have something like > > (pseudo code, not in python) > > data = new TData( option1=..., option2=...) > > action1 = new TAction(option1=range(1,10)...) > > action2 = new TSubAction(option1=sin(5),..., option2=...) > > data.run( action1, action2) > > data.print > > The benefits here is that I do not have to worry about user-input > (python handles functions like range(), and numeric/string operations > for me and send them to my objects), running logic (user create the > scripts) and need only focus on the objects themselves. It would be > better if users can easily extend TAction by themselves, through either > Python or C++. > > I am totally new to Python. I have read boost.python, python extension > document but still do not know exactly what to do. My questions are: > > 1. can Python fully read/write member data and run member functions of > my objects? > > 2. can python pass complicated objects (TAction) to another object > (TData)? > > 3. If python can not do this, I will have to create my own scripting > language. Given the above pseudo code, any suggestion on how to > implement it? I have googgled Qt Script for Application and many other > weird implementations but I either do not like the grammar of the script > language or the huge overheads. > > Many thanks in advance. > > Bo You can try the Python module in Boost ( http://boost.org/ ) Here's a direct link : http://boost.org/libs/python/doc/index.html From michele.simionato at poste.it Thu Jun 17 02:13:21 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 16 Jun 2004 23:13:21 -0700 Subject: datetime, calendar, time intervals Message-ID: <95aa1afa.0406162213.3cf3d7f7@posting.google.com> Strangely enough, I never needed the datetime and calendar module before, so I just looked at them today. I am surprised I don't easily find an interval function such this: import datetime def interval(day, lastday, step): # not necessarely restricted to days while day < lastday: yield day day += step firstday = datetime.date(2004, 05, 01) lastday = datetime.date(2004, 06, 01) oneday = datetime.timedelta(1) for day in interval(firstday, lastday, oneday): print day Did I overlook something? Has an iterator over time intervals been taken in consideration for addition in the standard library? (or maybe is already there ...) Also, the calendar module seems to be giving just the Unix "cal" functionality which is a bit poor, I would have expected more ... Just curious, Michele Simionato From bjg at network-theory.co.uk Thu Jun 3 09:01:07 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 03 Jun 2004 14:01:07 +0100 Subject: Optimizing multiple dispatch References: Message-ID: <87pt8gbxt8.fsf@network-theory.co.uk> Jacek Generowicz writes: > Profiling suggests that "tuple(map(type, args))" is taking a > significant proportion of time in certain critical loops. > Do you have any suggestions about how to make in run faster? (Either > by optimizing "tuple(map(type, args)", or by using a completely > different organization for the whole thing. If the arguments inside the loop have fixed types, then maybe you could have a method to get the reference to the function (once) outside the loop. This would be like methodForSelector in Objective-C. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From google at prodigycomputing.com Sat Jun 26 06:22:01 2004 From: google at prodigycomputing.com (Paul Keating) Date: 26 Jun 2004 03:22:01 -0700 Subject: Python COM - limit on size/complexity of returned object? References: <51f8958a.0406240327.1b26a76f@posting.google.com> <5155aad2.0406250612.29d5039b@posting.google.com> Message-ID: <51f8958a.0406260222.72c9caee@posting.google.com> kveretennicov at yahoo.com (Konstantin Veretennicov) wrote in message news:<5155aad2.0406250612.29d5039b at posting.google.com>... > Well, I did some testing with python 2.3 (that's what I have). > Not sure if it will cheer you up, but I had no problems. Thanks for the pointer. I tried it on another machine with 2.3 and that works with no problems. And I made some further discoveries on the 2.2 side: the problem isn't a limit on the size of the returned object, it's cumulative. I amended GetProfileComponentMatrixEx() to return the first n rows of the matrix, to find out what the limit was: like this >>> print len(GetProfileComponentMatrixEx(10)) 10 >>> print len(GetProfileComponentMatrixEx(40)) 40 >>> print len(GetProfileComponentMatrixEx(80)) But trying it repeatedly I found that I could only execute the following line once: it crashed calling it with an argument of 40 the second time: >>> print len(GetProfileComponentMatrixEx(40)) 40 >>> print len(GetProfileComponentMatrixEx(40)) And then I tried this repeatedly: >>> print len(GetProfileComponentMatrixEx(10)) and -- surprise! -- it failed about the 7th or 8th invocation. So, now there are two possibilities. 1. It's a 2.2 problem that is fixed in 2.3 (though I looked in Sourceforge for the bug reports and this did not show up there). 2. It's a side-effect of the module I'm importing to do the actual work. On the machine running 2.3, I had to write a stub to represent this module, because it is a home machine that can't see the work server where the data is. If the DLL is at fault, I'm going to have a hard time convincing the vendor that they have to fix it. If I were them, I'd be sceptical. The DLL is loaded by the import statement, but in this test it is never called. It's hard to see what it's initialization code could possibly be doing to break pythoncom. From dmq at gain.com Fri Jun 11 17:15:50 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 11 Jun 2004 14:15:50 -0700 Subject: Can someone explain this weakref behavior? References: Message-ID: On Fri, 11 Jun 2004 15:38:29 -0400, "Tim Peters" wrote: >[Tim Peters] >>> That will pass under CPython today, but there's no general guarantee >>> about exactly when a weak dict will notice that keys (or values) have >>> become unreachable by strong references. > >[David MacQuigg] >> OUCH!! We just built a module that uses weak references to keep a >> "robust count" of instances in various classes. The claim is that this >> is more robust than simply incrementing and decrementing class variables >> using __init__ and __del__. The module seems to be working OK, >> immediately deleting the weak reference as soon as all references to the >> corresponding instance are deleted. > >Then it must be the case that you're running CPython, and that these >instances aren't involved in cycles. Because CPython primarily uses >reference-counting to recycle garbage, its behavior is predictable in the >absence of cycles. I'm not worried about cyclic references, but it is something to keep in mind. >CPython's use of reference counting is an implementation detail, and that >internal weakref lists are traversed "immediately" upon an object's refcount >reaching 0 is also an implementation detail. Nothing in the language >definition guarantees these behaviors. > >> If I understand you correctly, there is some chance that a future >> implementation of Python may have the weak references "out-of-sync" with >> the actual count of live instances. Is that a remote possibility, or >> something quite likely to occur? > >Well, it's been the case for a long time in JPython. I judge the odds of it >changing in CPython as slim. I personally wouldn't worry about it ever >changing in CPython. If a PyPy- or Parrot-based implementation of Python >takes off, behavior will depend on its implementation details. > >> I have to decide now whether to rip out some risky code. >> >> Is there a good way to track the count of instances? > >If you want it enough, you can build Python in a mode that tracks this >automatically (see the discussion of COUNT_ALLOCS in Misc/SpecialBuilds.txt >-- for each distinct type object, the total # of allocations, # of >deallocations, and highwater mark (max(#alloc - #dealloc) over time) are >maintained in a COUNT_ALLOCS build). > >> If not, would it make sense to request a guarantee on the current >> behavior of weak references? Maybe it could be an option, assuming there >> is some performance penalty, an option to be used when accuracy is more >> important than speed. > >You can request anything you can dream up . If it's something your >business needs, the only way to guarantee it is to get involved in Python >development deeply enough so that, if worse comes to worse, you can maintain >your own Python implementation. That's unreasonably paranoid in my >estimation, but it's a judgment call. Seems like we could do this more easily with a function that lists instances, like __subclasses__() does with subclasses. This doesn't have to be efficient, just reliable. So when I call cls.__instances__(), I get a current list of all instances in the class. Maybe we could implement this function using weak references. If I understand the problem with weak references, we could have a WeakValueDictionary with references to objects that actually have a refcount of zero. There may be too many entries in the dictionary, but never too few. In that case, maybe I could just loop over every item in my WeakValueDictionary, and ignore any with a refcount of zero. def _getInstances(cls): d1 = cls.__dict__.get('_instances' , {}) d2 = {} for key in d1: if sys.getrefcount(d1[key]) > 0: d2[key] = d1[key] return d2 _getInstances = staticmethod(_getInstances) I'm making some assumptions here that may not be valid, like sys.getrefcount() for a particular object really will be zero immediately after all normal references to it are gone. i.e. we don't have any temporary "out-of-sync" problems like with the weak references themselves. Does this seem like a safe strategy? -- Dave From lunarium at comail.ru Fri Jun 11 03:59:58 2004 From: lunarium at comail.ru (Sergey Krushinsky) Date: Fri, 11 Jun 2004 11:59:58 +0400 Subject: Anonymous file closing Message-ID: <40C9667E.2000407@comail.ru> Hello all, If I need to read a string from a file and use syntax like: text = open(filename, 'r').read() ... is the file object ever closed? With best regards, Sergey From randall at tnr.cc Wed Jun 16 02:06:41 2004 From: randall at tnr.cc (Randall Smith) Date: Wed, 16 Jun 2004 01:06:41 -0500 Subject: how to become a really good Python programmer? Message-ID: I've been programming in Python for about 2 years. I think it offers the best combination of simplicity and power of any language I have explored. As I write more and larger and complex programs, I need to code better. By better I mean clearer, cleaner, more efficient and maintainable. As the subject states, I want to become a really good Python programmer. I learn most everything from random examples and experience and that's good, but now I would like some sound, directed guidance. Following Guido around would be ideal, but I will settle for a good book. Any recommendations for learning resources? Randall From rogerb at rogerbinns.com Tue Jun 29 13:59:09 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 29 Jun 2004 10:59:09 -0700 Subject: win32 pyserial requires javax.comm for py2exe? References: Message-ID: Grant Edwards wrote: > I'm trying to package a small Python program using py2exe. > > Everything works fine until I add an "include serial", then > py2exe fails because > > The following modules appear to be missing > ['javax.comm'] > > Apparently serial.py imports a both the posix and java versions > of things even on a win32 platform? It is a "feature" of modulefinder which is used by py2exe, cx_Freeze and several other freezing tools. modulefinder imports your main script and then scans the bytecode for all imports. It has no idea if the imports are in conditionals and doesn't care. eg if you do this: if False: import specialsauce Then it will always try to add the specialsauce module since that is visible in the bytecode. It isn't an error for the module to be missing as you saw, but there won't be any issue if you then run the frozen program. Similar things happen for other modules. For example if you import urllib (IIRC) you will find that modulefinder also includes the SSL binary module even though you may never use SSL. Again, this is because it was in the bytecode. I recommend reading the source for the modulefinder module to get a better understanding of what is happening. So ultimately it is all harmless and there will be no difference between running from source and running from frozen. If it bugs you at the cosmetic level then you can exclude packages in the arguments to your freezing tool, as well as delete any shared libraries that are sucked in you don't want (eg an SSL one in the earlier example). Roger From ryan at ryankaskel.com Thu Jun 24 01:03:04 2004 From: ryan at ryankaskel.com (Ryan Kaskel) Date: 23 Jun 2004 22:03:04 -0700 Subject: Obtaining Webpage Source with Python Message-ID: <6962d028.0406232103.6f5d9f7f@posting.google.com> How can I obtain the source of a remote webpage (e.g. http://www.python.org/index.html) using Python? Something like: pyPage = open('http://www.python.org/index.html',r).read() Obviously that won't work but how can I do something to that effect? Thanks, Ryan Kaskel --I posed this before but it seems it is not showing up... From christopher at baus.net Thu Jun 3 04:36:45 2004 From: christopher at baus.net (Christopher Baus) Date: Thu, 3 Jun 2004 01:36:45 -0700 (PDT) Subject: question regarding Guido's main article Message-ID: <4042.66.215.139.141.1086251805.squirrel@mail.baus.net> Hi, I'm new to Python and am learning the languge for writing test scripts for C++. I just finished reading this: http://www.artima.com/weblogs/viewpost.jsp?thread=4829 article. Coming from C++ I am a bit confused about the relationship of the interpreter to main. I think I understand the __name__ variable, it just doesn't work as expected. I implemented a script using the form described in the article. The then did: > python >>> execfile("myscript.py") This immediately called my main function, which should have only been called if __name__ == "__main__". What I expect was that __name__ would be something other than __main__ and I would be put back at the prompt for instance... >>> execfile("myscript.py") >>> foobar = "foo and a bar" >>> main(foobar) That way I could pass any arguments to main or do processing before calling main. The article mentions calling main from the interactive prompt, I just don't see how to do this. Thanks for your help... -- Christopher Baus http://www.baus.net/ Tahoe, Wine, and Linux. What more could you ask for? From jason at tishler.net Tue Jun 15 16:39:00 2004 From: jason at tishler.net (Jason Tishler) Date: Tue, 15 Jun 2004 16:39:00 -0400 Subject: Enthought Python + Cygwin In-Reply-To: References: Message-ID: <20040615203900.GA5648@tishler.net> Roger, On Tue, Jun 15, 2004 at 10:32:14AM -0700, RMJ wrote: > After installing Enthought's python and typing 'python' from within > cygwin the program hangs with no output. I do not remember this being > the case with earlier versions of Enthought python. Is this version > not compatible with cygwin? Or, is there some configuration file that > needs changing? It does run successfully with 'python somecode.py' > -but without printing out intermediate results. There are some known "tty" issues when running native Win32 programs under Cygwin. They typical manifest themselves under rxvt and (IIRC) when CYGWIN=tty. Try using bash (instead of rxvt) and CYGWIN=notty. BTW, Cygwin Python does not have any of these issues. If you don't need any Win32 Python features, then you may want to use this version instead. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From grey at despair.dmiyu.org Thu Jun 3 13:22:55 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 17:22:55 GMT Subject: python vs awk for simple sysamin tasks References: Message-ID: On 2004-06-03, Matthew Thorley wrote: > It is A LOT longer than the one liners (obviously) but it has way more > functionality. With a little tweaking you could easily do all sorts of > other useful things. I'm sure utils like this already exist out there > whether written in python or not. Also it can be made part of a larger project with relative ease. :) > Another question. The example my friend gave me takes the user name as > an argument not the uid. Does any one know how to convert usernames to > uids and vice versa in python ? Please also comment on the script, any > thoughts on simplification ? I'd just do a quick pass over the passwd file but then many times I'm blisfully unaware of things already coded to do the work I'm after. I mean my first stab at iterating over the file system didn't use os.path.walk(). :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From ods at strana.ru Thu Jun 3 05:23:05 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 3 Jun 2004 13:23:05 +0400 (MSD) Subject: Triple quoted repr In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE018EFF90@au3010avexu1.global.avaya.com> Message-ID: On Thu, 3 Jun 2004, Delaney, Timothy C (Timothy) wrote: DTCT> > > I need a way of writing strings or arbitrary Python DTCT> code that will DTCT> > > DTCT> > > a) allow the strings to be read again unchanged (like DTCT> repr) DTCT> > > b) write multiline strings as multiline strings DTCT> instead of escaping DTCT> > > the \n's. [...] DTCT> Perhaps something like: DTCT> DTCT> s = repr("'''multi\n'line'\nstring'''") DTCT> s = "'''%s'''" % (s[1:-1].replace('\\n', DTCT> '\n').replace("'''", DTCT> "\\'\\'\\'"),) DTCT> DTCT> which changes \n to a linefeed, \r to a carriage return, DTCT> and ''' to an DTCT> escaped form (in case you have a triple-quoted string with DTCT> the same DTCT> quote character). This fails for some strings, e.g.: >>> s = repr("'''multi\n'line'\nstring''") >>> s = "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''", "\\'\\'\\'"),) >>> print s '''\'\'\'multi 'line' string''''' >>> eval(s) "'''multi\n'line'\nstring" A better solution: >>> def trepr(s): ... return "'''"+'\n'.join([`l+'"'`[1:-2] for l in s.split('\n')])+"'''" ... >>> s = trepr("'''multi\n'line'\nstring''") >>> print s '''\'\'\'multi \'line\' string\'\'''' >>> eval(s) "'''multi\n'line'\nstring''" Or you can improve your solution to handle quotes properly at the begining and the end of string. -- Denis S. Otkidach http://www.python.ru/ [ru] From tim.one at comcast.net Thu Jun 10 19:56:16 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jun 2004 19:56:16 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <2is27mFqeen8U1@uni-berlin.de> Message-ID: [Claudio Grondi] > According to latest news the largest known prime is: > 2**24036583 - 1 > (right?) > > Do someone of you know how long would it take on a 2.8 GHz Pentium 4 > machine to write a _decimal_ form (hexadecimal form can be written in > less than one second) of this prime to a file and what should be the > Python code to use for it? binary -> hex conversion takes time linear in the number of bits (Python longs are stored internally in a form of binary representation). binary -> decimal conversion takes time quadratic in the number of bits, so is an enormously slower process for large numbers. You've got about 7 million decimal digits here. That's a lot . You could estimate the required time by measuring how long it takes to print smaller decimal numbers, then approximately quadruple the time for each doubling of the number of decimal digits. If you only want the first or last N decimal digits, there are reasonably efficient ways to do that for small N. For example, here are the last 6 digits, in much less than an eyeblink: >>> print pow(2, 24036583, 1000000) - 1 969407 >>> In more than an eyeblink, here's a way to print it "from the right", 6 digits at a time: >>> x = 2**24036583 - 1 >>> while x: ... x, r = divmod(x, 1000000) ... print ("000000" + str(r))[-6:], ... 969407 882733 436921 915067 118412 031269 800556 687039 526858 ... The digits come faster the longer it runs, but you're still going to wait a long time for more than a million 6-digit blocks to get displayed. From klachemin at home.com Sat Jun 26 17:58:32 2004 From: klachemin at home.com (Kamilche) Date: 26 Jun 2004 14:58:32 -0700 Subject: Is there a more elegant way to do this? Message-ID: <889cbba0.0406261358.6bc18e1d@posting.google.com> ''' Is there a more elegant way of doing this? I would like to have the arguments to pack automatically taken from lst. ''' def pack(self): lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \ 'green', 'blue', 'size', 'rotate', 'translucency'] return struct.pack(' Message-ID: jfouhy at paradise.net.nz (John Fouhy) wrote in message news:... > So I've got a horizontal scale widget in my GUI. When I click the > mouse in the area to the right of the GUI, the scale advances by 1. > > 13 > +-------------------------+ > |<| [===] X |>| > +-------------------------+ > > || > \/ > > 14 > +-------------------------+ > |<| [===] |>| > +-------------------------+ > > I want to change this, so it jumps by a larger amount (and likewise if > I click to the left of the slider). > > Any clues? > (setting 'bigincrement' only works for CTRL-left / CTRL-right when the > widget has keyboard focus) You can address the part of the scale widget you clicked on with event.x/event.y, so maybe something like this might do what you want (untested): var = IntVar() var.set(0) sb = Scrollbar(master, variable=var) sb.bind('<1>', jump) def jump(event): if sb.identify(event.x, event.y) == 'trough1': var.set(var.get()-5) return 'break' elif sb.identify(event.x, event.y) == 'trough2': var.set(var.get()+5) return 'break' I hope this helps Michael From stephen.no at spam.theboulets.net.please Fri Jun 25 00:27:27 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Thu, 24 Jun 2004 23:27:27 -0500 Subject: Cut and paste to X clipboard? Message-ID: Does anyone have a code sample for cutting and pasting to the X-clipboard in python? I'm actually using xorg-x11-6.7.0 under kde 3.2.3, so either the X clipboard or the kde clipboard would work fine. Thanks. -- Stephen If your desktop gets out of control easily, you probably have too much stuff on it that doesn't need to be there. Donna Smallin, "Unclutter Your Home" From jzgoda at gazeta.usun.pl Tue Jun 22 17:05:33 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 22 Jun 2004 21:05:33 +0000 (UTC) Subject: FFT with Python References: Message-ID: Satish Chimakurthi pisze: > Did anyone compute FFT - Fast Fourier Trans using Python ? I am > looking for a simple Python package which can do spectral analysis for > me. Can someone help me get such a package ? Numeric has it. -- Jarek Zgoda http://jpa.berlios.de/ From eurleif at ecritters.biz Thu Jun 24 03:58:01 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 24 Jun 2004 03:58:01 -0400 Subject: Classic and New Style Classes? In-Reply-To: References: Message-ID: <2jvfs8F15rq6hU1@uni-berlin.de> Chris S. wrote: > I'm generating the source of an object from a list of objects. Therefore > I need to determine if the object is a class definition (i.e. 'def > something(whatever):') or a class instance (i.e. 'somename = > somethingelse()'). I'm assuming you meant 'class something(whatever):' rather than def. If so, this should work: >>> class Foo(object): ... pass ... >>> isinstance(Foo, type) True >>> isinstance(Foo(), type) False From lars at post.cz Tue Jun 29 13:03:17 2004 From: lars at post.cz (Lars) Date: Tue, 29 Jun 2004 19:03:17 +0200 Subject: embedded python? In-Reply-To: References: Message-ID: Hi, Python (at least version 1.something) was running fine on my Psion 5mx (36 Mhz ARM, 16MB RAM). No problem. Jirka Alexander May wrote: > Hi, > > I love Python! I've been using it for a couple of years now and have found > it to be a highly productive language. I evangelize it to my developer > friends and am probably responsible for the sale of at least 10 Alex > Martelli books. I am now in the fortunate position of being able to use > Python for a large project, and as such I have a question. > > We are developing a distributed application running on approximately six > thousand nodes with somewhat limited hardware resources. Our hardware > target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected > specific hardware yet; the hardware target is what we are trying to fit into > based on price constraints. Each device needs to be able to handle about 2 > kbs (yes kilo, not mega) worth of network traffic. > > I intend to a least prototype the system in Python. It would be great if we > could we could use Python in production by embedding it in the hardware. My > question is does anyone have any real world experience using python in an > embedded system? Two general categories of questions: > > 1) Are there any embedded Pythons out there? The nodes will likely be > running some form of Linux, but I don't particularly feel like devoting > resrouces to porting python. Any embedded Linuxes supporting Python? > Thoughts in general? > > 2) What are the resource requirements of Python? How much overhead do the > network related modules add? Obviously I'll be able to determine our > application's resource usage once the prototype is written, but I curious > about other people's past experience. > > In short, is embedding python realistic? > > Thoughts and comments are greatly appreciated! > > Thanks, > Alex > > From bnet at ifrance.com Tue Jun 1 14:47:51 2004 From: bnet at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Tue, 01 Jun 2004 20:47:51 +0200 Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> <7ioeo3ydqu.fsf@enark.csis.hku.hk> <40BCAED7.533B8827@alcyone.com> Message-ID: Le Tue, 01 Jun 2004 09:29:11 -0700, Erik Max Francis a ?crit?: > Isaac To wrote: > >> This is not quite right. A string literal is always put into >> read-only >> memory, no matter whether you specify const or not. true. but the pointer to it isn't and i was talking of a const char * kwlist[] { } obvious optimization is to declare kwlist as static. but when the module is loade, kwlist gets initialize. adding another const tags the whole kwlist as const and then totally readonly. therefor, your compiler is able to store kwlist (the array) in a RO segment. From imbosol at aerojockey.invalid Thu Jun 10 02:48:00 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 10 Jun 2004 06:48:00 GMT Subject: Passing file descriptors References: Message-ID: Josiah Carlson wrote: > I've been working on this for more hours than I'm willing to admit, > perhaps someone here can help me make it happen. When I first saw the subject, I was about to point out that you had the wrong newsgroup: you want comp.lang.perl.misc I see you were talking about something else though. > This us using Python 2.3.3 > - I do have access to a SunOS 5.8 machine, and the script at the end > of this email works. > - I need it to work on linux kernel 2.4.x. > > > I'm trying to write the equivalent of what the author calls "ringd" > described in the below article, and use it with python 2.3.x on linux 2.4: > http://www.remote.org/jochen/work/pub/zero-downtime.pdf > > > The script that I provide at the end of this post is a variation of one > posted in this thread: > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=7t5i40%241pn%241%40nyheter.chalmers.se&rnum=8 > > There is a C version listed later in that article, but I've not yet > tried it out. > > Certainly I need a two things: > 1. Unix domain socket, local socket (standard socket connected locally), > or pipe > 2. sendmsg/recvmsg, fcntl.ioctl, or equivalent file descriptor manipulation > > In the script listed at the end of this post, I use a file descriptor > pair returned by os.pipe(), which should be sufficient. I also use > fcntl.ioctl(). > > > As stated previously, this works properly on SunOS 5.8: > jcarlson at synergistic-envision% python2.3 fdpass.py > Parent ioctl() returned 0 > #!/usr/pd/bin/python > jcarlson at synergistic-envision% > > It does not work on the linux machine I'm testing it on: > [jcarlson at dev jcarlson]$ python fdpass.py > [Errno 22] Invalid argument > Traceback (most recent call last): > File "fdpass.py", line 58, in ? > ret = fcntl.ioctl(pRead, fcntl.I_RECVFD, s) > IOError: [Errno 22] Invalid argument > [jcarlson at dev jcarlson]$ > > Seemingly this is because I_SENDFD/I_RECVFD is not properly implemented > on linux 2.4, but maybe I'm doing something wrong. > > I've also tried using SCM_RIGHTS as per this thread: > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=78c7ca81.0402110402.11eb957d%40posting.google.com > > It is not defined in python's fcntl module, but I did find the C > definition in the linux /usr/include/bits/socket.h... > SCM_RIGHTS = 0x01, /* Transfer file descriptors. */ > > So I passed the integer 1 manually, on both linux and SunOS 5.8 and got > exceptions like I normally do on linux. Last I checked, you have to use a Unix-domain socket to do this in Linux. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From dmq at gain.com Wed Jun 16 06:43:08 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 16 Jun 2004 03:43:08 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: On Sat, 12 Jun 2004 03:22:23 GMT, Mediocre Person wrote: >Well, after years of teaching grade 12 students c++, I've decided to >make a switch to Python. Excellent choice. > >Why? > > * interactive mode for learning > * less fussing with edit - compile - link - run - debug - edit - >compile - link - run -..... The IDLE environment, included with Python, is perfect for interactive learning (and for serious work later). It's a minimal environment, but it has everything I need. It has no GUI builder, but I don't miss that because I use Qt Designer when I need a GUI. > * lots of modules > * I was getting tired of teaching c++! Bored teacher = bad instruction. > * thought about tcl/tk but it's just too different syntactically >(for me, not my students!) after so much time with languages like >c++/ada95/pascal/BASIC/Fortran, etc. I looked at tcl/tk before discovering Python. I've never looked at it since. > * it appears to be FREE (which in a high school environment is >mightily important) from both python.org or activestate.com. I think I >like activestate's ide (under Win98) a bit better than idle, but your >comments/suggestions? I haven't looked at Activestate, but it may be the right choice if you are using Windows. Qt Designer is free only on Linux. I think there is an educational license for Windows, but you might want to check on that. http://www.trolltech.com >I've decided to give John Zelle's new book a try as a student >textbook--it's as good an introductory CS book in any language I've >seen. I've done a couple of small projects with tkinter, like what I >see, and would like to introduct my students to it, although Zelle >doesn't make use of it in his text. I haven't seen Zelle's book, but I would think the best book for a one-semester course would be Learning Python, 2nd ed. My only problem with LP2E is that I need something shorter because I have only a few weeks in a course on circuit-design tools. I've written a shorter presentation of Python OOP for engineering students. It may be too short for high school students, but you are welcome to use it. I'm thinking of expanding it to a larger audience by keeping the basic presentation short, but adding more simple examples and exercises. Your comments would be appreciated. http://ece.arizona.edu/~edatools/Python/ >So, what pitfalls should I look out for in introducing Python to >students who have had a year of Visual BASIC? I used VB for many years, but never really learned it. It has always been just a way to get something simple done quickly. Now that Python has assumed that role, about the only thing I would use VB for is macros in an Excel spreadsheet. I would think having a year of VB prior to Python would be an advantage, in that the students have at least worked with computers and simple programs. The problems might be an expectation of being able to do instantly in Python what was done with the GUI builder in VB. You will need to avoid long discussions of syntax, and focus as early as possible on interesting examples. From your later posts, it sounds like you already have some good examples in mind. I would be interested in following your progress in developing this course. Do you have a website? -- Dave ************************************************************* * * David MacQuigg, PhD * email: dmq at gain.com * * * IC Design Engineer * phone: USA 520-721-4583 * * * * Analog Design Methodologies * * * * * 9320 East Mikelyn Lane * * * * VRS Consulting, P.C. * Tucson, Arizona 85710 * ************************************************************* * From fishboy at spamspamspam.com Sun Jun 6 02:19:26 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 06:19:26 GMT Subject: Python 2.3.3 signals, threads & extensions: signal handling problem References: Message-ID: On Thu, 3 Jun 2004 14:48:05 +0200, "Holger Joukl" wrote: >Hi, >migrating from good old python 1.5.2 to python 2.3, I have a problem >running a program that features some threads which execute calls to >an extension module. >Problem is that all of a sudden, I cannot stop the program with a keyboard >interrupt any more; the installed signal handler does not seem to receive >the signal at all. >This happens both if I rebuild this extension using python 2.3 >headers/library >and if I simply use the old extension (ignoring the API version warnings >:-) > >Any hints? >Btw this is a sun sparc solaris 6 box, python 2.3.3. > >G > Holger http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&q=threads+signals&meta=group%3Dcomp.lang.python.* Looking at this search leads me to believe: 1. Threads + signals = bad 2. at some point things were changed to send all signals to the main thread. (python) Which leads me to believe that your signal handler is in a sub-thread? hth, ><{{{*> From mickel at csc.fi Fri Jun 4 07:34:26 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Fri, 4 Jun 2004 14:34:26 +0300 (EEST) Subject: Which is the most mature Soap module? In-Reply-To: <040601c44a20$ffc0c990$5b0aa8c0@cxodt03> References: <040601c44a20$ffc0c990$5b0aa8c0@cxodt03> Message-ID: > If you are working with Windows, you can use the excellent WebServices > support in .NET. Unfortunately, I need to get the software to work on both Linux and Windows. Moving to .NET now would lead me into problems in other areas, I assume ... I have narrowed down my problem to the HTTP header. I need a way of accessing the HTTP header of the SOAP message that is sent to the server from my client. More specifically, I need to add a line such as: Cookie: hotpageauth=user 1234567890 blablablablabla; path=/; expires=date; domain=.csc.fi; secure; to the HTTP header. Then the web server will allow access to the soap server that takes care of parsing and handling the actual SOAP message. So any ideas on how to fiddle with the HTTP header of a SOAP message being sent from SOAPpy? The SOAP::Lite module in Perl takes care of that so nicely ... /Mickel > > To access this from Python, you can use one of the many .NET extensions > for Python. > > http://www.python.org/wiki/pub/PyConChetanGadgil/attachments/PyCON%20Pap > er%20on%20%22.NET%20for%20Python%22.htm > > http://www.zope.org/Members/Brian/PythonNet/index_html > > > With these, you can let everything be done from Python, in .NET, such > as: > 1) WSE > 2) HPPTS > 3) Transparent client stubs for webservices > > If needed, you can search online for Microsoft's documentation for > webservices from .NET. > > > > Regards > Chetan > > > "Contrariwise," continued Tweedledee, "if it was so, it might be, and if > it were so, it would be; but as it isn't, it ain't. That's logic!" > -- Lewis Carroll, "Through the Looking Glass" > > > > -----Original Message----- > > From: > > python-list-bounces+cgadgil_list=cxoindia.dnsalias.com at python. > > org > > [mailto:python-list-bounces+cgadgil_list=cxoindia.dnsalias.com > > @python.org] On Behalf Of Mickel Gr?nroos > > Sent: Friday, June 04, 2004 3:57 PM > > To: John J. Lee > > Cc: python-list at python.org > > Subject: Re: Which is the most mature Soap module? > > > > > > The following is a rather long message. Here is a summary of > > my questions > > below: > > > > 1. ZSI fails on a TypeError when using ZSI.ServiceProxy, why? > > > > 2. Is there a way to use cookie authentification with SOAPpy > > (client-side)? > > > > > > On Tue, 1 Jun 2004, John J. Lee wrote: > > > > > Mickel Gr?nroos writes: > > > > > > > To the heart of the matter: Which of the available Soap > > modules is > > > > best fitted for client side soap messaging? I have an > > upload service > > > > (written in Perl) that I want to use from a Python > > application. What > > > > I want to do is send base64 encoded files via Soap to this upload > > > > service which is on a SSL encrypted server. I cannot really grasp > > > > the current development status > > > > > > IIRC, ZSI is. Certainly there is no solid WSDL implementation. > > > > I downloaded and installed both ZSI (1.5) and SOAPpy (0.11.4) > > both from . ZSI only > > required PyXML (0.8.3, from > > ) to be available, SOAPpy > > needed PyXML as well as fpconst (0.7.0, from > > > pconst/>) > > > > My problem concerns doing two things: > > > > 1. First, I need to log in at a secure server. In return I > > get a cookie that functions as user authentification. > > > > 2. Second, I need to upload a local file to a specific place > > on the server using the cookie as authentification. > > > > I got the login part working nicely using SOAPpy: > > > > >>> import SOAPpy > > >>> server = > > >>> SOAPpy.WSDL.Proxy("https://hotpage.csc.fi/log/soap.phtml?wsdl") > > >>> cookie = server.login("myusername", "secretpass") > > >>> > > > > Whereas ZSI failed on a TypeError: > > > > >>> server = > > >>> ZSI.ServiceProxy('https://hotpage.csc.fi/log/soap.phtml?wsdl', > > ... use_wsdl=True) > > >>> cookie = server.login(username='myusername', passwd='secretpass') > > Traceback (most recent call last): > > File "", line 1, in ? > > File > > "/usr/local/lib/python2.3/site-packages/ZSI/ServiceProxy.py", > > line 278, in __call__ > > return self.parent()._call(self.__name__, *args, **kwargs) > > File > > "/usr/local/lib/python2.3/site-packages/ZSI/ServiceProxy.py", > > line 83, in _call > > nsdict=self._nsdict, soapaction=soapAction, > > requesttypecode=request) > > File > > "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 209, > > in Send self.h.connect() > > File "/usr/local/lib/python2.3/httplib.py", line 960, in connect > > sock.connect((self.host, self.port)) > > File "", line 1, in connect > > TypeError: an integer is required > > >>> > > > > Any ideas what this might be? I gather I would need to set > > the port to 443 somewhere, but I can't find the right place. > > > > > > The second part, i.e. the upload, is trickier. Using > > SOAP::Lite in Perl, one can specify a cookie to use for > > authentification, but I can seem to find that in the > > documentation of SOAPpy. So how do I do cookie > > authentification with SOAPpy (or ZSI for that matter)?? > > > > Here is the Perl SOAP::Lite code that does the trick (copied from > > ): > > > > use SOAP::Lite; > > use HTTP::Cookies; > > > > my $soap = SOAP::Lite > > -> uri('urn:xmethodsInterop') > > > > -> proxy('http://services.xmethods.net/soap/servlet/rpcrouter', > > cookie_jar => HTTP::Cookies->new(ignore_discard => 1)); > > > > print $soap->echoString('Hello')->result; > > > > I need something like that 'cookie_jar' parameter in SOAPpy > > too. Help and thanks! > > > > /Mickel > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From bart_nessux at hotmail.com Wed Jun 16 14:25:42 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 14:25:42 -0400 Subject: thread help In-Reply-To: References: <40cea9cb$1@nntp0.pdx.net> Message-ID: <40D090A6.5010008@hotmail.com> One word Eddie... WOW! This async stuff is fabulous! It works and it's dead easy for my application. There is no cpu limit with what I'm doing... only I/O problems. At your suggestion, I looked at twisted, and then just used the standard python asyncore module because it looked so darn easy, and as it turned out, it was. Thanks a million for the advice. I was looking in the *wrong* direction. Eddie Corns wrote: > Bart Nessux writes: > > > >>The problem I have is this: I know too little about thread programming. >>If anyone thinks the code I have below could be made to work for my >>tasks (probe 65,000 IPs for HTTP servers using threads to speed things >>up), then please *show* me how I might change it in order for it to work. > > > I haven't been following this thread but if I was doing this I would want to > use asynchronous programming. It would finally force me to get to grips with > twisted. > > Eddie From eric at zomething.com Sun Jun 13 17:25:57 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sun, 13 Jun 2004 13:25:57 -0800 Subject: Searching for the best scripting language, Message-ID: <20040613132557.814918828.eric@zomething.com> Richard James wrote: > "Folks at the Scriptometer conducted a practical survey of which > scripting language is the best. While question like that is bound to > generate flamewars between the usual Perl vs PHP, Python vs Perl, > VBScript vs everything crowds, the Scriptometer survey is practical: > if I have to write a script, I have to write it fast, it has to be > small (less typing), it should allow me to either debug itself via a > debugger or just verbose output mode. sh, Perl and Ruby won the > competition, and with the difference of 1-2 points they were > essentially tied for first place... Well, if you ask me (and I guess you did!) they have the second set of metrics practically inverted for how I evaluate a language. Perl, with this: -e "/etc/mtab" or exit 1 gains more than 2x the points over Python, because Python uses more than 2x the characters with this: import os, sys sys.exit(not os.path.exists("/etc/mtab")) Well, if one lives in a Perl Mind, then Perl is more finger efficient. If you are going to type this in from the command line a dozen times a day, Perl is quicker than Python. You think in Perl and become an efficient part of the machine, and you may or may not even remember your days with Captain Picard before you became part of Borg. Python is pretty nice, though, when you start thinking of larger and/or more complex structures, or have to go back through source code months later, but maybe that's not considered "scripting". Maybe that's "programming". OK: imagine The President of the United States outlawed Perl tomorrow! Sure, some Perl programmers would take up Python, but a great many, I believe, would reject it's "bulk" and swell the ranks of Egyptologists. Finally we would come to know how the pyramids were built, or at least see a lot of Egyptian symbology on Slashdot. Eric Pederson :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Blogs: Music & Internet: http://www.songzilla.blogspot.com Politics: http://www.gigarot.blogspot.com Aged Fitness: http://www.oldmansknees.blogspot.com :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: e-mail me at: do at something.com except, increment the "d" and "o" by one letter and spell something with a "z" :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: From jepler at unpythonic.net Wed Jun 16 08:34:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 16 Jun 2004 07:34:06 -0500 Subject: bindings in Tkinter In-Reply-To: References: Message-ID: <20040616123404.GA19510@unpythonic.net> On Wed, Jun 16, 2004 at 06:58:37AM +0200, p.kosina wrote: > Solved.- I must have old documentation, I used 'n'. > Thank you. > Pavel Aha! The first argument to bind can be a sequence of events, which would explain exactly the behavior you saw. This *can* be useful (it's in effect how double-click works) but it can also do something different than what you want. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jaydonnell at yahoo.com Mon Jun 28 18:22:05 2004 From: jaydonnell at yahoo.com (Jay Donnell) Date: 28 Jun 2004 15:22:05 -0700 Subject: IOError: [Errno 32] Broken pipe Message-ID: I'm working on a simple script to manipulate csv files. Right now it just prints the first field of the file for each line. Everything works fine, but if I use 'head' or 'more' and quit while in more then I get IOError: [Errno 32] Broken pipe Anyone know why this is happening? jay at linux:~/Desktop/gmProductData> ./variance.py | head 91109 : 91109 A0101 : A0101 A0102 : A0102 A0103 : A0103 A0104 : A0104 A0105 : A0105 A0106 : A0106 A0107 : A0107 A0111 : A0111 A0112 : A0112 Traceback (most recent call last): File "./variance.py", line 39, in ? print '%s : %s' % (match, skuS[0]) IOError: [Errno 32] Broken pipe From peufeu at free.fr Fri Jun 18 04:50:36 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 10:50:36 +0200 Subject: very large dictionaries References: Message-ID: From what I understand... - The match table is static (or does not changes often) - Your input data changes every time (so you don't want to load it in a postgres database everytime) Your problem : - read the input data. - for each input row, generate several keys - lookup each key in the match table - take appropriate action My solution : - read the input data. - for each input row, generate several keys - save the keys in a file (tempfile) in this format : (key, record id) Generate tempfile in partitions : Generate N tempfiles which will each contain a partition of the keys. - For each tempfile : - Load it (you chose a number of partitions such that the files fit into about 1/4 your RAM.) - group by keys (dict( key: [record ids] )) again it fits into RAM. Record IDs are already sorted because they were generated this way. - sort on keys (again, fast because it fits in RAM) Now you have a sorted keyset which you want to lookup into a match table, which is ALSO sorted (you sorted it beforehand because it doesn't change often). Now start a key_pointer at the beginning of your key list, and a match_pointer at the beginning of your match table. You are basically comparing two sorted lists. This does not involve any search, rather a very simple algorithm. Your match table is not partitioned. If key_pointer.key < match_pointer.key: advance match_pointer elif key_pointer.key > match_pointer.key: advance key_pointer if at end of your tempfile partition, load the next one and sort it. elif key_pointer.key == match_pointer.key: you have a match. record id. What do you think ? I already used this algorithm and it's very powerful. > Let me specify further. Our actual data is enormous, and tests with > Postgres and MySQL indicate that the time taken just to build a single > index is on the order of hours, which is too long. After analysis we > believe that the important lookup info can be compressed to about 40 > million records of 48 bytes each. Furthermore, we have the flexibility > to partition this into four somewhat equal parts. Each will hence be > about 460MB in size. Even with structural overhead I see no reason > this couldn't fit into memory. This is our match file. > > Our process involves taking an input disk file, and traversing it one > record at a time. This we can sort by the same partition criteria used > to split the match file (so that each match file can be loaded but > once). For each input record we build a series of keys and compare > them to the appropriate match file; thus there are multiple lookups > per input record. An algorithm then determines which match record we > wish to pick and we write an ID to the input. > > There is more to it than this, but these are the major elements. The > input table may be millions of records long, but likely will be much > smaller. > > The total processing time will be a sum of: > time to sort/index input file > time to traverse input file > time to load in all parts of the match table > time to build keys on input records > time to search match table for each key > time to write match key ID > overhead time of routine > > A new wrinkle is that the match table may have duplicate keys, so > storing it as a dictionary is not an option. > > The data is alphanumeric. > > Assume an arbitrarily powerful computer, since adding a GB of RAM is > not an issue. > > The question I had, for those with experience with large data sets, is > what structure would best handle this problem? > > -- robin -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From nospam at nowhere.hu Thu Jun 10 17:28:11 2004 From: nospam at nowhere.hu (Miklós) Date: Thu, 10 Jun 2004 23:28:11 +0200 Subject: Source Code Generation Tool References: <3c91a864.0406101223.7c17926e@posting.google.com> Message-ID: Hi, Infinite Monkeys ;) Pm "logistix at cathoderaymission.net" wrote in message news:3c91a864.0406101223.7c17926e at posting.google.com... > # > # libraryOfBabel.py > # > # This is a general purpose source code generation tool. > # > # It generates any code you may require for python, perl, rexx, > # C, C++, befunge, ADA, ruby and other programming languages > # > # It will generate the source code for Python 3000 > # > # It is also capable of generating the complete works of > # William Shakespeare, Friedrich Nietzsche, > # and Raymond Chandler > # > > import sys > > symbols = [chr(x) for x in range(128)] > symbols.remove(chr(7)) > > def indexToSymbol(index): > try: > return symbols[index] > except: > raise Exception("invalid index %i" % index) > > def symbolToIndex(symbol): > try: > return symbols.index(symbol) > except: > raise Exception("Invalid Symbol '%s'" % symbol) > > def generateDocument(number): > while number: > div,mod = number / len(symbols), number % len(symbols) > sys.stdout.write(indexToSymbol(mod)) > number = div > > i = 1401448258002517817034703038066348000649199218 > > while 1: > print '=' * 79 > print 'DOCUMENT ID ', i > print '=' * 79 > generateDocument(i) > i += 1 From nid_oizo at yahoo.com_remove_the_ Tue Jun 8 18:18:53 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 08 Jun 2004 18:18:53 -0400 Subject: if does not evaluate In-Reply-To: References: Message-ID: Robert Brewer wrote: > If your main desire is to code in some other language while still using > Python, write your own VB-style IIf function: All the solutions you propose don't work (except the long form). You cannot code an "iif" function. Test: def iif(cond, expr1, expr2): if cond: return expr1 return expr2 def foo(x): return iif(x == 0, 0, 1.0/x) foo(4) foo(0) See PEP 308. Regards, Nicolas From ruach at chpc.utah.edu Thu Jun 3 06:54:13 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 04:54:13 -0600 Subject: python uid uname manipultaion/fetching In-Reply-To: References: Message-ID: Phil Frost wrote: > See the pwd and grp standard modules. > > On Thu, Jun 03, 2004 at 04:06:31AM -0600, Matthew Thorley wrote: > >>Is there anything in the standard library that will convert a uid to a >>username ? or do I have to parse the /etc/passwd ? >> >>thanks >>-matthew > > thats perfect thanks -matthew From foo at bar.com Sun Jun 27 18:15:02 2004 From: foo at bar.com (bp) Date: Sun, 27 Jun 2004 22:15:02 GMT Subject: ANN: 'rex' 0.5, a module for easier creation and use of regular expressions. Message-ID: <270620041718002708%foo@bar.com> NOTE: This is my second attempt at posting this; as far as I can tell, the first posting never appeared on the newsgroups. If you've already seen this, sorry for the repeat. WHAT IS 'rex'? rex is a module which makes the creation and use of regular expressions, IMHO, much easier than is the case using the 're' module. It does this by subclassing strings to provide a special regular-expresssion-type string, and then defining operations on that class. This permits building regular expressions without the use of arcane sytax, and with the help of Python edit modes and the Python syntax checker. It also makes regular expressions far, far easier to use. WHERE TO GET IT? http://homepage.mac.com/ken.mcdonald/FileSharing2.html WHAT ELSE? I'd appreciate feedback and suggestions. Code contributions are welcome too. I don't think I've mentioned the license in the 0.5 docs, but it will change from a custom license in the previous version to a PSA or similar standard license in the final version. Appended below is the (current) documentation, which could be better, but isn't too bad. It's missing function/method reference documentation, but at least shows you what rex can do. The next version will have substantially more complete documentation. My editor 'helpfully' autowrapped the documentation--it's easier to read in the copy included in the module. rex: A Module to Provide a Better Interface to Regular Expressions. =================================================================== 'rex' provides a much better interface for creating and using regular expressions. It is built on top of, and and intended as a functional replacement for, the Python 're' module. Introduction ============ 'rex' stands for any of (your choice): - Regular Expression eXtensions - Regular Expressions eXpanded - Rex, King of Regular Expressions (ha, ha ha, ha). rex provides a completely different way of writing regular expressions (REs). You do not use strings to write any part of the RE _except_ for regular expression literals. No escape characters, metacharacters, etc. Regular expression operations, such as repetition, alternation, concatenation, etc., are done via Python operators, methods, or functions. The major advantages of rex are: - [This is a biggie.] rex permits complex REs to be built up easily of smaller parts. In fact, a rex definition for a complex RE is likely to end up looking somewhat like a mini grammar. - [Another biggie.] As an ancillary to the above, rex permits REs to be easily reused. - rex expressions are checked for well-formedness by the Python parser; this will typically provide earlier and easier-to-understand diagnoses of syntactically malformed regular expressions - rex expressions are all strings! They are, in fact, a specialized subclass of strings, which means you can pass them to existing code which expects REs. - rex goes to some lengths to produce REs which are similar to those written by hand, i.e. it tries to avoid unnecessary use of nongrouping parentheses, uses special escape sequences where possible, writes 'A?' instead of 'A{0,1}', etc. In general, rex tries to produce concise REs, on the theory that if you really need to read the buggers at some point, it's easier to read simpler ones than more complex ones. As an example, take a look at the definition of an RE matching a complex number, an example included in the test_rex.py. The rex Python code to do this is: COMPLEX= ( PAT.aFloat['re'] + PAT.anyWhitespace + ALT("+", "-")['op'] + PAT.anyWhitespace + PAT.aFloat['im'] + 'i' ) while the analogous RE is: (?P(?:\+|\-)?\d+(?:.\d*)?)\s*(?P\+|\-)\s*(?P(?:\+|\-)?\d+(?:. \d*)?)i The rex code is more verbose than the simple RE (which, by the way, was the RE generated by the rex code, and is pretty much what you'd produce by hand). It is also FAR easier to read, modify, and debug. And, it illustrates how easy it is to reuse rex patterns: PAT.aFloat and PAT.anyWhitespace are predefined patterns provided in rex which match, respectively, a string representation of a floating point number (no exponent), and a sequence of zero or more whitespace characters. Using rex ========= This is a quick overview of how to use rex. See documentation associated with a specific method/function/name for details on that entity. In the following, we use the abbreviation RE to refer to standard regular expressions defined as strings, and the word 'rexp' to refer to rex objects which denote regular expressions. The starting point for building a rexp is either rex.PAT, which we'll just call PAT, or rex.CHAR, which we'll just call CHAR. CHAR builds rexps which match single character strings. PAT builds rexps which match strings of varying lengths. - PAT(string) returns a rexp which will match exactly the string given, and nothing else. - PAT._someattribute_ returns (for defined attributes) a corresponding rexp. For example, PAT.aDigit returns a rexp matching a single digit. - CHAR(a1, a2, . . .) returns a rexp matching a single character from a set of characters defined by its arguments. For example, CHAR("-", ["0","9"], ".") matches the characters necessary to build basic floating point numbers. See CHAR docs for details. Now assume that A, B, C,... are rexps. The following Python expressions (_not_ strings) may be used to build more complex rexps: - A | B | C . . . : returns a rexp which matches a string if any of the operands match that string. Similar to "A|B|C" in normal REs, except of course you can't use Python code to define a normal RE. - A + B + C ...: returns a rexp which matches a string if all of A, B, C match consecutive substrings of the string in succession. Like "ABC" in normal REs. - A*n : returns a rexp which matches a number of times as defined by n. This replaces '?', '+', and '*' as used in normal REs. See docs for details. 'rex' defines constants which allow you to say A*ANY, A*SOME, or A*MAYBE, indicating (0 or more matches), (1 or more matches), or (0 or 1 matches), respectively. - A**n : Like A*n, but does nongreedy matching. - +A : positive lookahead assertion: matches if A matches, but doesn't consume any of the input. - ~+A : negative lookahead assertion: matches of A _doesn't_ match, but doesn't consume any of the input. - -A, ~-A : positive and negative lookback assertions. Lke lookahead assertions, but in the other direction. - A[name] : name must be a string: anything matched by A can be referred to by the given name in the match result object. (This is the equivalent of named groups in the re module). - A.group() : A will be in an unnamed group, referable by number. In addition, a few other operations can be done: - Some of the attributes defined in PAT have "natural inverses"; for such attributes, the inverse may be taken. For example, ~ PAT.digit is a pattern matching any character except a digit. - Character classes may be inverted: ~CHAR("aeiouAEIOU") returns a pattern matching anything except a vowel. - 'ALT' gives a different way to denote alternation: ALT(A, B, C,...) does the same thing as A | B | C | . . ., except that none of the arguments to ALT need be rexps; any which are normal strings will be converted to a rexp using PAT. - 'PAT' can take multiple arguments: PAT(A, B, C,...), which gives the same result as PAT(A) + PAT(B) + PAT(C) + . . . . Finally, a very convenient shortcut is that only the first object in a sequence of operator/method calls needs to be a rexp; all others will be automatically converted as if PAT[...] had been called on them. For example, the sequence A | "hello" is the same as A | PAT("hello") rex Character Classes ===================== CHAR(args...) defines a character class. Arguments are any number of strings or two-tuples/two-element lists. eg. CHAR("ab-z") is the same as the regular expression r"[ab\-z]". NOTE that there are no 'character range metacharacters'; the preceding define a character class containing four characters, one of which was a '-'. This is a character class containing a backslash, hyphen, and open/close brackets: CHAR(r"\-[]") or CHAR("\-[]") Note that we still need to use raw strings to turn off normal Python string escaping. To define ranges, do this : CHAR(["a","z"], ["A","Z"]) To define inverse ranges, use the ~ operator, eg. To define the class of all non-numeric characters: ~CHAR(["0","9"]) Character classes cannot (yet) be doubly negated: ~~CHAR("A") is an error. Predefined Constants ==================== rex provides a number of predefined patterns which will likely be of use in common cases. Generally speaking, rex constant pattern names begin with 'a' or 'an' (indicating a pattern that matches a single instance), 'any' (indicating a pattern that matches 0 or more instances), 'some' (indicating a pattern that matches 1 or more instances), and 'optional' (meaning the pattern matchs 0 or 1 instance.) Some special names are also provided. The 'rex' module may define other constant names, but you should only use those below; others may change in future release of rex. - Matches any character: aChar, someChars, anyChars - Matches digits (0-9): aDigit, someDigits, anyDigits - Matches whitespace characters: aWhitespace, someWhitespace, anyWhitespace - Matches letters (a-z, A-Z): aLetter, someLetters, anyLetters - Numeric values (signed or unsigned, no exponent): anInt, aFloat - Match only the start or end of the string: stringStart, stringEnd - Match only at a word border: wordBorder - Matches the emptyString: emptyString - Any punctuation (non whitespace) character on a standard US keyboard): aPunctuationMark From has.temp2 at virgin.net Thu Jun 3 17:31:39 2004 From: has.temp2 at virgin.net (has) Date: 3 Jun 2004 14:31:39 -0700 Subject: Need help resolving accidental (honest!) language pissing match References: <69cbbef2.0406020615.7540ad0@posting.google.com> Message-ID: <69cbbef2.0406031331.1b539466@posting.google.com> Jeff Epler wrote in message news:... > Here's my try, using numarray: [...] > This runs for about .6 seconds on a 2.4GHz PC running Linux. > > I'm not sure whether the results are right, but at least the program > finishes quickly, and involves a random array, a running sum, and some > statistics. Just what the doctor ordered! Many thanks! :) (p.s. If your interested, the numarray script takes about 1 sec on my G4/867 running OS10.2.6 - about same speed as the original example. Only change I made was replacing numint with uniform to get reals. But numarray wins on sheer size and breadth of functionality, imnsho...;) From Scott.Daniels at Acm.Org Fri Jun 4 12:40:09 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 04 Jun 2004 09:40:09 -0700 Subject: Setting the default precision in mxNumber In-Reply-To: <40c09982$1@zinews.unizh.ch> References: <40c09982$1@zinews.unizh.ch> Message-ID: <40c0aa26$1@nntp0.pdx.net> Thomas Chassaing wrote: > ... mxNumber package .... do I have to use the Float(value,precision) > constructor all the time? Why not define your own constructor with a default that you control? Then your code can happily use FLOAT(value) (for example), while mxNumber's internals can get what they are used to and expect. -- -Scott David Daniels Scott.Daniels at Acm.Org From jbors at mail.ru Sun Jun 13 15:52:06 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Sun, 13 Jun 2004 12:52:06 -0700 Subject: ANN: PyMedia 1.2.2( Python mutlimedia framework ) Message-ID: <006701c4517f$e9640840$0200a8c0@amr.corp.intel.com> Hi all, Just wanted to let you know that PyMedia 1.2.2 is out. What is it ? ---------------------------------------------------------------- PyMedia is a media library for Python based on the following libraries: libavcodec, libavformat, libdvdcss, libdvdread It has simple interface and yet powerfull for multimedia apps written in Python. Features ---------------------------------------------------------------- 1. Audio decoding/encoding for the following types: - mp2, mp3, ac3, ogg, wma 2. Video decoding/encoding for the following types: - mpeg1,2 ( dvd, vcd, svcd ), mpeg4, xvid, asf, mov 3. Video/Audio muxing for mpeg files only 4. Direct access to sound device( Input/Output ). Input is synchronous in Linux. 5. Sound manipulation classes such as Resampler and SpectrAnalyzer 6. Direct access to cdda tracks for easy grabbing and encoding Audio CDs 7. Direct access to dvd tracks for playing DVD movies( all types ) 8. Ability to convert video frames from YUV<->BMP formats 9. Simple interface and portability( Windows/Linux/cygwin ) What's new ---------------------------------------------------------------- This version includes these interfaces for better multimedia experience: 1. pymedia.sound.SpectrAnalyzer - analyzes sound in frequencies or bands 2. pymedia.sound.Input for grabbing sound from the external devices such as Microphone/Line-In 3. pymedia.video.vcodec.convertFrame for converting frames YUV<->RGB(A) 4. cygwin can be used to compile pymedia Downoad ---------------------------------------------------------------- Just check the http://pymedia.sourceforge.net and download the latest version( 1.2.2 ). You may download Windows binaries if needed. How to use ---------------------------------------------------------------- First of all you can see PyCar application( Windows only at this time ): http://pymedia.sourceforge.net/pycar/ Also you may find some really handy scripts in examples directory( see gz tarball ). These are: Video player: vplayer.py requires: pydfb( http://sourceforge.net/project/showfiles.php?group_id=86491&package_id=107482 ) pygame 1.6 patched with Overlay support: Linux patch at: http://pymedia.sourceforge.net/pygame-1.6-overlay.patch.gz Windows installer: http://pymedia.sourceforge.net/pygame-1.6-overlay.win32-py2.3.exe Audio player: aplayer.py CDDA grabber: read_cdda_track.py Video recoder: encode_video.py, recode_video.py Audio recoder: recode_audio.py Sound Recorder: voice_recorder.py Funky audio player with some visualization: sound_viz.py Next major release 1.3.* ----------------------------------------------------------------- It will feature: - usb support for easy handling the usb devices ability to write drivers in Python for devices that does not require realtime speed - more sound handling classes( Mixer, Equalizer ) - more codecs for audio playback( ape, flac, aac ) - support for better muxing of avi, asf, mov Enjoy, Dmitry/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bart_nessux at hotmail.com Wed Jun 16 21:13:25 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 21:13:25 -0400 Subject: breaking a list into smaller lists In-Reply-To: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> References: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> Message-ID: <40D0F035.7090508@hotmail.com> Maciej Dziardziel wrote: > Bart Nessux wrote: > > >>Is there a way to turn this big list into 100 small lists (each >>containing 1000 files) with one simple line of code? >> >>Thanks, >>Bart > > > big = range(87) > > print [ big[i*10:i*10+10] for i in xrange(len(big)/10+int((len(big) % > 10)>0) ) ] > > replace 10 with any value you need, but it is better not to keep all 100 000 > filenames in memory if it isn't necessary > Thank you for this example. It works very well. From martin at v.loewis.de Sun Jun 13 04:49:52 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 10:49:52 +0200 Subject: setlocale returns error In-Reply-To: References: <40cb6bbd$0$36860$e4fe514c@news.xs4all.nl> Message-ID: <40CC1530.9000506@v.loewis.de> transam wrote: > What about windows and other systems? > Does this problem never occur there? If it occurs, > how to cure it? First of all, you have to know the locale names for Windows; they differ from the locale names on Unix. In addition, Windows installations support only a subset of the locales support in Windows in general. The only "cure" is to install a different Windows product. E.g. if you find you are lacking an east-asian locale, it might be that you need to install an east-asian edition of Windows, or a multi-lingual edition. Regards, Martin From benn at cenix-bioscience.com Fri Jun 4 05:48:59 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Fri, 04 Jun 2004 11:48:59 +0200 Subject: UML Tools Message-ID: <40C0458B.2080901@cenix-bioscience.com> Hello, Does anyone know of a decent tool to write UML diagrams (mainly class diagrams but sequence would also be useful) that's aware of Python's syntax (i.e. modules). I'd like round-trip as well but I can live without it. cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From me at privacy.net Tue Jun 22 04:24:03 2004 From: me at privacy.net (Duncan Booth) Date: 22 Jun 2004 08:24:03 GMT Subject: Catching errors in attribute names at assigment References: Message-ID: tkpmep at hotmail.com (Thomas Philips) wrote in news:b4a8ffb6.0406211000.dd207c4 at posting.google.com: > Is there a way to check assignments when they are made and to allow > only those that modify a restricted set of allowable attributes? > Looking through ClassName.__dict__.keys() is perhaps one way to > achieve this: Is there a simpler (i.e. more Pythonic) way to do it as > well? Two more Pythonic ways to do this: Write lots of unit tests. That way you not only catch this specific problem but lots of others as well. Use PyChecker. That way you not only catch this specific problem but lots of others as well. From peter at engcorp.com Wed Jun 16 16:10:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 16:10:56 -0400 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: Message-ID: Mark Hahn wrote: > Andrea Griffini wrote: >>I like more as an example: >> >>> def foo(x): >> ... if not hasattr(foo,'list'): >> ... foo.list = [] >> ... foo.list.append(x) >> ... print foo.list > > In Prothon: > def foo(x): > print foo.list.append!(x) > foo.list = [] > > (Sorry. I couldn't resist bragging.) About what? Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] >>> def foo(x): ... foo.list.append(x) ... print foo.list ... >>> foo.list = [] >>> foo('test') ['test'] (Oh, did you mean bragging about how a hard-to-see exclamation mark causes append() to return the sequence? I thought maybe it was about the function attribute or something.) -Peter From gardner at networknow.org Tue Jun 8 20:03:16 2004 From: gardner at networknow.org (Gardner Pomper) Date: Tue, 8 Jun 2004 20:03:16 -0400 Subject: How to get process info from python In-Reply-To: Message-ID: Nick, AIX does not seem to support the -o format syntax. What I am using is "ps -lf" which seems to give me as much information as possible. I also, optionally, add "-u user" if I need to get all the information for a user, instead of just for the current tty process tree. Currently, all I am using is the cmd line, but since there doesn't seem to be any other way to get the memory information for the process from python, I will need to start using the SZ column. Here is what I have so far (hopefully 129 lines of code is not too much to post in the group. If it is, I apologize) #!/usr/bin/env python import string import commands import emea from optparse import OptionParser # class ProcessStatus : def __init__(self,header,status): self.uid = '' self.pid = '' self.ppid = '' self.priority = '' self.nice = '' self.size = '' self.start = '' self.time = '' self.cmd = '' headings = header.split() headings.remove('WCHAN') # # ----- find the char position of the WCHAN, STIME # ----- TTY and CMD headings # wchan_pos = string.index(header,'WCHAN') stime_pos = string.index(header,'STIME') tty_pos = string.index(header,'TTY') cmd_pos = string.index(header,'CMD',stime_pos) # # ----- cut the status line before WCHAN because # ----- that is often blank # n = string.rindex(status,' ',0,wchan_pos) status1 = status[:n-1] fields = status1.split() if string.find(status,'') < 0 : # # ----- the stime is all the chars between # ----- STIME and TTY # x = string.rindex(status,' ',0,stime_pos) y = string.rindex(status,' ',stime_pos,tty_pos) sTime = string.strip(status[x:y]) fields.append( sTime) # # ----- the TTY and TIME fields are all the chars # ----- between TTY and CMD # max_pos = cmd_pos + 5 if max_pos > len(status)-1 : max_pos = len(status) - 1 m = string.rindex(status,':',tty_pos,max_pos) n = string.index(status,' ',m) status2 = status[y+1:n].strip() fields.extend(status2.split()) # # ----- CMD is the rest of the line # status3 = status[n:].strip() fields.append(status3) try : for h,y in map(None,headings,fields) : if h == 'UID' : self.uid = y elif h == 'PID' : self.pid = y elif h == 'PPID' : self.ppid = y elif h == 'PRI' : self.priority = y elif h == 'NI': self.nice = y elif h == 'SZ' : self.size = y elif h == 'STIME' : self.start = y elif h == 'TIME' : self.time = y elif h == 'CMD' : if string.find(status,'') >= 0 : self.cmd = '' else: self.cmd = y except Exception, error : logger = emea.get_logger() logger.exception(error) raise Exception(error) def __str__(self) : return "UID %s PID %s PPID %s PRI %s NI %s SZ %s STIME %s TIME %s CMD %s" \ %(self.uid,self.pid,self.ppid,self.priority,self.nice, self.size,self.start,self.time,self.cmd) def ps(user=None) : options = '' if user == 'all' : options += ' -e' elif user != None : options += ' -u ' + user cmd = 'ps -lf ' + options ps_result = commands.getoutput(cmd) lines = ps_result.splitlines() psList = [] for l in lines[1:] : psList.append(ProcessStatus(lines[0],l)) return psList # # # ----- # if __name__ == "__main__" : parser = OptionParser() parser.add_option("", "--user",action="store",dest="user", help="user to do ps for") parser.add_option("","--log",action="store",dest="log", default="emea_auto.log",help="name of log file") parser.add_option("","--verbose",action="store_true",dest="verbose", help="verbose mode (for debugging)") (options,args) = parser.parse_args() # # ----- define logging # emea.set_logger('process_status',options.log,options.verbose) psList = ps(options.user) for p in psList: print p > -----Original Message----- > From: python-list-bounces+gardner=networknow.org at python.org > [mailto:python-list-bounces+gardner=networknow.org at python.org]On Behalf > Of Nick Vargish > Sent: Tuesday, June 08, 2004 10:52 AM > To: python-list at python.org > Subject: Re: How to get process info from python > > > "Gardner Pomper" writes: > > > On a related issue, I was very surprise to see that > os.loadavg() had been > > added in version 2.3. This seems just as OS specific as the ps > functionality > > I want, so that raised my hopes. > > Gardner, > > I've had to work with process data in the past, and you're right, a > module to handle accessing ps data would be quite useful. Just for > fun, I've started writing something to help. All the systems that I > use "ps" on support a "-o format" for extracting specific information, > is this option supported on AIX?[*] > > What sort of information do you need from ps? I'll try to work it into > the module's functionality. > > I can't promise when it will be ready, but you seem to be rolling your > own solution anyway. > > Nick > > [*] Linux, OS X, and Tru64 (nee DEC Unix nee OSF/1). I don't have > access to an AIX system right now. > > -- > # sigmask || 0.2 || 20030107 || public domain || feed > this to a python > print reduce(lambda x,y:x+chr(ord(y)-1),' > Ojdl!Wbshjti!=obwAcboefstobudi/psh?') > -- > http://mail.python.org/mailman/listinfo/python-list From jlbraams at cistron.nl Sun Jun 20 06:10:24 2004 From: jlbraams at cistron.nl (jlbraams at cistron.nl) Date: Sun, 20 Jun 2004 12:10:24 +0200 Subject: Your text Message-ID: See the attached file for details. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_text.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From antoine at vanmaarle.nl Fri Jun 4 12:52:41 2004 From: antoine at vanmaarle.nl (AnToine van Maarle) Date: Fri, 4 Jun 2004 18:52:41 +0200 Subject: wxAssertFailure (tbar95.cpp(582)) Message-ID: Hi, This message we get at some winXP machine's after installing the setup.exe of our compiled CRM program (for free license http://www.alexion.nl/pynx/registrationalexion.html). We use McMillan and Inno Setup 4. Why is xwPython making such a fuss? C:\Program Files\Alexion Software\Relation Manager\program>arm.exe Extracting binaries C:\Program Files\Alexion Software\Relation Manager\program\python23.dll Manipulating evironment PYTHONPATH=C:/Program Files/Alexion Software/Relation Manager/program importing modules from CArchive iu archive Installing import hooks out1.pyz Running scripts bin\buildstdapp\out1.pyz/fcntl:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl Traceback (most recent call last): File "", line 90, in ? File "bin\buildstdapp\out1.pyz/wxPython.wx", line 1957, in __init__ File "", line 66, in OnInit File "bin\buildstdapp\out1.pyz/pynx.gui.frame", line 97, in __init__ File "bin\buildstdapp\out1.pyz/wxPython.stattool", line 227, in Realize wxPython.wxc.wxPyAssertionError: C++ assertion "wxAssertFailure" failed in e:\Projects\wx2.4\src\msw\tbar95.cpp(582): invalid tool button bitmap RC: -1 from main OK. 09:06:53: Debug: e:\Projects\wx2.4\src\msw\app.cpp(407): 'UnregisterClass(MDI parent)' failed with error 0x00000584 (de klasse heeft nog geopende vensters.). From pawel_Kraszewski at wp.pl Mon Jun 21 16:01:31 2004 From: pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Mon, 21 Jun 2004 22:01:31 +0200 Subject: Catching errors in attribute names at assigment References: Message-ID: Thomas Philips wrote: > If one makes a typographical error when assigning a value to an > attribute (i.e if one types ClassName.xyc = 10 instead of > ClassName.xyz=10), a new attribute xyc will be created, and the error > can later prove difficult to debug. > Is there a way to check assignments when they are made and to allow > only those that modify a restricted set of allowable attributes? > Looking through ClassName.__dict__.keys() is perhaps one way to > achieve this: Is there a simpler (i.e. more Pythonic) way to do it as > well? Yes, there are at least two ways The "new" way is to use "new classes" - ones being children of "object" class - where you have a special attribute __all__ . If you say __all__=["a","b","c"], those 3 attributes are the only ones valid for field/method accessing. So class.a=5 is ok, but class.d=5 raises exception. The "old" way is to override __getattr__ and __setattr__ and check for a valid name before accessing. -- Pawel Kraszewski FreeBSD/Linux E-Mail/Jabber Phone ICQ GG Pawel_Kraszewski at wp.pl +48 604 777447 45615564 69381 From winexpert at hotmail.com Wed Jun 16 13:36:55 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 16 Jun 2004 17:36:55 +0000 Subject: getting arguments off the command line Message-ID: Whats a good way to get arguments off of the command line? Thanks David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Looking to buy a house? Get informed with the Home Buying Guide from MSN House & Home. http://coldwellbanker.msn.com/ From chrisks at NOSPAMudel.edu Tue Jun 15 00:54:17 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Tue, 15 Jun 2004 00:54:17 -0400 Subject: Finding Function Args? In-Reply-To: References: Message-ID: Thanks for the help. Mike C. Fletcher wrote: > Check the standard module inspect, particularly; > > >>> import inspect > >>> import cgi > >>> inspect.getargspec( cgi.escape ) > (['s', 'quote'], None, None, (None,)) > > > HTH, > Mike > > Chris S. wrote: > >> Is there a way to dynamically find out how many arguments a function >> requires? I thought this would be listed somewhere with dir() but I >> can't find anything. Any help is appreciated. > > > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > blog: http://zope.vex.net/~mcfletch/plumbing/ > > From michele.simionato at poste.it Fri Jun 18 02:25:36 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 17 Jun 2004 23:25:36 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: <95aa1afa.0406172225.7ef5bc15@posting.google.com> j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > You guys are WAY over my head, and I'm supposed to be a C.S. junior! :-\ > > Could someone give me an idea of what metaclasses and decorators _are_? > > I think metaclasses are classes with their base methods overridden, correct? > > And decorators are a form of delegation, right? > > If so, where am I wrong? And how do these techniques make for better code/coding? > > jonathon http://www.python.org/cgi-bin/moinmoin/MetaClasses for decorators, look at PEP318. From tim.one at comcast.net Sat Jun 12 16:12:06 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 12 Jun 2004 16:12:06 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <40caf01b$0$41764$5fc3050@dreader2.news.tiscali.nl> Message-ID: [Gr?goire Dooms] > If speed is the matter, go for C: > > with the GNU MP library use > void mpz_pow_ui (mpz_t rop, mpz_t base, unsigned long int exp) and > char * mpz_get_str (char *str, int base, mpz_t op) There are some GMP wrappers for Python. Using Marc-Andre Lemburg's mxNumber wrapper (which is maximally convenient for me on Windows, since it includes a precompiled-for-Windows GMP), the OP's task is spelled like so: >>> from mx.Number import * >>> Integer(2)**24036583 - 1 That does call mpz_pow_ui() and mpz_get_str() (with base=10) under the covers. Since I typed that in, the process has accumulated 59 CPU minutes, with no output yet. Curiously, >>> x = Integer(2)**24036583 - 1 consumes 112 CPU seconds on its own, while the straight Python >>> x = 2**24036583 - 1 consumes only 2 CPU seconds -- so Python is 50+ times faster than this GMP for the computational part. Python's Karatsuba multiplication gets enormous benefit out of special-casing zeroes in this particular case (all the squarings when computing the power see an input whose least-significant half is entirely zero bits, so huge mounds of needless work get skipped). The fastest pure-Python solution I've found consumed about 20 CPU minutes to do the whole job, so is at least 3X as fast as the GMP here (which is still running as I type this, over an hour of CPU time and climbing). For that, I wrote my own multiplication and exponentiation routines in Python, using digits in base 10**5000. Computing in a form of decimal from the start makes "conversion to decimal" a speedy operation. > I did a small contest about the decimal repr of 2**1000000 a a couple > years ago. A few languages were compared on a time-to-result basis. > Python won with 7 minutes (10 sec devel, 6:50 comput.) and C + GMP was > second: 15 min devel(including reading the doc) + a few sec of comput. I > bet you can expect a 30-100 fold speedup using C + GMP compared to python > -c 'print 2**24036583 - 1' On the box I'm using here, the straight Python 2.3.4: >>> 2**1000000 consumed 80 CPU seconds (which includes decimal display), and the mxNumber version: >>> from mx.Number import * >>> Integer(2)**1000000 consumed 60 CPU seconds. I expect Python 2.3.4 is faster at this stuff than the version you used (in particular, recent Pythons use base 10000 internally when converting to decimal, instead of base 10; it's still quadratic-time, but the constant factor was slashed). The box is a 3.2GHz P4, which is probably also faster than the box you used. It could also be that the version of GMP shipped with mxNumber isn't optimally compiled for this box, and/or getting old. Lessons to take home : + The speed of bigint operations can be data-dependent in implementation- specific ways (Python's native pow() ran circles around GMP's for this particular data). + That changes over time (recent Pythons are much faster at some of these tasks than the one you used). + A better algorithm is always the better answer (computing in decimal from the start allows pure Python to run circles around GMP computing in binary then forced to do a non-trivial 24-million bit base conversion). From tjreedy at udel.edu Sat Jun 5 01:22:33 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Jun 2004 01:22:33 -0400 Subject: Can python control complicated classes/objects written in C++ References: Message-ID: "Bo Peng" wrote in message news:c9rhu6$sk6$1 at joe.rice.edu... > Dear Python group: > > I am planning on an application that involves several complicated C++ > classes. Basically, there will be one or two big data objects and some > "action" objects that can act on the data. I would like to use a script > language to control the interaction between these c++ objects. > > I become interested in Python since it can load C++ objects and can even > extend C++ classes. However, I am not quite sure to what extent can > python do this. Ideally, I would like to have something like > > (pseudo code, not in python) > > data = new TData( option1=..., option2=...) > > action1 = new TAction(option1=range(1,10)...) > > action2 = new TSubAction(option1=sin(5),..., option2=...) > > data.run( action1, action2) > > data.print If you remove 'new' on the first three lines, the above could be Python. > The benefits here is that I do not have to worry about user-input > (python handles functions like range(), and numeric/string operations > for me and send them to my objects), running logic (user create the > scripts) and need only focus on the objects themselves. It would be > better if users can easily extend TAction by themselves, through either > Python or C++. > > I am totally new to Python. I have read boost.python, python extension > document but still do not know exactly what to do. My questions are: > > 1. can Python fully read/write member data and run member functions of > my objects? If they are properly wrapped, yes. > 2. can python pass complicated objects (TAction) to another object (TData)? Everything in Python is a first class object that can be passed, returned, or whatever. Phil's response: does python supported in WinCE/ProcketPC? From marco at reimeika.ca Thu Jun 10 22:09:04 2004 From: marco at reimeika.ca (marco) Date: 10 Jun 2004 22:09:04 -0400 Subject: tempfile broken in 2.3.4? References: Message-ID: marco writes: > It's probably me, but I'm really not sure what I'm doing wrong: It was me :) Solution: >>> tempfile.mkstemp('','ham') (13, '/tmp/ham7nPTfN') Sorry 'bout that... Cheers, -- marco at reimeika.ca Gunnm: Broken Angel http://amv.reimeika.ca http://reimeika.ca/ http://photo.reimeika.ca From Kyler at news.Lairds.org Tue Jun 1 12:09:12 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Tue, 01 Jun 2004 16:09:12 GMT Subject: having serious problems getting a python CGI to work References: Message-ID: John Draper writes: >error] (2)No such file or directory: exec of >/Library/WebServer/CGI-Executables/index.py failed I suspect that this has little to do with Python. Can you run a shell script through CGI on that system? #!/bin/sh echo Content-type: text/plain echo date If you can get that far, we can easily debug the Python execution. (Is there "strace" for MacOS?) --kyler From sbat at sbat.be Fri Jun 11 10:55:56 2004 From: sbat at sbat.be (SBAT) Date: Fri, 11 Jun 2004 16:55:56 +0200 Subject: Virus Found in message "Hello" Message-ID: Symantec AntiVirus found a virus in an attachment you (python-list at python.org ) sent to SBAT. To ensure the recipient(s) are able to use the files you sent, perform a virus scan on your computer, clean any infected files, then resend this attachment. Attachment: application.exe Virus name: W32.Netsky.P at mm Action taken: Clean failed : Quarantine succeeded : File status: Infected -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 1711 bytes Desc: not available URL: From skip at pobox.com Mon Jun 21 07:27:05 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 21 Jun 2004 06:27:05 -0500 Subject: Queue module and Python Documentation Rant In-Reply-To: References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: <16598.50697.482821.400388@montanaro.dyndns.org> >> I think a policy that requires all modules to have examples, and a >> consistent place for them in the documentation, would be a big help. Bart> I agree. It'd be nice to see examples based on how one intends to Bart> use the language. People are always welcome to submit patches for the documentation. Skip From mediocre_person at hotmail.com Fri Jun 11 23:22:23 2004 From: mediocre_person at hotmail.com (Mediocre Person) Date: Sat, 12 Jun 2004 03:22:23 GMT Subject: Teaching Python Message-ID: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Well, after years of teaching grade 12 students c++, I've decided to make a switch to Python. Why? * interactive mode for learning * less fussing with edit - compile - link - run - debug - edit - compile - link - run -..... * lots of modules * I was getting tired of teaching c++! Bored teacher = bad instruction. * thought about tcl/tk but it's just too different syntactically (for me, not my students!) after so much time with languages like c++/ada95/pascal/BASIC/Fortran, etc. * it appears to be FREE (which in a high school environment is mightily important) from both python.org or activestate.com. I think I like activestate's ide (under Win98) a bit better than idle, but your comments/suggestions? I've decided to give John Zelle's new book a try as a student textbook--it's as good an introductory CS book in any language I've seen. I've done a couple of small projects with tkinter, like what I see, and would like to introduct my students to it, although Zelle doesn't make use of it in his text. So, what pitfalls should I look out for in introducing Python to students who have had a year of Visual BASIC? Regards, chackowsky dot nick at portal dot brandonsd dot mb dot ca <-- have the spambots figured this one out yet? From peter at engcorp.com Tue Jun 29 14:18:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 14:18:45 -0400 Subject: poplib for multihomed machines In-Reply-To: <9418be08.0406291005.34d4277b@posting.google.com> References: <9418be08.0406280751.6cc50097@posting.google.com> <9418be08.0406291005.34d4277b@posting.google.com> Message-ID: Elbert Lev wrote: > This is a major design error. NO-NO is C++. Constructor is supposed > only initialise members and take no actions. Unfortunatelly this > paradigm is violated in many Python classes. __init__ is an initializer, not a constructor. Python didn't have real constructors until the new style classes were created, and __new__. From tzot at sil-tec.gr Tue Jun 8 05:12:53 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 08 Jun 2004 12:12:53 +0300 Subject: Balanced tree type coming in next Python? References: Message-ID: <8nvac0dohq837c4nth3bq6tnvesc20cn7o@4ax.com> On Mon, 07 Jun 2004 16:46:06 +0200, rumours say that "Thomas Guettler" might have written: >> PS Any volunteers to port and maintain Judy arrays/trees for Python?-) >> http://judy.sourceforge.net/ >> They'd be an interesting alternative to dictionaries in some cases (esp >> very large dictionaries). > >How do they compare to BTrees (ZODB)? I really don't know, to be honest; I have never used Zope's Btrees. It's just that in some older C program of mine, with big data structures running on a shared computer with lots of RAM but with limits per user, I gave Judy trees a try and I was impressed by their speed and their efficient usage of RAM. Since I was hitting my limits, before using Judy trees I had retorted to using the C stdlib qsort and bsearch on linear arrays (like Python lists); of course, the speed of adding elements and re-running qsort was not impressive (no timsort in the C stdlib :). Before using Judy trees, my program used up to 492 MiB of ram (with careful implementation so that realloc'ing my large list would just extend it, not copy it to another address and then freeing the old space); with Judy trees, it used about 508 MiB, which was inside my limit of 512, and much faster. I haven't tried so far to port Judy trees to Python; ISTR that somebody did an attempt using Pyrex, but never gave it a shot. Python dicts are excellent, but memory inefficient on large amounts of data. Also, they are not the right structure to use if you want range checks. Trees do have their use, as you surely know. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From tylere at gmail.com Fri Jun 25 21:44:16 2004 From: tylere at gmail.com (Tyler Eaves) Date: Fri, 25 Jun 2004 21:44:16 -0400 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: lambda? From dave at pythonapocrypha.com Thu Jun 17 11:01:01 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 17 Jun 2004 09:01:01 -0600 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> Message-ID: <034301c4547b$e8d99260$8119fea9@boba> Mark wrote: > >> In Prothon: > >> def foo(x): > >> print foo.list.append!(x) > >> foo.list = [] > >> > >> (Sorry. I couldn't resist bragging.) > > > > About what? > > > > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] > > >>> def foo(x): > > ... foo.list.append(x) > > ... print foo.list > > ... > > >>> foo.list = [] > > >>> foo('test') > > ['test'] > > > > (Oh, did you mean bragging about how a hard-to-see exclamation > > mark causes append() to return the sequence? I thought > > maybe it was about the function attribute or something.) > > Actually, I didn't know if the function attribute assignment outside the > function would work in Python or not. I guess I'll know better than to try > to play one-upmanship with Python next time. I did say I was sorry :-) > > FYI: It's not that the exclamation mark causes append to return the > sequence. The exclamation mark is always there and the sequence is always > returned. The exclamation mark is the universal symbol for in-place > modification. This is straight from Ruby and solves the problem that caused > Guido to not allow sequences to be returned. And, yes, I do think that's > worth bragging about ;-) Wait, so is the exclamation point required or not? IOW, say you have a class like this: class List(list): def append(self, what): list.append(self, what) return self a = List() b = a.append(5) So in the call to append, is it a.append!(5) or just a.append(5) ? If it's the former, then does the compiler detect that it's required because the function returns 'self' or is the determining factor something else? Or, does the append method not really return anything, and the language takes care of substituting in the object? (in which case, does that mean you can override the return value by adding '!' - such that z=foo.bar!() ignores the return value of bar and z references foo?) Personally, I don't like the modify-in-place-and-return-the-object 'feature' - it's not needed _that_ often, but more importantly, it makes the code harder to read (to me at least). For example, it makes sense that append() doesn't normally return a value. If you told me it did return something, my first guess would be that the return value is the new length of the list (I guess I find it too easy to overlook the presence of '!'). For something like list.sort(), *if* there's a return value I'd expect it to be a sorted _copy_ of the list, certainly not the list itself. Even with the extra punctuation, it seems likely that you'd have bugs of the form: a = b.sort!() # do something destructive to 'a' # do something with b, expecting it to be the original Or, maybe you'd get bugs of this form: w = x.y.z!() # Do something with w, thinking it's a reference to x Not that you'd go very far before discovering the bug, but it'd probably annoy the guy reading the code. :) If you want the object, then use the object (i.e. if you want to print the list, then print the list), but making tricked out method calls that return themselves just to save a line or two of code sacrifices clarity for too little benefit. Ah well, I guess that's why I use Python, huh? :) Best of luck, Dave From chuck at smtl.co.uk Mon Jun 14 12:06:48 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Mon, 14 Jun 2004 17:06:48 +0100 Subject: Script parse output screen but cant get desired output new file!. In-Reply-To: <84k6ygmg30.fsf@redpeanut.com> References: <84k6ygmg30.fsf@redpeanut.com> Message-ID: <1087229208.16436.8.camel@sevenofnine.smtl.co.uk> On Thu, 2004-06-10 at 01:03, David Fisher wrote: > chuck amadi writes: > > fp = open("/home/chuck/pythonScript/testbox") > > mbox = mailbox.UnixMailbox(fp, email.message_from_file) > > for mail in mbox: > > print mail['Subject'] > > print mail.get_content_type()#text/plain > > print mail.get_payload() > If your going to use the UnixMailbox in two different loops, you'll > need to reinitalize it. Just call: > > fp = open("/home/chuck/pythonScript/testbox") > mbox = mailbox.UnixMailbox(fp, email.message_from_file) > > again before you use 'mbox' again. Otherwise the file pointer is > still pointing at the end of the file which is why you get nothing the > second time. Or alternately, just to be more confusing :), use: > > for mail in mailbox.UnixMailbox(open("/home/chuck/pythonScript/testbox"), \ > email.message_from_file): > print mail['Subject'] > print mail.get_content_type()#text/plain > print mail.get_payload() > > Which does it all in one stroke. > > Oh, minor nitpick. open(filename) is depredicated I believe. The new > prefered (for now :P) usage is file(filename). Which makes sense > since it returns a file object not an 'open' object > > ><{{{*> By the way list is there a better way than using the readlines() to parse the mail data into a file , because Im using email.message_from_file it returns all the data i.e reads one entire line from the file , headers as well as just the desired body messages . fp = file("/home/chuck/pythonScript/testbox") mb = mailbox.UnixMailbox(fp, email.message_from_file) mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") for mail in fp.readlines(): mailout.write(mail) Something like this> for mail in mb: body = mail.get_payload() mailout.write(body) # write only the body messages to SurveyResults.txt Cheers if the is a better way I can't get my head round how I can print mail ( only the body messages) to screen and the entire mail headers and body to the new file. Hi have any one got any suggstions to my script I can parse the email body messages to screen but I want the same desired effect to save to a new file.I have tried a few things to no effect. From lights at cix.co.uk Fri Jun 25 11:13:32 2004 From: lights at cix.co.uk (Matthew Bell) Date: 25 Jun 2004 08:13:32 -0700 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> <4d79c4d9.0406240854.13489b48@posting.google.com> Message-ID: <4d79c4d9.0406250713.4caa4e54@posting.google.com> Les Smithson wrote in message news:... > I have to ask this - did you look at snmpy > (http://snmpy.sourceforge.net)? This uses ucd-snmp/net-snmp for the > grunt. It doesn't claim to be ported to Windows, but net-snmp is, and > the C module in snmpy doesn't *look* that difficult to build on > Windows. Yes, I did look at snmpy. And was instantly scared off by the obvious need to hack about with the C module to get it to compile on Win32. I haven't even been able to get net-snmp itself to compile on Win32 - I tried to follow the net-snmp readme about compiling it with cygwin and just ended up in a world of pain. The thought of doing the same for snmpy brings me out in hives. For better or for worse, I don't come from a UNIX / C background and so while such things may be straightforward for some, they're not for me. Thanks anyway, Matthew. From __peter__ at web.de Thu Jun 17 04:07:45 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 10:07:45 +0200 Subject: Regular expression, "except end of string", question. References: Message-ID: Peter Hansen wrote: > David Eppstein wrote: > >> Do you really need regexps for this? >> >>>>>string = "WHITE/CLARET/PINK/XL" >>>>>'-'.join(string.split('/',2)) >> >> 'WHITE-CLARET-PINK/XL' > > Dang! I started with split('/', 2) but stared at the > result trying to figure out how the heck to join it > to get the right result and ended up punting. :-( Strictly speaking the problem is underspecified, and your original solution might still be the best if claret is out tomorrow. Peter From rigga at hasnomail.com Tue Jun 15 04:25:34 2004 From: rigga at hasnomail.com (RiGGa) Date: Tue, 15 Jun 2004 09:25:34 +0100 Subject: Help with parsing web page References: Message-ID: RiGGa wrote: > Hi, > > I want to parse a web page in Python and have it write certain values out > to > a mysql database. I really dont know where to start with parsing the html > code ( I can work out the database part ). I have had a look at htmllib > but I need more info. Can anyone point me in the right direction , a > tutorial or something would be great. > > Many thanks > > RiGga Anyone?, I have found out I can use sgmllib but find the documentation is not that clear, if anyone knows of a tutorial or howto it would be appreciated. thanks R From imbosol at aerojockey.invalid Mon Jun 14 18:49:09 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 14 Jun 2004 22:49:09 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: Steve Lamb wrote: > > > On 2004-06-14, Carl Banks wrote: >> Ryan Paul wrote: >>> ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| >>> Dir[$prefix+fn].collect {|x| >>> x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| >>> `cat #{sesc x}.* > #{sesc x}`} } > >> Oh boy. I believe this untested Python code does what you want, also >> one line, also wrapped in the name of "clarity." > >> for f in dict([(__import__('re').sub(r"\.\d+[\d.-]*$","",x),None) >> for fn in ("*.rar.*","*.r[0-9][0-9].*") >> for x in __import__('glob').glob(prefix+fn)]): >> __import__('os').system("cat %s.* > %s" % (sesc(f),sesc(f))) > >> This would take about 7 lines in well-written Python, not 15. > >> bad-code-can-be-written-in-any-language-ly yr's, > > Ok, see, here's the thing. I look at the Ruby code and can kind > of follow it. I look at the Python code and can kind of follow it. > but in neither case have I, in glancing here and there today, been > able to decipher exactly what is going on. Care to show the 5 line > long form to see if I get that? No explination, just curious to see > if I can get it reading real code instead of hacked up line noise. Of course you can. import glob import os import re f = {} for pattern in ("*.rar.*","*.r[0-9][0-9].*"): for listing in glob.glob(prefix+pattern): f[listing] = None for filename in f: os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) I don't know what sesc is. I assume he had defined it elsewhere, because he said this was only part of a script he wrote (and that's what scares me--I can understand a throwaway one-liner looking like this, but not a line in a script). -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From dkuhlman at rexx.com Thu Jun 24 19:35:13 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 24 Jun 2004 16:35:13 -0700 Subject: How to call Java from Python? References: <2jrnfdF1592c4U1@uni-berlin.de> Message-ID: <2k16pdF175b0aU1@uni-berlin.de> Steve Menard wrote: [snip] > > Seems like my project my project got started at the right time :) > > Take a look at JPype http://jpype.sourceforge.net > > it aims to do what JPE did (but work). > > It is still early in development, and working on win32 exclusively > for now (the linux port should consist only of a few lines of > code, but I do not have a linux meachine readily available). If > you have a little C coding knowledge, you might even contribute it > :) > > What's more, your's truly is doing his best to answer question and > fix problems as they arise. > > I hope this helps, > > Steve Menard JPype looks like the real solution to me. And, I hope to use and help with it. However, I'm on Linux. So, until JPype supports Linux, I've done something a bit simpler (or maybe not) in the meantime, here is a mini-announcement. generate_wrappers.py ==================== ``generate_wrappers.py`` generates support files that enable Python to use the classes and methods in a Java source code file. This facility requires and uses ``gcj``, "The GNU Compiler for the Java Programming Language". It can be used only on platforms that support ``gcj``, ``gcjh``, and ``libgcj``. The basic strategy is the following: 1. Use ``gcjh`` to generate a header file for your Java class. 2. Write adapter classes, methods, and functions that use the CNI (the Compiled Native Interface) API to talk to your Java class. 3. Use SWIG to create Python wrappers for your adapter classes, methods, and functions. 4. Compile the resulting source code to produce Python extension (a shared library) that you can be import from Python. ``generate_wrappers.py`` helps you by generating some of the files you need and by generating a ``Makefile`` that generates others. *But*, you will need to write the C/C++ adapter classes, methods, and functions by hand yourself. And, this will require that you know enough CNI to do so. Where to get it -- You can find it at: http://www.rexx.com/~dkuhlman/generate_wrappers.html http://www.rexx.com/~dkuhlman/generate_wrappers-1.0a.tar.gz I'm interested in any suggestions, criticisms, ideas, etc. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From jasper_marzin at yahoo.com Sun Jun 27 22:18:05 2004 From: jasper_marzin at yahoo.com (Jasper) Date: 27 Jun 2004 19:18:05 -0700 Subject: know how to install GMP properly for usage by programs ? Message-ID: <89b27d52.0406271818.1feb1fae@posting.google.com> Hello pythoners I followed the directions on how to install GNU GMP for windows (below and on the URL) http://www.cs.nyu.edu/exact/core/gmp/ and I don't notice any performance gain..in Perl one is supposed to place this in the code: use Math::BigFloat lib => 'GMP'; But I notice zero difference in calculation speed..I realize this is a python board, but I am wondering if there is anyone who knows how to verify installation, or any tricks to ensure the library is actually being used, like executing the program in the GMP directory or something.. any tips would be appreciated.. Thank you, Jasper Marzin ****************** Installing GMP on Windows: Install latest Cygwin. Make sure that you choose to install "gcc", "m4" and "make" since the default installation doesn't include them. Download latest GMP from GNU MP to ${gmp_download}. Run "Cygwin Bash", unzip and untar GMP into ${gmp_build} using following command: cd ${gmp_build} tar xzvf ${gmp_download}/gmp-x.x.x.tar.gz Configure GMP for compilation: cd gmp-x.x.x ./configure --prefix=${gmp_install} Build GMP: make Install GMP header files and lib files: make install From porky_pig_jr at my-deja.com Thu Jun 3 01:03:36 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 2 Jun 2004 22:03:36 -0700 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> <10bsls7skd4ul7e@corp.supernews.com> Message-ID: <56cfb0e3.0406022103.211f06f8@posting.google.com> Nop, a class Rectangle is defined as a new style class. Nuthsell, page 85. It is given as a part of discussion of 'properties', also part of new style classes. My apologies for refering to the parent class, rather than providing its complete definition. This is one of the golden rules when asking for support: provide complete list of session -- and I did not. Mea culpa. Let me start all over. Here is the complete IDLE session, except on a different machine with Python 2.3.3 rather than 2.3.4 but I assume this shouldn't reallhy matter: Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.0.2 >>> class Rectangle(object): # defined as new class def __init__(self, width, heigth): self.width = width self.heigth = heigth def getArea(self): return self.width * self.heigth area = property(getArea, doc='area of the rectangle') >>> rect = Rectangle(4,5) >>> rect.area 20 >>> class OptimizedRectangle(Rectangle): # subclass with __slots__ __slots__ = 'width', 'heigth' >>> optrec = OptimizedRectangle(3,4) >>> optrec.area 12 >>> optrec.__dict__ # note that __dict__ shows up (why?) {} >>> optrec.newarea = 12 # so I can define new attribute on a fly >>> optrec.newarea 12 >>> >>> optrec.__slots__ # slots are the part of instance ('width', 'heigth') >>> >>> optrec.__dict__ # but so is the dict {'newarea': 12} >>> TIA. From lbates at swamisoft.com Thu Jun 3 17:08:36 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 16:08:36 -0500 Subject: Perlish dictionary behavior References: Message-ID: You can do this with: thingCounts={} for thing in file: thingCounts[thing]=thingCounts.get(thing, 0)+1 Larry Bates Syscon, Inc. "Chris" wrote in message news:fa7108b0.0406031202.6ab7cc8d at posting.google.com... > One nice thing about Perl that is helpful when tallying things up by > type is that if you increment a hash key and the key does not exist, > Perl puts a one there. So you can have code that does something like > this: > > my %thingCounts; > foreach my $thing() > { > $thingCounts{$thing}++; > } > > (I think the syntax is right, but with Perl I never am sure). > > In Python, this would generate a KeyError. So you'd do something like > > thingCounts = {} > for thing in file: > try: > thingCounts[thing] += 1 > except KeyError: > thingCounts[thing] = 1 > > Is there any clever way to be able to just say, like in Perl, > for thing in file: > thingCounts[thing] += 1 > > and have it do the above? Perhaps with a custom dictionary class or > something? Just wondering what that might look like. > > Just curious. Thanks. > -Chris From dooms at info.LESS.ucl.SPAM.ac.be Fri Jun 18 03:39:57 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Fri, 18 Jun 2004 09:39:57 +0200 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: <200406152201.20003.troy@gci.net> Message-ID: <40d29c7b$0$84231$5fc3050@dreader2.news.tiscali.nl> Mark Hahn wrote: > Troy Melhase wrote: > > >>Here's an idea: if it ain't broke, don't fix it. >> >>Seriously, you see a "wart" and a "problem". I see a pleasant >>side-effect of the documented semantics. True, new folks are >>surprised by the behavior, but once it's understood, it becomes more >>powerful. > > > All four of the Python gotcha's, wart's and regrets lists I have found > included this problem. It is not only a newbie's problem as I showed in my > posting. > > >>How do you intend to account for code like this: >> >>def F(a, b, cache={}): >> try: >> return cache[(a,b)] >> except (IndexError, ): >> value = cache[(a,b)] = do_some_long_calc(a,b) >> return value >> >>Or even this: >> >>shared_cache = {} >> >>def F(a, b, cache=shared_cache): >> ... > > > The first example is very unreadable and uncool in general. Your second > example will work just fine with our fix. > > >>Of course you can argue that this is bad style, > > > Yes I (and many others) will. > > >>but the counter >>argument is just as strong: this is quite pythonic and quite >>readable. > > > I disagree strongly. I would never be caught coding something like that and > I love Python dearly. > > >>Python is a tool, and you decrease the utility of that tool when you >>limit it's idioms. > > > So far you have only shown me an idiom that many say should not be used. > Show me one that everyone agrees is useful. > > >>>How much Python code would these different proposals break? >> >>A lot. I ran this: >> >>$ find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} >>\; | wc >> >>And see 67 instances just in the standard library. Multiply that by >>a factor of 1000, 10000 or more to reflect code in the field, and you >>might start to understand the significance of changing the language >>definition. > > > That count is not accurate. Fixing this will not break every use of [] as a > default formal param. Using [] in __init__ for example would break nothing. > I can think of many other cases where it is legal to use []. The only case > I can think of that would break would be the idiom we disagree on above. If > I am wrong, then show me other cases. > Right. I'd like to see how many of these 67 instances of mutable def args actually mutates them. I hope it is 0. In this case the proposed modification would break nothing at all. But I wonder what the actual semantics of the second proposal are. You say the default argument is evaluated in its declaration context at each call. But is that evaluation context garanteed to be the same at every call ? #Ex: x=0 def t(a,b,c=x+1): # could I assert c==1 if t called with 2 args ? def make_some_obj(): return [] def t(a,b,c=make_some_obj()): # can I assert c==[] if t called with 2 args ? I think every data coming from outside the expression (the variables in the expression including the global variables accessed from a function) should be preserved. Let aside the eventual mutable state stored in an object: #Ex: class Inc: def __init__(self): self.x=0 def newval(): self.x += 1 return self.x x=Inc() def t(a,b,c=x.newval()): # can I assert c will increase by 1 at each call with 2 args ? > If I also might make a general argument for the fix then let me continue. > Doing a late evaluation of the default expression makes the language more > dynamic, which fits the overall goal of making Prothon more dynamic. Using > prototypes instead of classes, dynamic var scoping, this fix, and many other > Prothon changes from Python all work towards that goal. > > Dynamic var scoping fixed another Python gotcha which doesn't break > anything. Here are the two versions of code showing the problem and the > fix: > > --- Python --- > > >>>>x = 1 >>>>def f(): > > ... x = x + 1 > ... print x > ... > >>>>f() > > UnboundLocalError: local variable 'x' referenced before assignment > > --- Prothon --- > > O>> x = 1 > 1 > O>> def f(): > ... x = x + 1 > ... print x > ... > O>> f() > 2 > > Prothon's scoping rules are dynamic which means that x comes from outside > the function until the actual assignment happens. At that point x becomes a > local variable. This, along with the fact that vars are inherited from > ancestors along with methods, allow for some intuitive and simple var > initialization techniques. So then 0>> f() 2 0>> x 1 > > Obviously it is the responsibility of the programmer to make sure that the > outer x has the proper initialization value for the local x. This can cause > a hiding-of-uninitialized-vars bug if the programmer uses the same names for > unrelated variables but it is worth the extra power and intuitiveness. > Nice, I had never heard about Prothon. I'll give it a look. -- Gr?goire Dooms From faassen at infrae.com Wed Jun 2 11:22:12 2004 From: faassen at infrae.com (Martijn Faassen) Date: Wed, 02 Jun 2004 17:22:12 +0200 Subject: last chance for online EuroPython registration! Message-ID: Online registration for EuroPython 2004 is open until 3 June at 23.00 CET -- that's just a week away. That is *tomorrow* at the time of this writing. So if you haven't registered yet, do so soon! Registration at the door will be possible, but more costly and cash only. Don't miss out on what will be *the* European Python and Zope event of the year! To register online, visit: http://www.europython.org/conferences/epc2004/registration_html For more information about EuroPython 2004, see our website: http://www.europython.org From paddy3118 at netscape.net Sat Jun 5 16:11:07 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Sat, 05 Jun 2004 21:11:07 +0100 Subject: python vs awk for simple sysamin tasks In-Reply-To: References: Message-ID: Matthew Thorley wrote: > My friend sent me an email asking this: > > > I'm attemtping to decide which scripting language I should master and > > was wondering if it's possible to do > > these unixy awkish commands in python: > > > > How to find the amount of disk space a user is taking up: > > > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > > {print "User rprice total disk use = " sum}' > > > > How to find the average size of a file for a user: > > > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > > {print "The ave size of file for rprice is = " sum/NR}' > > I wasn't able to give him an afirmative answer because I've never used > python for things like this. I just spent the last while looking on > google and haven't found an answer yet. I was hoping some one out there > might have some thoughts ? > > thanks much > -matthew I think you will find that the examples could be re-written in python (or perl), but assuming you have created the one liners above and so know your way around 'the basics' then you would be most productive in leaving a space for find and bash and sed and awk and grep ... for mainly smaller scripts Python is not good for one liners but tends to be easy to maintain. I don't believe that you should abandon AWK once you learn Python, especially if you do Sys-Admin work. Python has a broad range of uses but it is not better than AWK in all cases, as I think others have shown in the thread by giving a much longer Python version of an example. Cheers, Paddy. From klachemin at home.com Mon Jun 7 22:27:52 2004 From: klachemin at home.com (Kamilche) Date: 7 Jun 2004 19:27:52 -0700 Subject: Brain Dead Singleton References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> <40C1B470.1000407@jessikat.fsnet.co.uk> <40C4209A.6090403@jessikat.fsnet.co.uk> <40C4F149.7080607@jessikat.fsnet.co.uk> Message-ID: <889cbba0.0406071827.13f3fe2e@posting.google.com> Well, to cop a phrase from 'Brother Where Art Thou?', "I'm with you fellers." You both are much more experienced than I, so much so that I don't even know what you're talking about, yet. :-o From peter at engcorp.com Thu Jun 24 10:08:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jun 2004 10:08:42 -0400 Subject: python service problem In-Reply-To: <6NKdnaDwjYlTQUfdRVn-uA@comcast.com> References: <6NKdnaDwjYlTQUfdRVn-uA@comcast.com> Message-ID: Larry Bates wrote: > "David Fraser" wrote: > >>One thing I noticed about the first computer is that, even after >>uninstalling everything, there were some registry entries to do >>with the installed services. I could not delete these entries - I >>got an access denied error (details below) [...] > I can tell you that I use InnoInstaller to do my installations > and have it "clean" up during uninstallation by removing the > left over registry keys. If you cannot remove them, I would > suspect a "rights" issue (no administrative rights?). For what it's worth, in a possibly related situation we just encountered something similar. In our case it was not a service, but a COM server (using ctypes or win32com, running as LocalServer32 which launches pythonw.exe in the background). On my machine I've had no troubles, but on a remote machine there were "access denied" errors whenever the developer tried to "-unregserver", which removes the registry entries. I believe he tried removing them manually as well, but could not. It was a long-distance thing, so I couldn't troubleshoot it myself... I theorized there was a leftover process running, but after checking over the task list he insisted there was not anything active that could be doing this. A reboot cured the problem, and so far we haven't seen it again. He definitely had administrative rights, so it wasn't that. I'm positive it was a leftover "lock" of some kind, but I don't know anything about that area of Windows so we just moved on. My point is that it may not even be limited to the service stuff, but could be a little broader, maybe more fundamental to doing these kinds of background things using Python under Windows. -Peter From NOSPAM at easyconnect.fr Wed Jun 9 04:42:06 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Wed, 9 Jun 2004 10:42:06 +0200 Subject: compiling python with unix References: <40c033e0$0$2277$afc38c87@news.easynet.fr> <10c0un6nf57b4ce@corp.supernews.com> Message-ID: <40c6ce7b$0$17482$afc38c87@news.easynet.fr> "Cameron Laird" a ?crit dans le message de news:10c0un6nf57b4ce at corp.supernews.com... > In article <40c033e0$0$2277$afc38c87 at news.easynet.fr>, > RosalieM wrote: > >I would like to understand what python needs to work on unix. > >And to understand how i can make it smalest possible? > >I dont understand at all setup. > > > >I searched in python.org and in sources but it is not clear at all for me. > > > >Can python run with a posix C compiler and minix or something like that ? > . > . > . > There are probably simple answers to your questions. It > might take a bit of conversation before we understand each > other's language. > > Most Unix host nowadays install with Python already present. > Under MacOS and nearly all Linux distributions, for example, > I can type at the command line, and receive responses: > # python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> 3 + 8.5 > 11.5 > >>> print("Hello, world.") > Hello, world. > Is that the sort of information you seek? If you prefer, > fr.comp.lang.python is also available as a Usenet newsgroup. > -- > > Cameron Laird > Business: http://www.Phaseit.net I used a lfs 4.0 to build my unix. But is is very fat (250 M). I can compile python from there and play with "Hello World", but i dont uderstand how to choose what i need and what i dont need to compile python (library needed) and how to choose features that python would be able to do (for example if i dont inted to use some modules). My questions are like : For example, can i build python on a minix system? Why socket module needs threads to compile ? I search answers to this kind of questions. You may right saying that it is possible that there is simple answers and i may ununderstand some basic features of how system works if so give me direction to search, because as i told i looked into python site for documentation about this and found nothing. Thanks. From axel at axel.truedestiny.net Thu Jun 3 11:19:13 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Thu, 03 Jun 2004 15:19:13 GMT Subject: speed problems References: Message-ID: "Jacek Generowicz" wrote in message news:tyfvfi8g02f.fsf at pcepsft001.cern.ch... > "^" writes: > > > could you please [...] tell me where I should look for > > optimizations? > > import profile > help(profile) > > import hotshot > help(hotshot) > > (Teach a man to fish ... and all that :-) :-) That's kewl! Thanks! Regards, Axel From davidf at sjsoft.com Tue Jun 1 05:12:03 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Jun 2004 11:12:03 +0200 Subject: Will there be Function/class decorators in Python 2.4?? In-Reply-To: <40bc2cff$0$130$e4fe514c@dreader18.news.xs4all.nl> References: <40bc2cff$0$130$e4fe514c@dreader18.news.xs4all.nl> Message-ID: Iwan van der Kleyn wrote: > Anthony Baxter wrote: > >> the first alpha of Python 2.4 is about a month away. > > > Anyone know whether 2.4 will include function/class decorators? > > http://python.fyxm.net/peps/pep-0320.html - Python 2.4 Release Schedule > http://python.fyxm.net/peps/pep-0318.html - Decorators for Functions, > Methods and Classes > http://shattered.teched.net/www.python.org/peps/pep-0318.html - > Function/Method Decorator Syntax > > Basically, when I try to explain to other developers how you have to > define a property or class method in Python, the general response is > "why did they came up with that hare brained idea!?". I cannot find > another answer then to say that the python developers in this case > created the infrastructure but forgot the syntax. Whether or not that is > the case, I think you can fairly argue that the present syntax goes > against the grain of one of Python's core qualities: code clarity. > > Any thoughts or remarks? > > (Or am I missing something here? In the PEP 318 Guido van Rossum is > stated to express "skepticism about the concept") I think the concept of decorators is great, but I don't like the syntax: def foo(cls) using [synchronized(lock), classmethod]: pass What would be a really nice syntax that has the disadvantage of being totally insane, but seems much more logical / expressive to me: classmethod foo(cls): pass synchronized(lock) classmethod foo(cls): pass Or in a more standard way: def classmethod foo(cls): pass def synchronized(lock) classmethod foo(cls): pass Anyway the syntactic concept here is using the decorator as an adjective: define *this* kind of method. I think this represents the intent of the statement better than using [list of functions] does. Well there's been lots of discussion about this before and I'm not neccessarily adding much new but you asked :-) David From fishboy at spamspamspam.com Wed Jun 2 09:23:30 2004 From: fishboy at spamspamspam.com (fishboy) Date: Wed, 02 Jun 2004 13:23:30 GMT Subject: strange socket behaviour References: Message-ID: <82jrb0t5ss1dtf9qki44qphd13t0vpnl02@4ax.com> On Wed, 2 Jun 2004 10:37:21 +0800, "Joe Wong" wrote: >Hello, > > I have a short program that the client make a connection to server, a thread is then created to poll any data sent from the server. The main thread will close the socket after 5 seconds. Here are the code: > >from socket import * >import select >import threading >import time > >def poll(c): > i, o, e = select.select([c], [], []) > if not i: > print "time out" > return > print i > data = i[0].recv(1024) > print "data: ", data > >if __name__=="__main__": > c = socket(AF_INET, SOCK_STREAM) > c.connect(('192.168.100.74', 8888)) > th=threading.Thread(None, poll, "", (c, )) > th.setDaemon(1) > th.start() > > time.sleep(5) > c.shutdown(2) > c.close() > th.join() > print "completed" > >On Windows, as soon as client socket 'c' is closed, the select() call returns. However, on Linux, the program seems blocking forever ( may be I am not patient to wait ). Is there anything wrong with my code? > >Regards, > >-- Wong No, your code is ok. It's just that closing the local end of the socket is undefined in select(). Which is why Windows does one thing and Linux the other. Closing the remote end causes the socket to show up as readable with zero data. ><{{{*> From jcarlson at uci.edu Thu Jun 10 03:44:40 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 10 Jun 2004 00:44:40 -0700 Subject: Passing file descriptors In-Reply-To: References: Message-ID: > I've tested the data transfer and it works fine. > > Using the below modified code, unix domain sockets do not work. Any > other ideas? Oh, and on SunOS 5.8, using unix domain sockets gets the following error: jcarlson at synergistic-envision% python2.3 fdpass.py [Errno 122] Operation not supported on transport endpoint I needed to interrupt it because the read blocks in the child process. - Josiah From tim.peters at gmail.com Wed Jun 16 23:11:49 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 16 Jun 2004 23:11:49 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <40D016A1.2030707@egenix.com> References: <1f7befae0406142036442bf372@mail.gmail.com> <40CEFB48.7080807@egenix.com> <1f7befae04061518082f839cb3@mail.gmail.com> <40D016A1.2030707@egenix.com> Message-ID: <1f7befae04061620112a0a91ac@mail.gmail.com> [Tim Peters] >> There should be a standard Decimal type in 2.4, but there won't be a C >> interface at first (it's pure Python code -- in Python CVS >> sandbox/decimal/). [M.-A. Lemburg] > Will it be turned into a C implementation at some point ? I hope so, but that depends on volunteers appearing to do the work. This is a Python implementation of IBM's proposed standard for decimal arithmetic: http://www2.hursley.ibm.com/decimal/ and is quite an involved piece of work. The integration with Python will be weak at first, and it's probably more important to work on that. For example, the builtin round() function won't know what to do with Decimal instances, and neither will float format codes (e.g., '"%10.3f" % some_Decimal' won't work in a reasonable way at first). Involved as it already is, it's just a start at a complete numeric facility. From claird at lairds.com Fri Jun 4 09:36:38 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 04 Jun 2004 13:36:38 -0000 Subject: compiling python with unix References: <40c033e0$0$2277$afc38c87@news.easynet.fr> Message-ID: <10c0un6nf57b4ce@corp.supernews.com> In article <40c033e0$0$2277$afc38c87 at news.easynet.fr>, RosalieM wrote: >I would like to understand what python needs to work on unix. >And to understand how i can make it smalest possible? >I dont understand at all setup. > >I searched in python.org and in sources but it is not clear at all for me. > >Can python run with a posix C compiler and minix or something like that ? . . . There are probably simple answers to your questions. It might take a bit of conversation before we understand each other's language. Most Unix host nowadays install with Python already present. Under MacOS and nearly all Linux distributions, for example, I can type at the command line, and receive responses: # python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 3 + 8.5 11.5 >>> print("Hello, world.") Hello, world. Is that the sort of information you seek? If you prefer, fr.comp.lang.python is also available as a Usenet newsgroup. -- Cameron Laird Business: http://www.Phaseit.net From me at privacy.net Wed Jun 9 04:42:36 2004 From: me at privacy.net (Duncan Booth) Date: 9 Jun 2004 08:42:36 GMT Subject: Destructors and exceptions References: Message-ID: dkturner at telkomsa.net (David Turner) wrote in news:e251b7ba.0406082329.f0692fd at posting.google.com: >> When an exception is handled, you can access the stack traceback. >> This contains references to all the local variables which were in >> scope at the point when the exception was thrown. Normally these >> variables would be destroyed when the functions return, but if there >> is a traceback referencing them they stay alive as long as the >> traceback is accessible which is usually until the next exception is >> thrown. > > Then why not unreference the traceback (and therefore destroy it and > the down-stack locals, if the exception handler hasn't made another > reference) at the end of the handling suite? Fine, except that isn't what Python does now, and the current behaviour needs to be kept for compatibility. So if that is the behaviour you want, you have to do that explicitly yourself at the end of every exception handler. From km at mrna.tn.nic.in Sat Jun 12 11:07:39 2004 From: km at mrna.tn.nic.in (km) Date: Sat, 12 Jun 2004 20:37:39 +0530 Subject: datastructures Message-ID: <20040612150739.GA9555@mrna.tn.nic.in> hi all, how to create hash of an array in python as exists in perl ? how abt dict of dicts ? array of dicts etc ? regards, KM From olku at web.de Mon Jun 7 12:08:54 2004 From: olku at web.de (Oliver Kurz) Date: Mon, 7 Jun 2004 18:08:54 +0200 Subject: Decoding 'funky' e-mail subjects References: Message-ID: Have you tried decode_header from email.Header in the python email-package? Best regards, Oliver From insert at spam.here Wed Jun 16 22:17:11 2004 From: insert at spam.here (Doug Holton) Date: Wed, 16 Jun 2004 21:17:11 -0500 Subject: Regular expression, "except end of string", question. In-Reply-To: References: Message-ID: Derek Basch wrote: >string = "WHITE/CLARET/PINK/XL" > >which I need to alter to this format: > >string = "WHITE-CLARET-PINK/XL" You need the (?!...) operator: http://docs.python.org/lib/re-syntax.html import re #replace "/" with "-" if not followed by a word at the end of the string print re.sub(r"/(?!\w+$)",r"-",s) but like they said, join and split are better here instead of using regular expressions. From elbertlev at hotmail.com Thu Jun 24 10:42:03 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 24 Jun 2004 07:42:03 -0700 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: <9418be08.0406240642.6b7797f@posting.google.com> Very good! One remark: translate method is much slower then "c in string" method in the case when the test string is very long (say 5mb) and the invalid character is located close to the beginning of the string. (10000 times slower!) klachemin at home.com (Kamilche) wrote in message news:<889cbba0.0406232245.53b9025e at posting.google.com>... > I was looking for a way to speed up detecting invalid characters in my > TCP string, and thought of yet another use for the translate function! > If you were to 'translate out' the bad characters, and compare string > lengths afterwards, you would know whether or not the line contained > invalid characters. The new method is more than 10x faster than the > standard 'if char in string' test! So - here's the code plus sample > timings: > > ''' > Translate Speed Test > > This code looks for invalid characters in a string, > and raises an exception when it finds one. > I'm testing 2 methods: the 'if char in string' method, > and one based on using the 'translate' function and > comparing string lengths afterwards. > Wow, what a difference! Translate is over 10x faster! > > Function Loops Seconds Loops/sec > *********************************************** > In 10000 0.171 58479 > Translate 10000 0.016 624998 > > ''' > > import mytime > import string > > > _allchars = None > _deletechars = None > _validchars = string.ascii_letters + string.digits + \ > "!@#$%^&*()`~-_=+[{]}\\|;:\'\",<.>/?\t " > > > def init(): > global _allchars, _deletechars > l = [] > a = [] > for i in range(256): > a.append(chr(i)) > if not chr(i) in _validchars: > l.append(chr(i)) > _deletechars = ''.join(l) > _allchars = ''.join(a) > > > def test(): > max = 10000 > tmr = mytime.Timer() > r = range(max) > s = "This is a string to test for invalid characters." > print tmr.heading > > tmr.startit() > for i in r: > for c in s: > if c in _deletechars: > raise Exception("Invalid character found!") > tmr.stopit(max) > print tmr.results('In') > > tmr.startit() > for i in r: > s2 = s.translate(_allchars, _deletechars) > if len(s2) != len(s): > raise Exception("Invalid character found!") > tmr.stopit(max) > print tmr.results('Translate') > > > init() > > if __name__ == "__main__": > test() From max at alcyone.com Sun Jun 27 17:48:48 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 27 Jun 2004 14:48:48 -0700 Subject: Python Magazine exists! (was: Python intro questions) References: Message-ID: <40DF40C0.9503E50D@alcyone.com> Mark wrote: > I honestly find your characterzation very unfair. Regarding payment to > the > Python Software Foundation this is what I wrote: ... > I take full responsibility and will get an email by Monday *and you > will be paid* latest by Wednesday if you have a Paypal account. Sorry. Seems like it's a little silly to call his characterization unfair when he hasn't even been paid yet. (Now, he himself doesn't worry too much about getting paid, that's not why he did it, but surely the most fundamental contract between a writer and his publisher is that the writer actually gets paid for it.) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Whoever named it necking was a poor judge of anatomy. -- Groucho Marx From lights at cix.co.uk Wed Jun 23 16:32:28 2004 From: lights at cix.co.uk (Matthew Bell) Date: 23 Jun 2004 13:32:28 -0700 Subject: SNMP Toolkit Message-ID: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> Hi, I'm looking for a high-performance SNMP manager toolkit (SNMPv1 / v2, GET / GETNEXT / GETBULK) I can use with Python on Windows2K/XP. I wonder if anyone has got any suggestions? Commercial software is fine, as it's for a specialised in-house application. I've tried PySNMP which, while a fine piece of code (I've learnt a lot looking through it!), it's fairly CPU intensive in my application. I've also tried using UCDSNMP via popen() but that has a tendency to hang in a multi-threaded environment. So, does anyone know of a solid, multi-threading capable, fast SNMP library with a reasonable Python interface that will run on Windows without me needing to get my head round a C compiler to build it? I know I should be all manly-man and hew my own C-based SNMP library from scratch but, basically, while I'm only a mediocre Python programmer, the last compiled language I used was COBOL... Thanks! Matthew. From klachemin at home.com Thu Jun 24 02:45:43 2004 From: klachemin at home.com (Kamilche) Date: 23 Jun 2004 23:45:43 -0700 Subject: Faster 'if char in string' test Message-ID: <889cbba0.0406232245.53b9025e@posting.google.com> I was looking for a way to speed up detecting invalid characters in my TCP string, and thought of yet another use for the translate function! If you were to 'translate out' the bad characters, and compare string lengths afterwards, you would know whether or not the line contained invalid characters. The new method is more than 10x faster than the standard 'if char in string' test! So - here's the code plus sample timings: ''' Translate Speed Test This code looks for invalid characters in a string, and raises an exception when it finds one. I'm testing 2 methods: the 'if char in string' method, and one based on using the 'translate' function and comparing string lengths afterwards. Wow, what a difference! Translate is over 10x faster! Function Loops Seconds Loops/sec *********************************************** In 10000 0.171 58479 Translate 10000 0.016 624998 ''' import mytime import string _allchars = None _deletechars = None _validchars = string.ascii_letters + string.digits + \ "!@#$%^&*()`~-_=+[{]}\\|;:\'\",<.>/?\t " def init(): global _allchars, _deletechars l = [] a = [] for i in range(256): a.append(chr(i)) if not chr(i) in _validchars: l.append(chr(i)) _deletechars = ''.join(l) _allchars = ''.join(a) def test(): max = 10000 tmr = mytime.Timer() r = range(max) s = "This is a string to test for invalid characters." print tmr.heading tmr.startit() for i in r: for c in s: if c in _deletechars: raise Exception("Invalid character found!") tmr.stopit(max) print tmr.results('In') tmr.startit() for i in r: s2 = s.translate(_allchars, _deletechars) if len(s2) != len(s): raise Exception("Invalid character found!") tmr.stopit(max) print tmr.results('Translate') init() if __name__ == "__main__": test() From OlafMeding at compuserve.com Wed Jun 23 11:58:45 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 23 Jun 2004 08:58:45 -0700 Subject: import pythoncom Message-ID: <9e5ea2c4.0406230758.2a95dfe6@posting.google.com> How does Python (version 23 on Windows) know what to import? I could not find a file or directory named "pythoncom". import pythoncom help(pythoncom) FILE c:\windows\system32\pythoncom23.dll Obviously Python knows to which DLL to load, but the DLL has a different name (pythoncom versus pythoncom32.dll). So how does this work? Thanks for you help. Olaf From dkturner at telkomsa.net Tue Jun 15 07:26:07 2004 From: dkturner at telkomsa.net (David Turner) Date: 15 Jun 2004 04:26:07 -0700 Subject: does python have useless destructors? References: <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: Roy Smith wrote in message news:... > dkturner at telkomsa.net (David Turner) wrote: > > > Destruction and finalization are *different things*. > > For those of us not up on such things, could you explain the differences? Destruction is what happens to objects in C++. C++ does not manage your memory for you, so destruction happens at very specific times: 1. For stack-based objects, when the object "goes out of scope". 2. For heap-based objects, when the object is explicitly destroyed with the delete operator. Finalization is what happens to objects in Java. Java manages your memory for you, so finalization happens at very specific times: 1. When the object is garbage collected. The difficulty here is of course that garbage collection is unpredictable, and finalization may not happen at all. So essentially, when we say "destruction", we mean an operation that is called clean up the object, where the programmer has some sort of control over when it happens; when we say "finalization" we mean an operation that is called to clean up the object, where the programmer has no control over when it happens. It's perfectly possible to have both destruction and finalization. Here is one way of doing it in Python: ----- class Both: def __init__(self): self.refcount = 0 def copy(self): self.refcount += 1 return self def unref(self): self.refcount -= 1 if self.refcount == 0: self.destruct() def destruct(self): print "destruction" def __del__(self): print "finalization" if __name__ == "__main__": x = Both().copy() y = x.copy() x.unref() y.unref() # "destruction" printed at this point # "finalization" probably printed here ----- Hmm... I wonder if it would be possible to override the "=" operator...? Regards David Turner From maxm at mxm.dk Wed Jun 9 04:31:43 2004 From: maxm at mxm.dk (Max M) Date: Wed, 09 Jun 2004 10:31:43 +0200 Subject: python.org CMS In-Reply-To: References: Message-ID: <40C6CAEF.50304@mxm.dk> Aahz wrote: > The team for www.python.org is taking another crack at considering a > content management system for handling the website's content. This is > particularly important considering, for example, how far beind we are in > posting job ads -- getting the community to do our grunt work for us is > the primary motivator. it *does* need a facelift :-) > Right now, Plone/Zope2 is the primary competitor simply because it's > well-publicized Good choice! > The data must be stored in a plain text format that would allow direct > access if the main system was not functioning. This doesn't necessarily > imply the ability to circumvent a web based layer by editing text files > directly Your intention is unclear here. If you don't have access to eg. a plone site, you cannot edit the "files" at all. But on the other hand Zope allways work ;-) > though there does need to at least be an easy way to export > and import such files for people who want to use a Real Editor [tm]. You can easily do that in Plone by using ftp or webdav. Using either some kind of structured tekst or html. The data is marshalled before and after editing. This makes it really easy to us normal tools. > Workflow is presumed to be a hierarchial publish reject model (in other > words as simple as is possible to begin with). We'll need both > coarse-grained and fine-grained security (giving people a variety of > access levels to large and small sections of the site). You can do that out of the box in Plone. Either setting permissions on folders manually, or by using one of the workgroup tools that makes it a bit simpler. > The system needs to work with browsers that have limited functionality > (i.e. Lynx). hmm! Why on earth would anybody want to do that. Well I guess that some techs can be stubborn. For editing it would be far easier to just ftp to the documents you want to edit and then use your editor of choice. Anyhoo it should work in Plone too. regards Max M From lbates at swamisoft.com Fri Jun 4 13:20:29 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 4 Jun 2004 12:20:29 -0500 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> Message-ID: I have a theory that the more experienced a programmer is (e.g. has used a number of "hard" languages for many years) the more they will like and be able to use the power of Python. I've been programming for over 30 years and I LOVE Python. I committed to doing all my coding in Python about 2 years ago and have never regretted it. I find that I'm still turning up "jewels" of programming methodology every day. The power of any good programming language is the ability to "hide" complexity without limiting flexibility. Python does an excellent job of this. I wouldn't have any problem starting beginning programmers with Python (it's much better than VB for the pure beginner). The beauty is that unlike many "beginner" languages it never seems to run out of power. You can write incredibly complex programs in Python that run well and are a joy to maintain. Python is pseudo-code that actually runs without being translated into some other language! The other thing I like is that it runs everywhere. I've written Windows NT services, Windows NT COM+ objects, regular text mode programs, Windows GUI programs (with wxWindows), Linux programs, dynamic webpage programs, etc. Without Python I would have to switch between 3-4 languages and would never get really proficient with any of them. The reusability of modules means that I can use modules that I've written for one project and easily use them for other projects. I start out with thousands of lines of mature, debugged code in these modules that gives me a real running start at the project at hand. Now I know that this ability is not unique to Python, it just seems that it gets used more than in most other languages. Glad you hare having fun. Larry Bates Syscon, Inc. "Kamilche" wrote in message news:889cbba0.0406040849.1d8bd884 at posting.google.com... > Man, I've been banging my head against a C program for a while now. > I'm embarrassed to admit how long. I really want to use Python, as I > mentioned in a prior post, but the speed hit is such that I'll > probably use it only for prototyping. > > But boy, development sure is fast in Python! Today, while playing with > it, I thought of a better way to arrange my data, that makes the > program more flexible. It's a good enough idea to warrant redoing my > code (even my C code) to take advantage of it. When I went to write up > the pseudocode to process the new method, I found myself naturally > using Python. > > C is just so... detail oriented. By the time I set up the data > structures, do the string manipulation and memory management, I can > hardly remember what it was I was initially trying to accomplish, much > less think of a better way to do it! Maybe I'm just getting old... but > Python just fits my idea of 'mental pseudocode' so well, it's hard to > resist using it. Dictionaries ARE an underutilized concept in DP, and > I was using them up the yin yang, even in my C program. Python meshes > well with my programming style. > > --Kamilche From haim at babysnakes.org Mon Jun 28 05:14:29 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Mon, 28 Jun 2004 12:14:29 +0300 Subject: sending signals to the calling function Message-ID: Hi I have a function that receive a list of files and creates a zip from these files. I want it to send signal to the calling function with the name of the file it currently compressing. is there a way to do this (without threads)? Bye -- Haim From lwliuwei at gmail.com Fri Jun 25 10:24:51 2004 From: lwliuwei at gmail.com (dimfox) Date: 25 Jun 2004 07:24:51 -0700 Subject: How to draw points of a curve References: <5e692f7f.0406241917.7b08940c@posting.google.com> Message-ID: <5e692f7f.0406250624.3415b016@posting.google.com> Thank you for the reply, But can you explain a little more? How to do the manual plotting? With which function? I am really new to this thing. Thank you "Mitja" wrote in message news:... > dimfox > (news:5e692f7f.0406241917.7b08940c at posting.google.com) wrote: > > Hi, I am new to Python. > > > > What I need to do is to calculate a curve and display it at the same > > time. I don't want to use the gplt.plot() because I need to show the > > animation of the curving growing. > > > > Which package should I use? Which function? > > Maybe there's a more elegant solution, but I'd go for manual plotting and a > slight delay before drawing each of the pixels (or rather segments to avoid > any empty spaces in case of steep curves) > > > > > Thank you From aahz at pythoncraft.com Wed Jun 16 22:23:08 2004 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2004 22:23:08 -0400 Subject: Regular expression, "except end of string", question. References: Message-ID: In article , Derek Basch wrote: > >It always comforting to know that a really simple solution exists after >you waste a couple of hours messing with Regular Expressions. :) 'Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.' --Jamie Zawinski -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From rob at schellgames.com Wed Jun 16 17:24:02 2004 From: rob at schellgames.com (rob at schellgames.com) Date: Wed, 16 Jun 2004 16:24:02 -0500 (CDT) Subject: squeezeTool help, making pyz files Message-ID: <2374.128.2.239.109.1087421042.squirrel@www.schellgames.com> I'm having some trouble using Fredrik Lundh's SqueezeTool utility. I can use the python file to create the SampleMod.py and SampleMod.pyz files, but then I am not sure how to use the pyz, or what should go in the appMain "start" module. I have had some success with very basic py's. Larger collections of py files with lots of interdependencies cause "No module named ..." errors. The only documentation I've found for it is within the file itself. Has anyone seen anything that explains how to use the final files, or any restrictions on file dependencies. thanks, Rob Gordon From Mike at DeleteThis.Geary.com Sat Jun 5 04:19:45 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 5 Jun 2004 01:19:45 -0700 Subject: heredoc and variables References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> <10c161nfembfq14@corp.supernews.com> Message-ID: <10c30h24e15dh14@corp.supernews.com> > Michael Geary wrote: > > If you can live with the newline at the end of the text > > (which in most cases is what you want anyway), this > > is the cleanest way to do it: > > > > end_html = """\ > > > > > > """ > > > > Or, you can get rid of both newlines this way: > > > > end_html = """ > > > > > > """[1:-1] flupke wrote: > Thanks for the sollution! De nada. Now that I think of it, if you do want to get rid of both newlines, here are a couple of other ways to do it: end_html = """\ \ """ That is a bit ugly, but this seems reasonable (and better than the [1:-1] slice trick): end_html = """\ """ -Mike From qrczak at knm.org.pl Sun Jun 13 05:56:55 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sun, 13 Jun 2004 11:56:55 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: On Sat, 12 Jun 2004 20:18:07 -0400, Humpty Dumpty wrote: > I have been hearing a lot of reference to Jython. This is yet another > example how coupling languages can stifle their progress: C++ is stifled by > its need for compatilibity with C, now clearly Python is becoming stifled by > a need for compatibility with Jython. I have a different point of view. Relying on timely finalization is stifling progress of the Python runtime. It prevents using better, more efficient GC techniques, which all happen to not have this property, and it prevents porting Python to other architectures like JVM and .NET. It's better to drop compatibility with this artifact of the poor but conceptually simple GC scheme used in CPython, and declare programs which rely on that implementation detail as broken. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From dguillaume at pi.be Tue Jun 29 12:34:48 2004 From: dguillaume at pi.be (Didier) Date: Tue, 29 Jun 2004 12:34:48 -0400 Subject: Writing an NLP System in Python References: Message-ID: <97e52d8519cff2734ed3d210a22080db@localhost.talkaboutprogramming.com> you can have a look at http://nltk.sourceforge.net it seems very nice but it can be obscur if you re new with python From winexpert at hotmail.com Fri Jun 11 10:25:48 2004 From: winexpert at hotmail.com (David Stockwell) Date: Fri, 11 Jun 2004 14:25:48 +0000 Subject: [python] struct module round off error? Message-ID: Hi Peter, Thanks for the help. I took a look at the link and then my python bible book and now see whats going on. I must have been not paying attention during the tutorial on this part because I DID go through the whole thing... > > When I first set it and print it, it has the correct value (50.3). > > > > However all i did was pack it, and then unpack it and it lost its > > definite value of 50.3. > > After the unpack it was approximately 50.3 (50.29999......) > >Actually, they have the same value each time. See http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate >for more... > >(Hint: try repr(d) right after you do d=50.3 and see what you get.) Thanks for the help David Stockwell ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From kkto at csis.hku.hk Tue Jun 1 02:49:13 2004 From: kkto at csis.hku.hk (Isaac To) Date: Tue, 01 Jun 2004 14:49:13 +0800 Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> Message-ID: <7ioeo3ydqu.fsf@enark.csis.hku.hk> >>>>> "Erik" == Erik Max Francis writes: Erik> To his credit, he was talking about declaring an array of strings Erik> as const char *const. That is, he was indeed making the data he Erik> was passing in truly const. As others have pointed out, though, Erik> that doesn't guarantee that that data will be put in read-only Erik> memory, only that it makes it possible. This is not quite right. A string literal is always put into read-only memory, no matter whether you specify const or not. So: int main() { char *str = "abc"; str[0] = '\b'; // segmentation fault } On the other hand, as I've stated in another thread, an array of initialized pointers can never be put into read-only memory in a module, due to other restrictions. Regards, Isaac. From adonisv at REMTHISearthlink.net Sun Jun 6 16:22:18 2004 From: adonisv at REMTHISearthlink.net (Adonis) Date: Sun, 06 Jun 2004 20:22:18 GMT Subject: Problem with Python xrange References: Message-ID: <_1Lwc.896$Y3.681@newsread2.news.atl.earthlink.net> "Christian Neumann" wrote in message news:mailman.631.1086545766.6949.python-list at python.org... > Hello, > > > > i have a problem with the built-in function xrange(). Could you by any > chance be able to help? > > > > I use Python 2.3.4 (final) and i think there is a bug in the built-in > function xrange(). > > > > An example is: > > > > x = xrange(2, 11, 2) ## [2, 4, 6, 8, 10] > > > > I get an TypeError if i use it with SliceType: > > > > x[1:4] ## It should be return an xrange object with length 3 > > > > Here is the error message: > > > > "TypeError: sequence index must be integer". > > > > Is this really a bug? > > > > Sincerely yours, > > > > Christian Neumann Not a bug... Adonis Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = range(10) >>> y = xrange(10) >>> type(x) >>> type(y) >>> help(xrange) Help on class xrange in module __builtin__: class xrange(object) | xrange([start,] stop[, step]) -> xrange object | | Like range(), but instead of returning a list, returns an object that | generates the numbers in the range on demand. For looping, this is | slightly faster than range() and more memory efficient. From lbates at swamisoft.com Tue Jun 8 09:17:25 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 8 Jun 2004 08:17:25 -0500 Subject: Passing parameters using **kargs References: Message-ID: <9PWdnS6v16v-IVjdRVn-vw@comcast.com> Since kargs is a regular dictionary variable, you can reference the variables you want with kargs.get('', None) example kargs.get('a', None) will return value of keyword argument a or None if 'a' doesn't exist. If you are sure of what will exist you can just use kargs['a'], but then you could more easily do f(a=None, **kargs) in that case. kargs.keys() will give you the names of the keyword arguments if you want them. No real reason to put them anywhere else that I can see. HTH, Larry Bates "Thomas Philips" wrote in message news:b4a8ffb6.0406071858.24dbb8ee at posting.google.com... > I want to access parameters that are passed into a function using the > **kargs idiom. I define f(**kargs) via > > def f(**kargs): > print kargs > . > . > > the keyword arguments are converted to a dictionary, so that if I type > f(a=1, b=2, c=3) > > the function prints > {'a': 1, 'b': 2, 'c':3} > > Now assume the function has three variables a, b and c to which I want > to assign the dictionary's values of 'a', 'b' and 'c'. How can I > assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I > be trying to construct a string representation of each variable's name > and using that as a key, or am I just thinking about this the wrong > way? > > Thomas Philips From zonepro-antivirus at sylvain.zonepro-serveurs.net Mon Jun 28 04:40:52 2004 From: zonepro-antivirus at sylvain.zonepro-serveurs.net (zonepro-antivirus at sylvain.zonepro-serveurs.net) Date: Mon, 28 Jun 2004 10:40:52 +0200 Subject: alerte zonepro (z)> antivirus [votre courriel : "Re: Your document"] Message-ID: <200406280840.i5S8eqOl018055@sylvain.zonepro-serveurs.net> * * * * * * * * * * * * * * * alerte zonepro (z)> antivirus * * * * * * * * * * * * * * * zonepro (z)> antivirus a detecte que le courriel envoye contient un virus dangereux : Worm/NetSky.P Ce courriel a ete detruit avec succes. ATTENTION ! VOTRE ORDIANTEUR SEMBLE ETRE INFECTE PAR UN VIRUS ! Optez pour la solution antivirus de zonepro (z)> antivirus. Mail-Info: --8<-- From: python-list at python.org To: webmaster at radiofg.com Date: Mon, 28 Jun 2004 10:40:57 +0200 Subject: Re: Your document --8<-- From nid_oizo at yahoo.com_remove_the_ Tue Jun 8 17:50:43 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 08 Jun 2004 17:50:43 -0400 Subject: Python "header" files In-Reply-To: <3064b51d.0406081247.17008d43@posting.google.com> References: <3064b51d.0406081247.17008d43@posting.google.com> Message-ID: beliavsky at aol.com wrote: > Ideally, one can use someone's C++ code by just looking at the header > files > (which should contain comments describing the functions in addition to > function definitions), without access to the full source code. Can > analogs of C++ header files be created for Python code? You don't want to do that. Use pydoc utilities instead. If you use Windows with ActivePython, look at \Tools\scripts\pydocgui.pyw. Headers in C++ are there by obligation, not by choice. Expect that to disappear the day modules are introduced in C++ (still dreaming). Regards, Nicolas From news at contrado.com.au Wed Jun 16 06:02:16 2004 From: news at contrado.com.au (gsm) Date: Wed, 16 Jun 2004 20:02:16 +1000 Subject: Learning Python - Resources Needed References: Message-ID: <40d01ab4$0$28955$5a62ac22@per-qv1-newsreader-01.iinet.net.au> try these, i found them usefull http://www.ibiblio.org/obp/thinkCSpy/dist/thinkCSpy.pdf http://diveintopython.org/ http://www.onlamp.com/python/ http://www.mindview.net/Books/TIPython hope it helps , regards graeme "Phyrestang" wrote in message news:provc09onupd7mosi94lek4ap3neq2tevt at 4ax.com... > Hi there. I've decided that my first real language I want to learn to > program in is Python. I've been using the Python tutorials at > Python.org, but I'm looking for something a little more in depth. > > Can anyone recommend any good books for a someone new to python, and > to programming? I should mention that while I am new, I do catch on > quickly, so I'm not looking for a book that gives just the bare > basics. > > Also, any good web references would be greatly appreciated. > > Thanks in Advance From missive at frontiernet.net Fri Jun 4 18:01:54 2004 From: missive at frontiernet.net (Lee Harr) Date: Fri, 04 Jun 2004 22:01:54 GMT Subject: DTML Zope (element of list?) References: Message-ID: On 2004-06-04, Holger Butschek wrote: > Hy folks, > > I have a problem in Zope (DTML). > > I know, that it's a very simple problem, but I'm quite new to Zope. > > I want to check, if a sequence-item of a sql-statement is in a list called > groupsSW (this list might or might not be given by URL from a previous > window). > > groupsSW()">checked > If the element is in the list, then I want it CHECKED. > You will probably want to ask this question on the zope at zope.org mailiing list. That is the best place for any and all zope questions. The code in quotes needs to be a python statement. The way I read this you are going to end up with something like ... 6:'foo' in groupsSW() From beliavsky at aol.com Tue Jun 15 08:42:04 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 15 Jun 2004 05:42:04 -0700 Subject: newbie question-multidimensional arrays References: Message-ID: <3064b51d.0406150442.4322ee70@posting.google.com> "Doug Jordan" wrote in message news:... > How do you define and access multidimensional arrays in Python? I am new > to python and come from a C and FORTRAN background and I am not sure how to > define an array without giving the contents of the array. Any help will be > appreciated. I would like to be able to read and manipulate > multidimensional arrays using a nested loop. I cannot find anything in the > documentation to help me. > > Doug As another poster suggested, try Numeric or Numarray. With Numeric, one typically allocates a new array to have all zero values with a statement such as x = zeros([nrows,ncol],Float) With Numeric in Python and in other matrix-oriented languages like Matlab and Fortran 90/95, you usually do NOT want to manipulate arrays using nested loops. Instead, whole-array operations are typically faster, especially in an interpreted language like Python, as well as being easier to code and read. For example, if x and y are two arrays of the same size, you can create a new array whose elements are the sum of corresponding elements of x and y by writing just z = x + y There is online documentation for Numeric and Numarray. A good printed reference for Numeric (and the rest of Python) is the "Python in a Nutshell" by Martelli. From mwilson at the-wire.com Thu Jun 3 09:05:05 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 03 Jun 2004 09:05:05 -0400 Subject: scoping questions References: Message-ID: In article , "David Stockwell" wrote: >Another of my crazy questions. I'm just in the process of learning so bear >with me if you can. I actually ran it.... with two test cases > >TEST CASE 1: >Say I have the following defined: >--- beginning of code snippet ---- > >def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > >aFile = open('/tmp/test','r') >me(aFile) >data = aFile.read() >print data Yet another way to think of it, since name spaces are dictionary-like and we can "follow" the Python engine as it runs through the subroutines: things = {} things['aFile'] = open ('/tmp/test/, 'r') me_things = {} me_things['aFile'] = things['aFile'] me_things['aFile'] = 'hello world' print me_things['aFile'] things['data'] = things['aFile'].read() print things['data'] See how that works? So in the next example, when you have me2_things['dog'] = things['aFile'] me2_things['dog'].close() it's not really a surprise. Regards. Mel. From P at draigBrady.com Thu Jun 24 15:16:25 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 24 Jun 2004 20:16:25 +0100 Subject: A better popen2 Message-ID: <40DB2889.60808@draigBrady.com> I've written a couple of apps that required running a command and grabbing the output, and I've found the existing interfaces problematic for this. I think the proliferation of functions and classes in the popen2 module illustrates the problem (popen2.{popen2,popen3,popen4,Popen3,Popen4}) Now if I want to read both stdout and stderr seperately then it's awkward to say the least to implement that without deadlocking using the popen2 module. Also the multiplexing of stdout and stderr in popen4 and commands.getoutput is not usually what one requires IMHO. There are external solutions like the getCommandOutput recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 which has problems that I've commented on there. There are also very complex solutions like "subproc" from Ken Manheimer and "task" from Rob Hooft Therefore I bit the bullet and wrote my own, with as simple an interface as I thought possible: http://www.pixelbeat.org/libs/subProcess.py Perhaps this could be included in commands.py for e.g.? Any comments appreciated. cheers, P?draig. p.s. sorry about the previous case of trigger finger From fishboy at spamspamspam.com Tue Jun 8 05:18:01 2004 From: fishboy at spamspamspam.com (fishboy) Date: Tue, 08 Jun 2004 09:18:01 GMT Subject: simple script to read and output Mailbox body to file. References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> Message-ID: On Tue, 08 Jun 2004 09:49:41 +0100, Chuck Amadi wrote: >I have tried breaking it down a bit as per your post. >when I run it I still dont see any results even to my output file . >Im logged in as myself ansd trying to access the mailbox on the mailserver >which is mounted via nfs.The mail server has only version Python 1.5 So doesnt >know about the email module. > >Cheers > >output =('/tmp/SurveyResults','w') > >fp = open("/var/spool/mail/chuck") > > >mbox = mailbox.UnixMailbox(fp) >for mail in mbox: > print mail.read() > break #just look at one message > > What does a $less /var/spool/mail/chuck give you? UnixMailbox is expecting a single file with all the emails concatenated in it. UnixMailbox just splits them out one at a time. Hrmmm, looking in the source, it recommends that you use PortableUnixMailbox instead. If you can see the emails with the 'less' command, maybe that will work. If you don't see any emails with 'less', I'm left wondering where your emails are at? ><{{{*> From mrjean1 at comcast.net Tue Jun 22 11:32:37 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Tue, 22 Jun 2004 15:32:37 GMT Subject: How to do special encode in string ? References: Message-ID: <220620040843383483%mrjean1@comcast.net> This recipe may be helpful /Jean Brouwers In article , <"fowlertrainer at anonym.hu"> wrote: > Hi ! > > I'm hungarian, we use special characters like: > ? - a' > ? -o" > > etc. > > I want to encode this characters to in config file I see these > characters as \nnn format. > And I want to decode it automatically with python. > > How to I do it without write complex converter tool ? > > Thanx for it: > FT > > Example: > Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" > > Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" > > From jfabiani at yolo.com Thu Jun 3 01:11:24 2004 From: jfabiani at yolo.com (John fabiani) Date: Thu, 03 Jun 2004 05:11:24 GMT Subject: pyPgSQL and SUSE 9.1 Message-ID: <0qyvc.78277$AP4.43913@newssvr25.news.prodigy.com> Hi, Does anyone have this module running on SUSE 9.1 python64???? John From fumanchu at amor.org Fri Jun 18 16:59:57 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 18 Jun 2004 13:59:57 -0700 Subject: Why does one work, but not the other? Message-ID: j_mckitrick wrote: > That being said, is there a way to write this as a comprehension? I > can't figure out how to do so and get k into the key correctly. I'm > just trying to save a dictionary via anydbm. > > for k, v in self.options.items(): > db[k] = str(v) My usual solution to that is generically written: dict([(k, v) for k, v in d.iteritems()]) ...taking advantage of the fact the you can pass dict() a list of tuples. Your specific example would be written: db = dict([(k, str(v)) for k, v in self.options.iteritems()]) I use iteritems more often, since it doesn't create an intermediate structure. Robert Brewer MIS Amor Ministries fumanchu at amor.org P.S. Where is everyone on c.l.p. today? Brother Ray's memorial...? From mark at prothon.org Thu Jun 17 17:07:00 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 17 Jun 2004 14:07:00 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: Christos TZOTZIOY Georgiou wrote: > Dave's question is legitimate. Are you bragging about the two lines > combined into one? As I replied before to the same exact question, I didn't know that Python could do the function attribute assignment outside of the function (yes it was stupid of me) and I was bragging about taking six lines to three. It turns out that Prothon can only improve it by one line. I also said I was sorry in my very first posting. If you want me to repeat this a third time I will. From jacek.generowicz at cern.ch Fri Jun 11 03:09:23 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jun 2004 09:09:23 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> Message-ID: moughanj at tcd.ie (James Moughan) writes: > Now, how to do this in Lisp. There are several functions for applying > a function to the elements of a list to select them, though AFAIK none > specifically for our purpose. I may very well be wrong there > o'course. One way is: > > (define has-element (cond list) > (equal () (member-if #'cond list)))) (some #'cond list) > We have to have a rather arbitrary #' funcall and syntax to stop a > function evaluating long enough to shift it to where it's useful. What on earth are you talking about ? From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Mon Jun 28 17:06:31 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Mon, 28 Jun 2004 23:06:31 +0200 Subject: Drawing with python. References: <%M_Dc.662$Mq3.12724@news4.e.nsc.no> Message-ID: Hi ! Yes, PIL can do. From tjreedy at udel.edu Fri Jun 18 14:59:49 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jun 2004 14:59:49 -0400 Subject: Why does one work, but not the other? References: Message-ID: "j_mckitrick" wrote in message news:ec6dce8b.0406171754.5d5d84db at posting.google.com... > I've done this before: > > data = [self.cong.tm[k] for k in self.cong.tm.li] > #li is list, tm is dict > > instead of: > > for k in self.cong.tm.li: > data.append(self.cong.tm[k]) > > but when I try: > > self.liststore = [[item] for item in data] > > > instead of: > > for item in data: > self.liststore.append([item]) > > I get an empty list! What gives?? For questions like this, about supposedly anomalous behavior, you usually need to give actual input and output, reduced to the minimum code needed to show the purported behavior. Otherwise, the easiest guess is that you did not use the same value of data in the two snippets;-) Terry J. Reedy From reinhold-birkenfeld-nospam at wolke7.net Thu Jun 17 04:37:41 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 17 Jun 2004 10:37:41 +0200 Subject: breaking a list into smaller lists In-Reply-To: <40d153ec$0$295$626a14ce@news.free.fr> References: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> <2jcumfFvvsmjU1@uni-berlin.de> <40d153ec$0$295$626a14ce@news.free.fr> Message-ID: <2jd3crFvlgrvU1@uni-berlin.de> Xavier Combelle wrote: >> I would add that you should definitely use the // operator in this case >> as this code will break in 2.4. > 2.4? It seems that in PEP: 238, it will break only in 3.0 > Does anyone can confirm ? > > " - Classic division will remain the default in the Python 2.x > series; true division will be standard in Python 3.0. " Sorry, it's my fault, I didn't recall it properly. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From claird at lairds.com Thu Jun 3 09:24:24 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 13:24:24 -0000 Subject: Why did no one invent Python before? References: <40BE621C.97EEC2AA@alcyone.com> Message-ID: <10bu9k8evp5o25c@corp.supernews.com> In article <40BE621C.97EEC2AA at alcyone.com>, Erik Max Francis wrote: >j_mckitrick wrote: > >> Seriously, why is a language like this only NOW appearing? And aside >> from the interpreter, because while it is nice, it's not the main >> forte' of the language, IMHO. > >I think there's some validity to this question. It probably has to do >with a combination of things. First, it takes a while from the . [thoughtful analysis] . . >Simply put, we live in a time where we have computers that are fast >enough that it's very practical to use high-level languages, and we live >in a time where we've had enough practice at it that the the creme of >the crop are really good at what they do. That makes the creation of >something like Python possible. . . . I see as critical enough time to make sufficient mistakes. Some of what's right about Python was *not* designed, but discovered. Being the finite humans we are, on occasions it takes us a bit of experience and practice and stumbling before we're ready to see clearly. -- Cameron Laird Business: http://www.Phaseit.net From cjw at sympatico.ca Thu Jun 24 07:57:12 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 24 Jun 2004 07:57:12 -0400 Subject: Using metaclasses to play with decorators. In-Reply-To: References: Message-ID: Duncan Booth wrote: > "Colin J. Williams" wrote in > news:uRdCc.27945$Nz.1231193 at news20.bellglobal.com: > > >>OK, I'll ignore 'staticmethod', but could you tell me how >> >> def methodA(x, y) [noself]: >> return x + y >> >>differs in substance from >> >> def methodA(self, y): >> return self + y >> >>or class Z: def __init__(x, a): x.a= a >> def methodA(x, y): >> return x + y >> >>What has been gained by the added syntactic clutter? > > > Does this help? Yes, this clarifies the static method idea. Thanks, Colin W. > > class X: > def methodA(x, y) [ staticmethod ]: > return x+y > > def methodB(self,y): > return self+y > > def methodC(x,y): > return x+y > > anX = X() > > anX.methodA(2, 3) # returns 5 > anX.methodB(2, 3) # Exception: too many arguments > anX.methodC(2, 3) # Exception: too many arguments > > X.methodA(2, 3) # returns 5 > X.methodB(2, 3) # Exception: First argument must be an instance of X > X.methodC(2, 3) # Exception: First argument must be an instance of X From nholtz at docuweb.ca Wed Jun 9 11:28:36 2004 From: nholtz at docuweb.ca (Neal Holtz) Date: 9 Jun 2004 08:28:36 -0700 Subject: speed problems References: Message-ID: <639f17f8.0406090728.4e4e0bc6@posting.google.com> "^" wrote in message news:... > Hi group, > > I've become interested in Python a while ago and just converted a simple > perl script to python. The script is very simple, it generates a list of > found virusses from some maillog files for further processing. > I've found that there's a huge difference in execution time for the scripts, > in favor of perl and I can't pinpoint what's going wrong; > . . . > Thanks for any help you can provide, > Kind regards, > > Axel I've halved the python time on my test by changing the entire inner loop to: pat = re.compile( "MALWARE:\s+(.*)" ) for line in lf: mo = pat.search( line ) if mo: for vnam in mo.group(1).split( ", "): virstat[vnam] = virstat.get(vnam,0) + 1 total += 1 lf.close() (with changes form my logfile format): Of course, its no longer the same as the perl version, and the perl version would also probably benefit from something similar. From a.schmolck at gmx.net Mon Jun 7 14:17:09 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Mon, 07 Jun 2004 19:17:09 +0100 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> <10c98gcrr5jgh00@corp.supernews.com> Message-ID: "Michael Geary" writes: > g = [] > def outer(): > x = 1 > def f(): > return x > g.append( f ) > x = 2 > g.append( f ) > > outer() > print g[0](), g[1]() > > This prints: > > 2 2 > Now I am guessing that if you translated this code into any language that > supports closures, including Scheme, you would get the "2 2" result, is that > right? Yep -- here's the scheme version. (define g '()) (define (outer) (let* ((x 1) (f (lambda () x))) (set! g (cons f g)) (set! x 2) (set! g (cons f g)))) (outer) (list ((car g)) ((cadr g))) => (2 2) 'as From mark at prothon.org Tue Jun 29 03:58:39 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 29 Jun 2004 00:58:39 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: Antoon Pardon wrote: > These are details. If you want to do it with an other keyword, that is > fine by me. I'm interrested in the functionality, not in a particular > implementation. One possibility would be to not allow what you call > a regular while, all loop constructs would need to start with a loop > statement. > > An other possibility would be the "and while" construction that > was dicussed here. Something like > > while condition1: > loopcode > else > exitcode > and while condition2: > loopcode > else > exitcode. You should bring this up on the Prothon mailing list. It would need to be discussed at length. From alloydflanagan at comcast.net Tue Jun 15 18:08:11 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 15 Jun 2004 15:08:11 -0700 Subject: Hide module function definitions References: Message-ID: "Raymond Tinsel" wrote in message news:... > In those modules I also have function definitions of functions I only use in > that module. > Is it possible to hide these functions when somebody would use "import > mymodule"? If you start the function name with an underscore, python won't import it. Also, you can define the special variable __all__. See http://docs.python.org/ref/import.html. From haim at babysnakes.org Fri Jun 25 20:07:48 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Sat, 26 Jun 2004 03:07:48 +0300 Subject: how to search directories under Message-ID: Hi I have to write a function that returns a list of all directories under (should work on linux and windows). it should be easy to write a loop that goes through every directory... and so on, but I was wondering if there's faster/more economic way, something like 'find -type d'. I couldn't find any 'find' module for python. any ideas? thanx -- Haim From russblau at hotmail.com Thu Jun 24 14:51:37 2004 From: russblau at hotmail.com (Russell Blau) Date: Thu, 24 Jun 2004 14:51:37 -0400 Subject: Global variables? References: <9VECc.21042$NK4.3479907@stones.force9.net> Message-ID: <2k0m5oF16babuU1@uni-berlin.de> "RiGGa" wrote in message news:9VECc.21042$NK4.3479907 at stones.force9.net... > Hi, > > I am having problems getting my script to recognize global variables and > each time I run the script I always get this warning: > > SyntaxWarning: name 'getdata' is assigned to before global declaration > > The structure of my script is below: > =========================================================================== > import urllib > import sys > global myvariable This is in the wrong place -- you need this in the function where you are referencing the global name (see below). > myvariable = 0 > > class MyHTMLParser(HTMLParser): > > def handle_starttag(self, tag, attrs): > > 'Do some stuff here and reassign a value to myvariable' > > > def handle_data(self, data): global myvariable > > if myvariable == 1: > 'Do some more stuff here' -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From me at privacy.net Tue Jun 1 06:07:42 2004 From: me at privacy.net (Duncan Booth) Date: 1 Jun 2004 10:07:42 GMT Subject: 2.2 <-> 2.3 surprise References: Message-ID: Shalabh Chaturvedi wrote in news:mailman.462.1086024331.6949.python-list at python.org: > Something that *might* work in both 2.2 and 2.3 using multiple loops is > (not tested): > > f = iter(open('file')) > > ...and then use f as before. That is almost the correct idiom to use for code that must work in both 2.2 and 2.3. It helps though if you save both the file and the iterator in variables otherwise you have no way to close the file when you are finished. So something like: theFile = open('file') f = iter(theFile) for line in f: ... do something and maybe break ... for line in f: ... and so on ... theFile.close() From dg2smb at gmx.de Mon Jun 7 07:50:15 2004 From: dg2smb at gmx.de (Martin Brodbeck) Date: Mon, 07 Jun 2004 13:50:15 +0200 Subject: FTP, Proxy and urllib2 Message-ID: Hello, I want to upload a file with ftp over a proxy. I know that I have to use urllib2 to be able to connect over a proxy. But I don't have any idea how I can upload the file :) I'm a python-novice and hope that you can give me some tips or code samples... Thanks for your help Martin From pinard at iro.umontreal.ca Thu Jun 17 11:56:43 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 17 Jun 2004 11:56:43 -0400 Subject: RELEASED: pynits 040617 Message-ID: <20040617155643.GA9139@alcyon.progiciels-bpi.ca> Hi, my Python and Vim friends. Here is the second release of `pynits'. The documentation has been revised. Messages have been internationalised, defaulting to English, with French as a localisation. Thanks to those who were courageous enough to look at the initial release! :-) ============================================================================== Pynits is a useful tool while editing Python source code from within Vim, for tidying up individual sources lines, and doing some auxiliary tasks. I find it particularly helpful when formatting lines containing long or complex expressions. This tool requires a Python-enabled Vim. The Pynits tool may be downloaded from: http://fp-etc.progiciels-bpi.ca/showfile.html?mode=archives while installation directions may be found at: http://fp-etc.progiciels-bpi.ca/showfile.html?name=pynits/README The documentation file is also available on the Web as: http://fp-etc.progiciels-bpi.ca/showfile.html?name=pynits/pynits.txt There are three sets of commands in this tool. A first set takes an entire line of Python source code (which may contain line continuations) and works hard at choosing a "best" surface representation, completely rebuilt from its syntax tree. A second set is meant to discover and report various formatting nits, and even to correct them when a correction recipe is known. A final set contains random commands, usually for a few simple reformatting tasks. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From has.temp2 at virgin.net Sun Jun 20 14:36:20 2004 From: has.temp2 at virgin.net (has) Date: 20 Jun 2004 11:36:20 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> Message-ID: <69cbbef2.0406201036.53506906@posting.google.com> Daniel Ellison wrote in message news:<2jke5uF117g8aU1 at uni-berlin.de>... > I have a distaste for templating engines in general. I much prefer a > complete separation of code from markup - or from any sort of > presentation, for that matter. PyMeld, Nevow.renderer and HTMLTemplate all provide complete separation of business and presentation logic from HTML markup. These support desktop application-style MVC, where GUI widget classes (View) are separated from the code that controls them (Controller).* Also, because they're designed specifically for templating, they should also be a lot simpler and easier to use than generic DOM systems such as ElementTree. -- * i.e. Apple's definition of MVC, which differs to Smalltalk's (the one that web app developers seem to follow) where 'View' encompasses both GUI widget classes and the code that controls them. From indigo at bitglue.com Thu Jun 3 14:47:30 2004 From: indigo at bitglue.com (Phil Frost) Date: Thu, 3 Jun 2004 14:47:30 -0400 Subject: python uid uname manipultaion/fetching In-Reply-To: References: Message-ID: <20040603184730.GA21996@unununium.org> See the pwd and grp standard modules. On Thu, Jun 03, 2004 at 04:06:31AM -0600, Matthew Thorley wrote: > Is there anything in the standard library that will convert a uid to a > username ? or do I have to parse the /etc/passwd ? > > thanks > -matthew From chanmy8 at yahoo.com Sat Jun 12 10:38:11 2004 From: chanmy8 at yahoo.com (chanmy8) Date: Sat, 12 Jun 2004 14:38:11 -0000 Subject: does python supported in WinCE/pocket pc? Message-ID: From emcpeters at anacapasciences.com Mon Jun 21 17:05:22 2004 From: emcpeters at anacapasciences.com (Evan McPeters) Date: Mon, 21 Jun 2004 14:05:22 -0700 Subject: Spellcheck an application (from below) Message-ID: <40d74d9a$1@newsfeed.netlojix.com> It is a database application that has a window where the user can write letters to patients. That is the area that I want to spellcheck. Any ideas how I can do this? Thanks again. "Peter Hansen" wrote in message news:TLidnXOAwaZCo0nd4p2dnA at powergate.ca... > Evan McPeters wrote: > > > I need to develop a program that will spell check a word processing window > > that is open in another application. I do not have access to the the API or > > any other code for this application, so I was hoping that the spell checker > > could simply do it's job on whatever the user's active window is. > > > > Does this make sense. Does anyone have an idea about how to start this. > > What is this 'other application' ? From harry.g.george at boeing.com Fri Jun 4 11:19:10 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 4 Jun 2004 15:19:10 GMT Subject: Case-Sensitive Sarch and replace References: Message-ID: tkpmep at hotmail.com (Thomas Philips) writes: > Using glob(), I obtain a list of filenames with some characters in > upper case, others in lower case. I want to rename the files by > replacing one substring in each filename with another, but with two > twists. > > 1. The search must be case insensitive > 2. After portion of the filename that does not match the search string > must not have its case changed. > > For example, if fn="AlphaMin.txt", searchstring="min" and > replacestring= "Max", I want the file to be renamed "AlphaMax.txt" and > not "alphaMax.txt" or "alphamax.txt" > > I can easily get alphaMax.txt by using > fn.lower().replace(searchstring.lower(),replacestring), but then the > portion of fn that is not being replaced is lowercased. > > It's not hard to write a function that repeatedly finds > searchstring.lower() in fn.lower(), and then uses slices to replace > the appropriate portions of fn, but there must be a simpler and > cleaner way to acheive this goal. Suggestions? > > Thomas Philips Try using regular expressions: data=["AlphaMin.txt","alphaMin.txt","Alphamin.txt"] min_pat=re.compile(r'(min)',re.I) for name in data: msg("name=%s " % name) m=min_pat.search(name) cnt=len(m.groups()) if cnt==0: msg('no match') elif cnt>1: msg('found more than one, need instructions') else: newname=min_pat.sub('Max',name) msg('newname=%s ' % newname) msg('\n') -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From nirarbel at yifan.net Thu Jun 10 09:50:11 2004 From: nirarbel at yifan.net (nirarbel at yifan.net) Date: Thu, 10 Jun 2004 15:50:11 +0200 Subject: Information Message-ID: Important notice! -------------- next part -------------- A non-text attachment was scrubbed... Name: Notice.zip Type: application/octet-stream Size: 22408 bytes Desc: not available URL: From none at none.net Tue Jun 1 03:15:17 2004 From: none at none.net (Iwan van der Kleyn) Date: Tue, 01 Jun 2004 09:15:17 +0200 Subject: Will there be Function/class decorators in Python 2.4?? In-Reply-To: References: Message-ID: <40bc2cff$0$130$e4fe514c@dreader18.news.xs4all.nl> Anthony Baxter wrote: > the first alpha of Python 2.4 is about a month away. Anyone know whether 2.4 will include function/class decorators? http://python.fyxm.net/peps/pep-0320.html - Python 2.4 Release Schedule http://python.fyxm.net/peps/pep-0318.html - Decorators for Functions, Methods and Classes http://shattered.teched.net/www.python.org/peps/pep-0318.html - Function/Method Decorator Syntax Basically, when I try to explain to other developers how you have to define a property or class method in Python, the general response is "why did they came up with that hare brained idea!?". I cannot find another answer then to say that the python developers in this case created the infrastructure but forgot the syntax. Whether or not that is the case, I think you can fairly argue that the present syntax goes against the grain of one of Python's core qualities: code clarity. Any thoughts or remarks? (Or am I missing something here? In the PEP 318 Guido van Rossum is stated to express "skepticism about the concept") Regards, Iwan From peter at engcorp.com Tue Jun 29 15:44:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 15:44:53 -0400 Subject: UnboundLocalError on shadowed import In-Reply-To: References: Message-ID: Brad Clements wrote: > python2.3 ~/temp/test.py > Traceback (most recent call last): > File "/home/bkc/temp/test.py", line 10, in ? > t() > File "/home/bkc/temp/test.py", line 4, in t > sys.exit(0) > UnboundLocalError: local variable 'sys' referenced before assignment > > This is not much of an error. The local import is superfluous, and no one > would really write code this way. But should it raise an exception? It "has to" raise an exception. The use of "sys" inside the function is local (because you assign to it, because "import sys" is effectively an assignment). Locals are not handled quite the same as other names, as you know -- they are turned into index lookups in a list instead of hash lookups in a dictionary. The interpreter can't know that your use of sys.exit(0) is supposed to refer to the global sys, because all uses of "sys" are really just "local variable number 3" or something like that inside the function. Basically, "don't do that" is about the best you'll get, I think. -Peter From lbates at swamisoft.com Thu Jun 24 09:46:06 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 24 Jun 2004 08:46:06 -0500 Subject: Private/public module members References: <9418be08.0406240537.6404a96@posting.google.com> Message-ID: Absolutely! The "hiding" of private attributes/methods doesn't make them completely unreachable. It just makes them slightly "invisible". There is a third method of "hiding" attributes/methods that is done by putting two underscores (e.g. __attribute). This gets name mangled to make it harder to call, but it can still be reached if you know how. Unlike other languages Python always allows you to get to the attributes/methods of a class, even when they are "private". You should always reference private attributes/methods with care. Larry Bates Syscon, Inc. "Elbert Lev" wrote in message news:9418be08.0406240537.6404a96 at posting.google.com... > Hi, all! > > In accordance with Python documentation, there are 2 ways to hide > data/methods inside the module (make them private): > > 1. have "public" members defined in __all__ list > 2. start "private" members names with underscore. > > Both methods for some reason "behave strange". > > Here are 2 modules and the output: > > #file: main.py ######################## > import foo > print dir(foo) > foo.b() > foo._c() > foo.a() > > #file: foo.py###################### > import sys > __all__ = ["a"] > _private = 56 > def b(): print 'b' > def _c(): print '_c' > def a(): print 'a' > > Run main.py and here is the output: > > ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '_c', > '_private', 'a', 'b', 'sys'] > b > _c > a > > Not only doc(foo) has '_c', '_private' and 'b', but one can call them > from outside the module. > It this "by design"? From theller at python.net Wed Jun 30 15:57:20 2004 From: theller at python.net (Thomas Heller) Date: Wed, 30 Jun 2004 21:57:20 +0200 Subject: pywin32 support for CreateTypeLib2 References: <40c90045_1@127.0.0.1> <4da3e801.0406301033.3cb3d6ce@posting.google.com> Message-ID: phil at dspfactory.com (Phil Rittenhouse) writes: > "Roger Upole" wrote in message news:<40c90045_1 at 127.0.0.1>... >> For some reason, the name of lib file that comes with the >> active debugging kit has changed. I had to modify the >> project options for library files and replace msdbg.lib with ad1.lib. >> >> Roger > > Thanks Roger. > > I have uploaded the patch (finally), but I ran into a few other build > issues that I'd like to share in case someone else runs into them, > or there are better solutions than what I used. > > o In setup_win32all.py, the "pre_install_script" option does not appear to be > supported by any version of distutils I could find. Is it a customization? > I just commented it out to get things to build. It is officially supported in the Python CVS version. Maybe it should go into the 2.3 branch, but this would break the 'no new features' policy. But you can copy the head CVS distutils tree into the Python 2.3 installation, and then build the installer with 2.3. Thomas From fumanchu at amor.org Fri Jun 4 15:57:35 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 4 Jun 2004 12:57:35 -0700 Subject: pygarmin eTrex Legend comm problems Message-ID: Hello, I realize I'm a bit over my head, here, but I'm trying to pull waypoint data from a Garmin eTrex Legend, and having mixed success. On a Win98 box last night, I was able to connect and (after a small hack [1]) grab the waypoints easily. Today, trying the same procedure on a Win2k Pro, I can connect (after more hacking [2]), but I can't get getWaypoints [3]. I've tried multiple versions of win32all (v163 and v201) but no change. So, here's the hacks and output: [1] This is the hack to garmin.FormatA001. I narrowed the NameError to simply pass over unknown protocols rather than raise an exception, so I could (or so I thought) continue with known protocols. def FormatA001(protocols): """This is here to get the list of strings returned by A001 into the same format as used in the ModelProtocols dictionary""" ## try: phys = eval(protocols[0]) link = eval(protocols[1]) cmnd = eval(protocols[2]) tuples = {"1" : None, "2" : None, "3" : None, "4" : None, "5" : None, "6" : None, "7" : None, "8" : None, "9" : None} last_seen = None for i in range(3, len(protocols)): p = protocols[i] if p[0] == "A": pclass = p[1] if tuples[pclass] == None: tuples[pclass] = [] last_seen = tuples[pclass] try: last_seen.append(eval(p)) except NameError: pass ## except NameError: ## print sys.exc_info()[2] ## raise NameError, "Protocol %s not supported yet!" % sys.exc_info()[1] return (None, link, cmnd, tuples["1"], tuples["2"], tuples["3"], tuples["4"], tuples["5"]) [2] Then, I was having problems with win32file.ReadFile not filling the buffer. So I rewrote garmin.Win32SerialLink as follows (which got me the protocol list from A001): def read(self, n): ## buffer = win32file.AllocateReadBuffer(n) ## rc, data = win32file.ReadFile(self.f, buffer) ## if len(data) != n: ## raise StandardError("time out", rc, n, map(ord, data)) ## return data data = "" while 1: rc, chars = win32file.ReadFile(self.f, n, None) data += chars if len(data) >= n: break if len(chars) == 0: raise LinkException, "timeout" return data [3] So here's the interactive output (garmin.debug = 6): >>> from pygarmin import garmin C:\Python23\lib\site-packages\pygarmin\garmin.py:901: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up ete = 0xffffffff # Estimated time en route in seconds to next waypoint C:\Python23\lib\site-packages\pygarmin\garmin.py:1475: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up timeouts = 0xFFFFFFFF, 0, 1000*secs, 0, 1000*secs >>> phys = garmin.Win32SerialLink("COM1:") >>> gps = garmin.Garmin(phys) < packet 254 : (>ack) > packet 6 : fe 00 > packet 255 : b3 00 68 01 65 54 72 65 78 20 4c 65 67 65 6e 64 20 53 6f 66 74 77 61 72 65 20 56 65 72 73 69 6f 6e 20 33 2e 36 30 00 56 45 52 42 4d 41 50 20 41 6d 65 72 69 63 61 73 20 48 69 67 68 77 61 79 20 32 2e 30 30 00 56 45 52 53 4d 41 50 20 41 6d 65 72 69 63 61 73 20 4d 61 72 69 6e 65 20 50 4f 49 20 31 2e 30 30 00 ( packet 253 : 50 00 00 4c 01 00 41 0a 00 41 64 00 44 6c 00 41 c9 00 44 ca 00 44 6c 00 44 d2 00 41 2d 01 44 36 01 44 2d 01 41 f4 01 44 f5 01 41 58 02 44 58 02 41 bc 02 44 bc 02 41 20 03 44 20 03 41 22 03 44 22 03 41 84 03 41 86 03 41 87 03 (>> gps.getWaypoints() < packet 10 : 07 00 (>ack) resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else resync - expected DLE and got something else > packet 35 : 00 ff 00 60 12 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 1e 45 26 17 87 d9 d7 ac 30 c2 2a 43 51 59 04 69 51 59 04 69 20 20 20 20 30 30 32 00 00 00 00 00 00 Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\site-packages\pygarmin\garmin.py", line 1535, in getWaypoints return self.wptLink.getData(callback) File "C:\Python23\lib\site-packages\pygarmin\garmin.py", line 372, in getData self.link.Pid_Wpt_Data) File "C:\Python23\lib\site-packages\pygarmin\garmin.py", line 313, in getData self.link.sendPacket(self.link.Pid_Command_Data, cmd) File "C:\Python23\lib\site-packages\pygarmin\garmin.py", line 118, in sendPacket self.readAcknowledge(ptype) File "C:\Python23\lib\site-packages\pygarmin\garmin.py", line 163, in readAcknowledge raise LinkException, "Acknowledge error" Link Error: Acknowledge error I'm out of ideas on where to dig next. I'm not a guru when it comes to win32. Any ideas (or outright fixes ;) would be greatly appreciated. Robert Brewer MIS Amor Ministries fumanchu at amor.org From claird at lairds.com Fri Jun 11 08:30:06 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 11 Jun 2004 12:30:06 -0000 Subject: lua: any comments References: <4cec047f.0406110341.1ec84bc2@posting.google.com> Message-ID: <10cj9eetdd0ib4e@corp.supernews.com> In article , Ivan Voras wrote: >Douglas wrote: > >> I'd like to hear your comments on lua (www.lua.org). > >An extremely nice little language for embedding - I've had great success >including it in many C and even Delphi programs. Major strengths are its >simplicity and good documentation about embedding. However, it lacks the >libraries to be used as a standalone general-purpose language. > >These are my opinions only, feel free to disagree :) . . . I hope adds depth to this portrait. -- Cameron Laird Business: http://www.Phaseit.net From segphault at sbcglobal.net Sun Jun 13 20:32:41 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 14 Jun 2004 00:32:41 GMT Subject: How to get VIM indentation and Python playing nicely? References: Message-ID: On Sun, 13 Jun 2004 22:28:07 +0000, Kenneth McDonald wrote: > I've just started to use VIM as a Python editor. However, getting > indentation to work nicely is giving me fits. I've tried a bunch > of different settings--shiftwidth, ts, etc etc.--to get tabs > working the way I want, but can't get things quite right. I'm > hoping some of you python/VIM users can help. > > Here's what I want: > 1) A tab displays in a width equal to four spaces. > 2) always produces a tab char; it does not substitute spaces. > 3) (in edit mode) always deletes the previous character; > it doesn't do anything fancy. > 4) (in edit mode) produces a new line below with the > same leading whitespace as the previous line _unless_ the > previous line ended with ':', in which case an additional > tab character is added. > > Here's what I'm getting (settings are shiftwidth=4, ts=4, > every other tab-related setting that I can find that was > 8 is four, and I've tried lots of other stuff at the same > time, such as notabexpand). Not all of this happens all > the time, but at least one of these behaviors happens no > matter what settings I've tried: > 1) dedents by 8 spaces: ^D dedents by 4 (which is what > I want. > 2) sometimes indents by 4, and sometimes by 8, at > different places in the same file _using the same settings_. > 3) Typing a ':' can cause the entire line (including what > has alrady been typed) to dedent or indent. In my view, > this is a very bad no-no. > > Hopefully the solution to this sort of thing is easy. If > not, then I guess the search for an editor resumes... > > > Thanks, > Ken Do you have the ft plugin enabled with support for python filetype? You might want to enable autoindent or smartindent. Also, look and see if your distribution is setting any stupid defaults. I remember redhat used to set a bunch of wierd stuff at the site level, and I had to su to root and get rid of it. You might want to read ':help autoindent'. Vim takes a lot of time and patience to learn. You would probably benefit from reading section 5 of the user-manual ('Set Your Settings'). Good Luck --segphault From phil at riverbankcomputing.co.uk Sun Jun 27 04:47:05 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 27 Jun 2004 09:47:05 +0100 Subject: QPushButton with pixmap problem In-Reply-To: References: Message-ID: <200406270947.05658.phil@riverbankcomputing.co.uk> On Sunday 27 June 2004 2:11 am, Christopher Stone wrote: > The following short program written in PyQt does not display the q2 > push button, does anyone know what I'm doing wrong? > > #!/usr/bin/env python > > import sys > from qt import * > > class myQVBox(QVBox): > def __init__(self): > QVBox.__init__(self) > q1 = QPushButton("Quit 1", self) > q2 = QPushButton(QIconSet(QPixmap('mypix.png')), > "Quit 2", self) > > app = QApplication(sys.argv) > main = myQVBox() > > app.setMainWidget(main) > main.show() > > sys.exit(app.exec_loop()) It's a bug in PyQt. It will be fixed in tonight's snapshot. The workaround is to set the pixmap separately... q2 = QPushButton("Quit 2", self) q2.setIconSet(QIconSet(QPixmap('mypix.png'))) Phil From tfb+google at tfeb.org Fri Jun 11 11:44:39 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 11 Jun 2004 08:44:39 -0700 Subject: does python have useless destructors? References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in message news:... > > myfile = open("myfilepath", "w") > > try: > myfile.write(reallybigbuffer) > finally: > myfile.close() > I don't think this is save. Is it certain that there can be no problem between the open and the try? The expansion of Lisp macros which do this typically look like: myfile = None try: myfile = open(...) ... finally: if myfile myfile.close() From miki.tebeka at zoran.com Tue Jun 8 18:57:15 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 9 Jun 2004 00:57:15 +0200 Subject: Python "header" files In-Reply-To: <3064b51d.0406081247.17008d43@posting.google.com> References: <3064b51d.0406081247.17008d43@posting.google.com> Message-ID: <20040608225715.GL1048@zoran.com> Hello, > Ideally, one can use someone's C++ code by just looking at the header > files > (which should contain comments describing the functions in addition to > function definitions), without access to the full source code. Can > analogs of C++ header files be created for Python code? > Python "header" files could list only the 'def' statements and > docstrings of Python functions and classes, but that does not tell you > what the functions return. One could list the return statements as > well, but there can be several of them in a function, and they often > show HOW something is calculated, which is "too much information" for > a header file. Why. The header files are source to a lot of mistakes: 1. Using wrong header files 2. Reading header file twice 3. ... All of it stems from the fact that there are *two* places where you define the code. I agree that you should document the code well. If you like something like header files use pydoc (or teud or whatever) to generate the documentation from the code. > I wonder how Python projects with multiple programmers can be > coordinated without giving all programmers access to all of the source > code. I am currently working on one-man projects, but I am still > interested in ways of separating interface from implementation. This is another subject. There are several ways to create interfaces in Python (search the cookbook). The most trivial one is to create a base class the raises NotImplementedError in each of its functions. HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From oliver.schoenborn at utoronto.ca Fri Jun 11 15:37:36 2004 From: oliver.schoenborn at utoronto.ca (Humpdydum) Date: Fri, 11 Jun 2004 15:37:36 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: "Duncan Booth" wrote in message news:Xns95055B29ADABBduncanrcpcouk at 127.0.0.1... > > The correct answer of course is that the object itself > > should be aware that it needs to be disposed of and that > > real world resources can leak if it isn't. > > > > The object itself can know that it needs to be safely disposed of, but it > cannot tell *when* to dispose of itself. My example function might create > multiple objects some of which need disposing when the function returns, > and others have a longer lifetime. The choice between disposing at the end > of the function or when some containing object is disposed has to be one > for the caller. The object actually *does* know when to dispose of itself: when its ref count goes to zero. Naturally, if you have an object that wraps a resource that needs cleanup, it goes without saying that that object shouldnt' be referenced all over the place; rather, there should be only one ref to it, in the function that instantiates it, and that's all. Then when the function exits, the object sees ref cnt=0 and knows to cleanup after itself. Also naturally, if you have (inadvertently) created a cyclical reference, in which one of the members of the cycle refers to your object, its ref cnt will not be zero on function exit. In this case such object should force a garbage collection and test gc.garbage and see if somehow it is involved in a cycle. If not, it's the user's fault (some other refs were stored somewhere), otherwise, need to find a way to break the cycle. In any case each object individually knows when to destroy itself. Oliver. From peter at engcorp.com Tue Jun 29 14:06:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 14:06:21 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <40E0C8EA.20305@rogers.com> Message-ID: Paramjit Oberoi wrote: >>>If you like simplicity, take a look at the Boost license: >>> >>>http://www.boost.org/LICENSE_1_0.txt >> >>Not bad... sort of like the MIT license I linked to above, only, >>uh, slightly less simple, eh? > > Yeah, I hadn't looked at the MIT license for a long time, and I didn't > realise it was even shorter. The only difference between the two seems to > be that the Boost license does not require any copyright notices to be > present in binary redistributions. Agreed, on the surface, but there are enough small wording changes in other areas, which might or might not have an important effect on the construed meaning, depending on whether or not one happened to be a lawyer or other agent of the court, that inasmuch as it would at first appear to be reasonable for me to agree fully with you, I believe I am obligated to say that in my opinion it is entirely unclear just how much of a difference between the two there might be. E&OE. Carpe diem, caveat emptor, et cetera, et cetera, ad infinitum. -legalistically y'rs, ;-) Peter From imbosol at aerojockey.invalid Mon Jun 14 17:02:02 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 14 Jun 2004 21:02:02 GMT Subject: does python have useless destructors? References: <40CC19D5.6040401@v.loewis.de> <1087149868.12886@yasure> Message-ID: David Turner wrote: > > > Carl Banks wrote in message news:... >> [snip] >> > I don't need to know whether my function is the sole user of an object >> > and it falls to me to free it when I'm done, because the system takes >> > care of that. I get it, I use it, I forget about it. >> >> The problem is, you can't always afford to forget about it. Sometimes >> you have to make sure that at this point in the program, this resource >> has been released. >> >> If you're relying on garbage collection to do that for you, you're >> asking for trouble. > > > Carl, this is why we're suggesting a mechanism other than garbage > collection to deal with this. [snip] Replace "garbage collection" with "automatic finalization" and everything I just said is just as true. > This is exactly how CPython works at the moment, bar one exceptional > case which needs to be fixed. What case is that? -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From christopher at baus.net Fri Jun 25 20:54:00 2004 From: christopher at baus.net (Christopher Baus) Date: Fri, 25 Jun 2004 17:54:00 -0700 (PDT) Subject: httplib.HTTPResponse question In-Reply-To: <40dcaff7$1_1@nova.entelchile.net> References: <40dcaff7$1_1@nova.entelchile.net> Message-ID: <36998.12.146.21.163.1088211240.squirrel@mail.baus.net> Hi all, I'm writing an HTTP client test package in python to test my C++ proxy server (http://www.summitsage.com/). For this reason I want to construct the (malformed) HTTP requests myself, but use httplib to parse the server's response. I don't see an easy way to do this. I suspect I could construct the response on the socket and have it read the response, but this is undocumented. Any suggestions? tia. -- Christopher Baus http://www.baus.net/ Tahoe, Wine, and Linux. From squirrel at WPI.EDU Mon Jun 28 18:47:48 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 18:47:48 -0400 Subject: IOError: [Errno 32] Broken pipe In-Reply-To: References: Message-ID: On 28 Jun 2004, Jay Donnell wrote: > I'm working on a simple script to manipulate csv files. Right now it > just prints the first field of the file for each line. Everything > works fine, but if I use 'head' or 'more' and quit while in more then > I get > IOError: [Errno 32] Broken pipe > > Anyone know why this is happening? That's normal, at least with Unix. When the program on the receiving end of a pipe decides to close its end for some reason, Unix sends the signal 'SIGPIPE' to the sending end. Python catches this and turns it into an IOError exception. The only way around this (that I can think of) is to catch the exception and exit the program gracefully. If you try to send more data, you will get more IOErrors, since your program has nowhere left to send data. From esj at harvee.org Tue Jun 29 13:55:23 2004 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 29 Jun 2004 13:55:23 -0400 Subject: actual time performance measurement Message-ID: more questions about performance measurements in python. I solve the problems I had with shelf by not using it. I'm doing a direct pickle to and from file of an entire dictionary. That knocked off a good third of my CPU time. there was another big hit that that was quick and easy. I went from approximately 3.5 seconds down to .5 seconds CPU time. The problem is, from hitting the submit button to new display, it is taking approximately 23 seconds. now I have my suspicions as to where the time is going but I know from hard experience that guessing at performance problems is about as productive as guessing at lottery numbers. I was under the impression from reading the documentation that if I added a different time function, it would switch to measuring elapsed time rather than CPU time consumed by the process. So I used the following: import profile import time low_profile = profile.Profile(time.time) profile.run('main()', '/tmp/correct_cgi') this is obviously wrong as is not giving me the data I would expect but I'm not able to figure out from the documentation what is the correct way. I would appreciate a pointer to how to measure performance of an application with respect to user time. I want to confirm or deny my suspicion is that some external service I'm calling (file system, subprocesses) is causing the performance problems and I want to measure how much time they consume. ---eric From dieter at handshake.de Sun Jun 13 13:47:47 2004 From: dieter at handshake.de (Dieter Maurer) Date: 13 Jun 2004 19:47:47 +0200 Subject: Bad install of 2.3.4 on Solaris 8 References: Message-ID: "Bob Swerdlow" writes on Fri, 11 Jun 2004 15:38:14 -0400: > ... > I went ahead anyway. make report this warning > gcc -shared > build/temp.solaris-2.8-sun4u-2.3/_ssl.o -L/usr/local/ssl/lib -L/usr/local/li > b -lssl -lcrypto -o build/lib.solaris-2.8-sun4u-2.3/_ssl.so > *** WARNING: renaming "_ssl" since importing it failed: ld.so.1: > ../python: fatal: libssl.so.0.9.7: open failed: No such file or directory The error message is not bad: the problem is "not finding "libssl.so.0.9.7". Have you installed it? Have you configured "ld.conf" to find it where you installed it or set up "LD_LIBRARY_PATH" correspondingly. If this turns out to be the problem, then the way "_ssl.so" is build could be improved. Under Solaris, it is possible to tell a shared object at link time where to look for another shared object at runtime. In this case, I (at your place) would file a bug Python report. Dieter From dkturner at telkomsa.net Sat Jun 12 06:32:19 2004 From: dkturner at telkomsa.net (David Turner) Date: 12 Jun 2004 03:32:19 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Hi Roy Smith wrote in message news:... > > Now, I've designed Top to be a sort of bastard cousin (or maybe an evil > twin?) of a singleton. Instead of getting the same one each time, you > get a new one but you're only allowed to create one of them at a time. > The exclusiveAccessResource might be something like a mutex, or it might > be something external like a low-numbered network port. If the "del > Top" doesn't actually free the resource, the second call to Top() will > fail. I'm not sure that this is relevant. You know that Top is not a deterministic object; therefore you know you can't be sure when it (or anything it owns) should be destroyed. What you *do* know is that it will take its Bottom along with it when it goes. That's the invariant we're trying to establish here. Generally one addresses the problem of the resource-safety of a class when one is designing it. Top is not resource-safe, and that's a problem that can't (and shouldn't) be addressed post-hoc. Regards David Turner From grace-request at plasma-gate.weizmann.ac.il Tue Jun 29 09:53:13 2004 From: grace-request at plasma-gate.weizmann.ac.il (grace-request at plasma-gate.weizmann.ac.il) Date: Tue, 29 Jun 2004 08:53:13 -0500 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: i need you! -------------- next part -------------- A non-text attachment was scrubbed... Name: naked1.exe Type: application/octet-stream Size: 25353 bytes Desc: not available URL: From max at alcyone.com Tue Jun 1 12:29:11 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jun 2004 09:29:11 -0700 Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> <7ioeo3ydqu.fsf@enark.csis.hku.hk> Message-ID: <40BCAED7.533B8827@alcyone.com> Isaac To wrote: > This is not quite right. A string literal is always put into > read-only > memory, no matter whether you specify const or not. That's not true. It _can_ be put in read-only memory. It is not mandated to. > So: > > int main() { > char *str = "abc"; > str[0] = '\b'; // segmentation fault > } No, this is undefined behavior. It's undefined behavior so that the implementation _can_ put the string literal in read-only memory, but the implementation is under no obligation to. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Chastity the most unnatural of the sexual perversions. -- Aldous Huxley From fumanchu at amor.org Mon Jun 7 00:12:25 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 6 Jun 2004 21:12:25 -0700 Subject: Misunderstanding about closures Message-ID: Alexander May wrote: > When I define a function in the body of a loop, why doesn't > the function "close" on the loop variable? > > >>> l=[] > >>> for x in xrange(10): > ... def f(): > ... return x > ... l.append(f) > ... > >>> for f in l: > ... f() > ... > 9 > 9 > 9 ...because "for" does have it's own scope. The 'x' which is bound in the 'for' statement persists in locals(), and it equals 9 after the 'for' terminates. Calling each f() simply looks up x in locals() each time; there's nothing going on in f() which tells Python that x should be in f's scope. That would require an assignment to x within f, usually. You could trot out the 'default arg' hack to work around this: >>> l = [] >>> for x in xrange(10): ... def f(y=x): ... return y ... l.append(f) ... >>> x 9 >>> [f() for f in l] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Robert Brewer MIS Amor Ministries From arctic at tuxtrax.com Sat Jun 5 16:46:54 2004 From: arctic at tuxtrax.com (TuxTrax) Date: 5 Jun 2004 13:46:54 -0700 Subject: Python on a thumbdrive Message-ID: <10d9011b.0406051246.7eac1408@posting.google.com> Hi all I use a macintosh and a pc at home. On My Mac, I have python installed. But my Pc hard drive recently failed and I have been running Damn Small Linux, a derivitave of Knoppix Linux direct from the cd. I like Damn small Linux much better than Knoppix, but DSL dosen't have python. An idea came to me: what if I could load a complete python distribution for unix onto a jumpdrive (also known as a thumbdrive or USB drive), those inexpensive flash memory stick drives that plug into the USB port. then I cold take python with me wherever I went. In fact, I could have versions for all platforms I was likely to encounter! so I bought a 128 meg jumpdrive and copied the python 2.3 directory from the knoppix disk to the jumpdrive. It copied fine. So I tried running it. Thats where the problems started. Becuase there was no linux installation on the jumpdrive, python looked to the ramdrive where all the usual files would be stored, and not finding them, gave me the following errors: Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Import site failed; use -v for traceback Python 2.3.3 (#2, May 1 2004, 06:12:12) [GCC 3.3.3 (debian 20040401)] on Linux 2 Type "help", "copyright", "credits" or "license", for more information. >>> Unlike the windows and Mac versions, you have to compile the Linux version which is why I copied it off of the Knoppix CD. due to my lack of a hard drive on the PC, I don't have GCC and it's associated files, and my lack of a swap file makes it impossible to compile from the Knoppix version of GCC due to only having 64 Megs of memory in the PC. I tried setting pythonhome from Bash: PYTHONHOME="/mnt/sda1/python/python2.3" No dice. Same errors. Any help achieving my goals of having a transportable python install on a jumpdrive would be greatly appreciated. regards, Mathew From claird at lairds.com Mon Jun 14 11:57:29 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 14 Jun 2004 15:57:29 -0000 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <10crin9k9sufi32@corp.supernews.com> In article , Peter Hansen wrote: >Ryan Paul wrote: > >> The proof is in the source. This is part of a ruby program I wrote. This >> snippet is actually a single 'line'. I broke it into several lines for >> slightly improved readability. This single line would probably take at >> least 15 lines to do in python, probably more if you wanted to do it >> intelligently. >> >> ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| >> Dir[$prefix+fn].collect {|x| >> x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| >> `cat #{sesc x}.* > #{sesc x}`} } > >This is proof of something, I'm sure, but for me it's simply another >indication that (a) Ruby is more like Perl than it is like Python, >(b) unreadable code can be written in any language, and (c) I >really don't mind using 15 lines to write something if it means >the resulting code can readily be understood. . . . Regular expressions are great. They're also limited. My experience is that it's quite rare for anything meaningful to an end-user to find its most natural implementation in an RE. That's what this subthread brings to *my* mind. I recognize that Mr. Paul was doing "utility programming", not application development. -- Cameron Laird Business: http://www.Phaseit.net From gerrit.muller at embeddedsystems.nl Fri Jun 11 03:10:29 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 11 Jun 2004 09:10:29 +0200 Subject: python and microsoft visio In-Reply-To: References: Message-ID: Jaco Smuts wrote: > > Hello there > > short question: Any body got experience in extracting information from > visio drawings using python. > I presume I am looking at something like > win32com.client.Dispatch('Visio.Application [or Drawing]), but I am a > bit lost. > > > long version: > I am about to embark on an excersize to document existing deployment of > middleware in our organisation. > (will also be used for design of future projects) > The standard used for architecture and design docs here is MS Visio. > I am hoping to write a python script to extract information from these > drawings. Then use this information to test the actual deployment vs. > the documents. > Any ideas will be appreciated. > > thanks > Jaco > Jaco, I am using Python to automate the generation of derived formats: eps and gif. My experiences with this combination are that Visio automation is somewhat shaky. I am using Visio 5. On the net I hear that newer Visio versions have changed the export functions I am using, but they did apparantly not improve :-(. The symptoms are Visio crashes because of some memory problem. Despite this intermittent problem I generate the complete Gaudi site, with over 700 different Visio Diagrams, with these tools. You are welcome to have a look at my scripts, but they are really very poorly documented, abosuletly non-fool proof, scripts. kind regards, Gerrit -- Gaudi systems architecting: From FBatista at uniFON.com.ar Wed Jun 9 10:59:45 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 9 Jun 2004 11:59:45 -0300 Subject: .idlerc directory - windoze Message-ID: [michael at foord.net] #- I use IDLE as my IDE (tried various... IDLE does more of what I want #- than any others). It's just started creating a directory called #- '.idlerc' in the directory of any file I try to edit... Is this #- because some environment variable has got screwed up ? ALWAYS worked for me in that way. I'm on w95. I would want to IDLE to open a .idlerc directory in only ONE place, and not everywhere. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sholden at flexal.cs.usyd.edu.au Fri Jun 18 21:42:53 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 19 Jun 2004 01:42:53 GMT Subject: Game - Map data structures References: Message-ID: On Fri, 18 Jun 2004 22:58:45 +0200, Pierre-Fr?d?ric Caillaud wrote: > > Save memory by having all the water tiles pointing to the same water > instance. > > water = WaterTile() > > ... build your tiles : > > if tile should be water: > tile[x][y] = water # doesn't instanciate > else: > tile[x][y] = GroundTile() # instanciate new object That's going to make it really hard to determine which boats are on a given water tile. -- Sam Holden From tjreedy at udel.edu Mon Jun 7 08:29:08 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Jun 2004 08:29:08 -0400 Subject: python -- question with list.pop(0) References: Message-ID: "David Stockwell" wrote in message news:BAY2-F110eI4ks6AM1w0001905d at hotmail.com... > ourFile = open(fileNamesList[0],'r') > strData = ourFile.read() >From what you do below, you want .readlines() > ourFile.close() > > records = [] > print "split 0.5" > records.append(strData.split("\n")) strData.split('\n') is a list of lines. append adds one element to a list -- in this case the list of lines. You apparently want .extend() > print "records '%s'" % records > === end snippet ==== > at this point the output looks like this > > '[['this is line 1', 'this is line 2', 'this is line 3', '' ]]' right, as you requested, even if not what you meant ;-) Terry J. Reedy From a at a.invalid Fri Jun 4 13:46:14 2004 From: a at a.invalid (Timo Virkkala) Date: Fri, 04 Jun 2004 17:46:14 GMT Subject: Python reference In-Reply-To: References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> <2i9g5sFjg95hU1@uni-berlin.de> Message-ID: > I hope that this is taken in a spirit of _constructive_ criticism, > AFAIK pyDoc can do this type of thing already - would it be an idea to > put a pyDoc type language reference on the python.org webpage? How about http://pydoc.org/ And then there's always http://starship.python.net/crew/theller/pyhelp.cgi You can give it a word to search through the python documentation. -- WT From customer at service.boy Sat Jun 12 05:02:24 2004 From: customer at service.boy (jim) Date: Sat, 12 Jun 2004 09:02:24 GMT Subject: python+kinterbas+gui+web+boa Message-ID: hi- is anyone using this combo of tools? do you have a website i can visit or gui with screen shots or fairly easy to install so i can get inspired? now that firebird has its first manual and python has manuals published i can read and get up to speed. i am not crazy about a c++ style reference manual but i now have cable internet and a couple of c++ books so if i work hard i believe i can get the hang of it. i know that wxwidgets and wxpython work extremely hard on the documentation and it is very thorough and that is one of the big reasons i chose to go this route. i cant wait to get started writing code and reading manuals. later jim From mark at prothon.org Wed Jun 16 15:40:10 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 16 Jun 2004 12:40:10 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: Andrea Griffini wrote: > That's what I mean with "I'm new to python" :-) > >> def another( x ): >> y = getattr( another, 'static', 10 ) >> another.static = x >> return y >> >> print another(1), another(2), another(4) > > I like more as an example: > > >>> def foo(x): > ... if not hasattr(foo,'list'): > ... foo.list = [] > ... foo.list.append(x) > ... print foo.list In Prothon: def foo(x): print foo.list.append!(x) foo.list = [] (Sorry. I couldn't resist bragging.) From gandalf at geochemsource.com Tue Jun 1 12:38:41 2004 From: gandalf at geochemsource.com (Gandalf) Date: Tue, 01 Jun 2004 18:38:41 +0200 Subject: Authentication for socket communication ... In-Reply-To: <68fec103.0406010601.43c8ca4c@posting.google.com> References: <68fec103.0406010601.43c8ca4c@posting.google.com> Message-ID: <40BCB111.2050703@geochemsource.com> >Im using a derived HTTP socket server, the base class in python. >I've got a modified version of the implementation, right now I >want to introduce authentication of users in my server. What is >the best way to implement this? The server is on the machine running >the user database. > >So how do I validate a user and a password with the system? >Are there any modules for this? How should passwords be sent? >Using clear-text isnt good enough! > > Well, I would suggest HTTPS because it is transparent so you can send the password safely. However, you said you are using a derived version of the HTTP socket server. Probably it cannot handle HTTPS. In that case, it is a very good idea to use OTP (One Time Password) authentication. The basic idea is that you do not send the passwords in clear text. Instead of that, you send a hash of the password. The hash function must be different for each connection. There are standards (RFCs) for OTP authentication. But of course you can implement yours. For standard OTP, please read the RFCs. You will need OpenSSL to follow the standards. To create your own OTP algorithm, please follow this scheme: 1. Client connects to the server 2. Client sends the user name to the server 3. The server generates a random string and sends it to the client 4. The client generates a random string and sends it to the client 5. At this point, both the server and the client know both random strings and the password. Both the server and the client should setup a session key using these values. A listener person or in-the-middle attacker cannot calculate the same session key because it does not know anything about the password. Important: the generation of the session key should be FULLY dependent on both of the random strings and the password and should be non-invertable (e.g. use cryptographically secure hash functions). 6. Optional: After this point you have a session key on both sides, you can setup a cipher on both sides to have an encrypted connection 7. Both the server and the client shoud setup a new hash function H() that is dependent on the session key 8. The server sends another random string 9. The client calculates its hash value using H() 10. The client sends back the calculated hash value 11. The server checks if the hash value maches the one calculated locally. If not, terminate the connection. If there is a match then the authentication was successful. The advantage of your own protocol is... a.) You only need a hash function. No encryption, no openssl etc. The built-in sha module is more than enough. As a result, your software will be more portable. b.) In theory, in specific scenarios, this system can be more secure than a standard authentication algorithm. E.g. if your clients and your servers are totally trustful then using a private protocol can be very hard to crack. (Of course this is not the case when you want to create a widely used, popular program.) Hope this helps. Best, Laci 2.0 From python at quixs.com Fri Jun 18 09:11:37 2004 From: python at quixs.com (Lars Heuer) Date: Fri, 18 Jun 2004 15:11:37 +0200 Subject: Python mentioned In-Reply-To: References: Message-ID: <533369715.20040618151137@quixs.com> Hi David, > python newbie wrote: >> Page 3 or 3 of this article on XUL (xml-based way of building browser-based >> apps in Mozilla), mentions that Python is built in as the scripting >> language) >> http://www.devx.com/webdev/Article/21350 >> >> > Note that this is talking about somebody else's XUL toolkit, not Mozilla The problem is that the author himself mixes Mozilla XUL and the luxor-xul of Gerald Bauer. There is a long fight from the Mozilla community against Gerald Bauer, because he spreads confusion with a technology which is named XUL, but is not (Mozilla) XUL (and the article is a good example for this confusion). But it's true, that you can get access to Mozilla via pyXPCOM and maybe the Mozilla community will use Python as scripting language for the front-end (currently only JavaScript is supported). http://www.mozilla.org/events/dev-day-feb-2004/mozilla-futures/ Especially: http://www.mozilla.org/events/dev-day-feb-2004/mozilla-futures/langs.html Best regards, Lars From martin at v.loewis.de Sun Jun 13 05:13:32 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 11:13:32 +0200 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: <40CC1ABC.4010400@v.loewis.de> Roger Binns wrote: > Peter Hansen wrote: > >>Do _you_ have a solution? If you do and it really works, >>it seems to me unlikely it would be ignored... > > > I would do the same thing that shutdown does. Run > the destructors, but don't delete the underlying > memory. Set all the fields to None (just as shutdown > points modules at None). Finally in a second round > actually free the memory. At what point would you do the shutdown, and to what objects would you apply it? "the same thing as shutdown" means that you clear out all modules. If the answer to the first question is "at the end of the function", then any Python application will crash as soon as the first function returns, as then all modules will be useless. Regards, Martin From Rigga at hasnomail.com Wed Jun 23 16:36:50 2004 From: Rigga at hasnomail.com (Rigga) Date: Wed, 23 Jun 2004 21:36:50 +0100 Subject: String help Message-ID: Hi, I am new to python and am working on a script that parses a file and loads the results in to variables for processing. I am having problems when it comes to data in the file that wraps over two lines i.e. las - lomas What i want to be able to do is to some how strip all the spaces from it so while it is contained as a variable so it equal 'las - lomas' How do I go about doing this? I have tried it using the string.strip(myvariable,"") however that doesnt appear to do anything. Any help appreciated Rigga From xholcik1 at fi.muni.cz Thu Jun 17 08:30:29 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Thu, 17 Jun 2004 12:30:29 GMT Subject: regexp substitution - a lot of work! In-Reply-To: References: Message-ID: Is it really that easy? Now I see Python is simply the best:)))! I just didn't know, how to use groups in a different way than MatchObject.group(..). You already answered that, thanks!:) ---------------------------------------_.)-- | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* ----------------------------------------''-- On Thu, 17 Jun 2004, Duncan Booth wrote: > Lukas Holcik wrote in > news:Pine.LNX.4.60.0406161824510.15043 at nymfe30.fi.muni.cz: > >> Yes, sorry, I was in such a hurry I didn't found it in the >> documentation, but when I want to use a lot of very different >> expressions using a lot of different grouping, which would be easy to >> implement using s/(..)/x\1x/ then it is quite problematic having to >> use re.sub(), isn't it? >> > > I don't understand your point. The Python equivalent is: > > re.sub('(..)', r'x\1x', s) > > or using a precompiled pattern: > > pat.sub(r'x\1x', s) > From martin at v.loewis.de Mon Jun 21 02:11:13 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 21 Jun 2004 08:11:13 +0200 Subject: test if PyObject * points to real python object In-Reply-To: References: Message-ID: <40D67C01.2030707@v.loewis.de> David McNab wrote: > With the Python/C API, how do i test if a given PyObject * actually > points to a real/valid python object? As opposed to being a NULL pointer? o != NULL As opposed to being a stray pointer, to garbage memory? You can't. Regards, Martin From hungjunglu at yahoo.com Thu Jun 3 00:26:35 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 2 Jun 2004 21:26:35 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> Message-ID: <8ef9bea6.0406022026.954155e@posting.google.com> Alexander Schmolck wrote: > [1] Here are a few of the hacks I'm using, in case anyone might > find them useful -- or even better tell me about better > alternatives (If someone has cooked something reasoable > for reloading modules, I'd love to hear about it). I have already answered to you on one previous occasion, and told you another time in this present thread. I've used this kind of trick in wxPython. It's good for interactively developing widgets, without re-starting your program. Now here is a third try. :) ( For the first time, see: http://groups.google.com/groups?q=g:thl272312511d&dq=&hl=en&lr=&ie=UTF-8&selm=8ef9bea6.0308220959.74317026%40posting.google.com ) You can of course use a metaclass to make things a bit easier. Here is a draft version. #----- autoupdate.py '''metaclass for auto-update classes''' class __metaclass__(type): # automatically keeps tracks of instances def __new__(cls, class_name, bases, class_dict): import inspect module_name = class_dict['__module__'] instance_dict_name = '_%s__instances' % class_name # see if there is already an older class import sys old_instance_dict = None if sys.modules.has_key(module_name): module = sys.modules[module_name] if hasattr(module, class_name): old_instance_dict = getattr( getattr(module, class_name), instance_dict_name) # add instance list import weakref class_dict[instance_dict_name] = weakref.WeakValueDictionary() # override the __init__ if class_dict.has_key('__init__'): def new_init(self, *args, **kw): instance_dict_name = '_%s__instances' % ( self.__class__.__name__) getattr(self.__class__, instance_dict_name)[id(self)] = self self.__original_init__(*args, **kw) class_dict['__original_init__'] = class_dict['__init__'] class_dict['__init__'] = new_init else: def new_init(self, *args, **kw): instance_dict_name = '_%s__instances' % ( self.__class__.__name__) getattr(self.__class__, instance_dict_name)[id(self)] = self class_dict['__init__'] = new_init # build the class, with instance_dict new_class = type.__new__(cls, class_name, bases, class_dict) # copy over the instance dictionary, and update __class__ if old_instance_dict is not None: for instance_id, instance in ( old_instance_dict.iteritems()): getattr(new_class, instance_dict_name)[instance_id] = instance instance.__class__ = new_class # return new class return new_class #----- Spam.py from autoupdate import __metaclass__ class Egg: '''Put here your class code''' # def print(self): # print 'Hello World!' #----- from your Python console import Spam x = Spam.Egg() # ... edit your Spam.py file and change code for Spam.Egg class, # e.g.: add a print() method to Spam.Egg by uncommenting # the corresponding lines. Save the file. reload(Spam) x.print() # prints 'Hello World!' --------------------- regards, Hung Jung From eppstein at ics.uci.edu Tue Jun 15 12:53:12 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 15 Jun 2004 09:53:12 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <60dfb6f6.0406150827.6dcc5ef5@posting.google.com> Message-ID: In article <60dfb6f6.0406150827.6dcc5ef5 at posting.google.com>, imbosol at aerojockey.com (Carl Banks) wrote: > > > import glob > > > import os > > > import re > > > > > > f = {} > > > for pattern in ("*.rar.*","*.r[0-9][0-9].*"): > > > for listing in glob.glob(prefix+pattern): > > > f[listing] = None > > > for filename in f: > > > os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) > > > > > > > > > I don't know what sesc is. I assume he had defined it elsewhere, > > > because he said this was only part of a script he wrote (and that's > > > what scares me--I can understand a throwaway one-liner looking like > > > this, but not a line in a script). > > > > As long as we're cleaning up code, how about > > > > import glob, os, sets > > f = Set() > > for pattern in ("*.rar.*","*.r[0-9][0-9].*"): > > f.update(glob.glob(prefix+pattern)) > > for filename in f: > > os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) > > > > Now it's not even much longer than the original unreadable mess... > > I just noticed that I mistakenly left out the regexp in my clean code. > Where I had f[listing] = None, I should have > f[re.sub(r"\.\d+[\d.-]*$","",listing)] = None, or an extra varible. I was wondering where the import re was supposed to be used... so the line f.update(glob.glob(prefix+pattern)) should become for listing in glob.glob(prefix+pattern): f.add(re.sub(r"\.\d+[\d.-]*$","",listing) I guess? Not so different from what you posted, after that change... As long as we're admitting to mistakes in code, I should have used sets.Set instead of just Set in the second line. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From nick125 at comcast.net Fri Jun 25 07:09:26 2004 From: nick125 at comcast.net (Nick) Date: Fri, 25 Jun 2004 05:09:26 -0600 Subject: what editor do you use? In-Reply-To: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <40DC07E6.8060906@comcast.net> Sticks wrote: > i'm new to python and i was wondering what editors people prefer to > use and why. i use kdevelop because of its ease of use, syntax highlighting, indenting, cvs built in and multiple language support. for more features go to: http://kdevelop.kde.org/index.html?filename=3.0/features.html From Bernd.Nawothnig at t-online.de Wed Jun 2 08:37:36 2004 From: Bernd.Nawothnig at t-online.de (Bernd Nawothnig) Date: Wed, 2 Jun 2004 14:37:36 +0200 Subject: noddy example, writing C modules for python References: Message-ID: Hi Torsten, On Sun, 30 May 2004, Torsten Mohr wrote: > based on the example module "noddy" i wrote an own one > and i have problems accessing the elements in the python > objects. I defined the example object: > typedef struct { > PyObject_HEAD > int num; > } pmod_obj; > static PyMemberDef pmod_members[] = { > {"number", T_INT, offsetof(pmod_obj, num), 0, /* LINE 143 */ > "pmod number"}, > {NULL} > }; > When i compile this under Win32, i get this (in german): > pmod.cc(143) : error C2552: 'pmod_members': Initialisierung nicht > zusammengesetzter Typen mit Initialisierungsliste ist nicht m?glich > 'PyMemberDef' : Typen mit benutzerdefinierten Konstruktoren sind > nicht 'aggregate' The explanation is shown quite clear in plain German - where is your problem? :-) One is sure: your problem has nothing to do with Python but with C++. Only for short, look at this example: #v+ class A { public: char *s; A(): s("") {} } a = {"Hallo"}; #v- That cannot compile too because there are two different initializations: one via constructor and the second via initialization list. So, of course, Gnu g++ also complains: test.cc:24: error: `a' must be initialized by constructor, not by `{...}' HTH & f'up2 Bernd -- Those who desire to give up freedom in order to gain security, will not have, nor do they deserve, either one. [T. Jefferson] From irmen at -nospam-remove-this-xs4all.nl Tue Jun 15 13:30:55 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 15 Jun 2004 19:30:55 +0200 Subject: Arjen Jongeling, een oude bekende In-Reply-To: <40cf235d_3@127.0.0.1> References: <40cf235d_3@127.0.0.1> Message-ID: <40cf324f$0$563$e4fe514c@news.xs4all.nl> Arjen Jongeling wrote: > Hoewel, Arjen Jongeling is hier nog nooit geweest en ik denk dat Arjen Jongeling hier > ook nooit meer zal terugkomen. Sterker nog, Arjen Jongeling zit hier helemaal fout. > Maar ja, het doet het goed in de Google archieven. Volgens mij heeft iemand z'n computer onbeheerd achtergelaten. [I think somebody left his computer unattended]. --Irmen From grante at visi.com Wed Jun 30 11:25:47 2004 From: grante at visi.com (Grant Edwards) Date: 30 Jun 2004 15:25:47 GMT Subject: setting icon using py2exe? References: Message-ID: On 2004-06-30, Thomas Heller wrote: >> Never mind.... >> >> Further googling reveals this is a known bug when running under >> Win98/Me: >> >> http://groups.google.com/groups?th=4d594c535345b98b > > The bug should be fixed in CVS. Since py2exe now can also be built with > MingW32, you could try that, even if you don't have MSVC. Or you have > to wait for the release. Thanks! If I run out of things to do, I'll install MingW32 and try to build the CVS code. Otherwise I'll wait for the next release. -- Grant Edwards grante Yow! It was a JOKE!! Get at it?? I was receiving visi.com messages from DAVID LETTERMAN!! YOW!! From chrisks at NOSPAMudel.edu Sat Jun 26 02:44:31 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 26 Jun 2004 02:44:31 -0400 Subject: new to this In-Reply-To: References: Message-ID: pearsoneric wrote: > I have never tried to program before but I'm starting a class and I > was wondering if anyone knew the best way to get started learning > about python?? Any help would be very much welcomed because I have > no idea what I'm doing.. Are there any good books out there? There are several good books, but the best place to start is www.python.org/doc From lard at tardis.ed.ac.molar.uk Fri Jun 25 07:53:50 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Fri, 25 Jun 2004 12:53:50 +0100 Subject: python image library making dotty gifs In-Reply-To: <10do3bfmr93ke48@corp.supernews.com> References: <10do3bfmr93ke48@corp.supernews.com> Message-ID: <10do4ifds0a7j58@corp.supernews.com> Alex Hunsley wrote: > I'm using python image library 1.1.4 > (http://www.pythonware.com/products/pil/) to plot images. > However, when I save an image to a gif file, it comes out very > dotty/ithered looking, even if it's a picture consisting only of one > colour! > > Here's some example code that produces a dotty gif: > > #!/usr/bin/python > > # pymand joy! > > import Image > import ImageDraw > > > imageWidth=300 > imageHeight=300 > > im = Image.new("RGB", (imageWidth, imageHeight)) > > > draw = ImageDraw.Draw(im) > for y in range (0,imageHeight): > for x in range (0, imageWidth): > draw.point((x, y), (128,128,128)) > > # saving as a gif comes out dotty/dithered looking! > im.save("plotImage.gif", "GIF") > > > you can see the output gif here: > > http://ohmslaw.ogr.uk/plotImage.gif sorry, duff link, should be .org.uk: http://ohmslaw.org.uk/plotImage.gif From __peter__ at web.de Tue Jun 8 11:56:21 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 17:56:21 +0200 Subject: Problem with Python xrange References: <5155aad2.0406080709.698cba47@posting.google.com> Message-ID: Konstantin Veretennicov wrote: > Write a class implementing the behaviour you need. You'll want to > implement xrange interface and slicing protocol. It's not possible to > subclass xrange (yet?), so you'll have to delegate. class XRangeFactory(object): def __getitem__(self, index): if isinstance( index, slice): if index.step is None: return xrange(index.start, index.stop) return xrange(index.start, index.stop, index.step) return xrange(index) makeRange = XRangeFactory() assert list(makeRange[5]) == range(5) assert list(makeRange[7:11]) == range(7, 11) assert list(makeRange[7:19:2]) == range(7, 19, 2) Peter From menucool at yahoo.com.cn Fri Jun 25 06:33:07 2004 From: menucool at yahoo.com.cn (coolmenu) Date: 25 Jun 2004 03:33:07 -0700 Subject: question about cx_Oracle .thanks References: Message-ID: David Fraser wrote in message news:... > coolmenu wrote: > > Hi > > i hava a db ORACLE 10G,a table valid_card > > (card_no,varchar2(10),now_balance number (12,2)) > > > > its'some record in table ('7188','42055.66') > > > > i use cx_Oracle to select now_balance from table > > > > curobj.execute("select loan_amount from valid_card where > > card_no='7181930166881974'"); > > [] > > > >>>>tuple=curobj.fetchone() > >>>>tuple > > > > (42505.660000000003) > > > > why 42505.66---->42505.6600000000003??? > > thanks > > This is because of the conversion of the float to decimal. Float objects > have limited accuracy. I don't think it's much to do with cx_Oracle > > David Can someone give me a advice? how can i do? donnt select number from oracle? From nhodgson at bigpond.net.au Tue Jun 8 17:49:10 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 08 Jun 2004 21:49:10 GMT Subject: how to add breakpoint at multithread program in pythonwin? References: Message-ID: gaoshan: > breakpoints did not work! help! Debugging multithreaded programs is not supported well by Python. There was a proposal to work on this: http://aspn.activestate.com/ASPN/Mail/Message/1610516 This may work: http://www.python.org/pypi?:action=display&name=rpdb.py&version=1.00 Neil From tjreedy at udel.edu Tue Jun 22 19:25:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jun 2004 19:25:48 -0400 Subject: Improving upon the Decorate-Sort-Undecorate idiom References: Message-ID: <7NSdnT6pIsudXUXdRVn-jA@comcast.com> "Thomas Philips" wrote in message news:b4a8ffb6.0406221212.741d2379 at posting.google.com... > I recently had the need to sort a large number of lists of lists, and > wondered if an improvement to the Decorate-Sort-Undecorate idiom is in > the works. See What's New for 2.4 at python.org. From peter at engcorp.com Mon Jun 14 09:05:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 09:05:29 -0400 Subject: A faster way of finding historical highs/lows In-Reply-To: <47e15340.0406111301.6cf1b3f1@posting.google.com> References: <47e15340.0406110356.3629d3e6@posting.google.com> <47e15340.0406111301.6cf1b3f1@posting.google.com> Message-ID: Eamonn Sullivan wrote: > Peter Hansen wrote in message news:... >>The fastest algorithm might depend on how you use the data, as well. > > Thanks for this. At the moment, the software answers a few questions > (highest/lowest, longest streak, etc.) once per retrieval of data. The > database retrieval, though, is *by far* the biggest time sapper, so a > little preprocessing would be almost unnoticeable in comparison, > probably (depends on how much, of course). > > So, I'm guessing I could sort on the particular price field I'm using > (decorate-sort-undecorate), and then just find the most recent date > among the subset of data that meets the criteria (higher or lower). Is > that what you mean? That's exactly the type of thing I meant, and even the specific improvement I was considering. > By binary search, do you mean further reorganizing > the data into a binary tree using date? The binary search is just a lot faster way of homing in on a region of the data compared to most other approaches. If it's sorted by price, then binary search to get to the chunk with prices equal to what you want. The last one (assuming ascending dates) is the "most recent with an equal or lower price", or if there is none equal, pick the one to the left of the final binary search point... that kind of thing. For a binary search, you just examine the data element halfway between two end points each time, comparing it with the search target. Decide if you need to continue search to the left or the right of the current position, then pick a point halfway into _that_ region and do it again. Eventually you are down to a region with a single point, and then you're done. It takes only log2(n) comparisons to search in n points, and often less... -Peter From irmen at -nospam-remove-this-xs4all.nl Sun Jun 20 03:02:58 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 20 Jun 2004 09:02:58 +0200 Subject: Access SSL websites with Python? In-Reply-To: <85c78d18.0406191921.f7dcbc7@posting.google.com> References: <85c78d18.0406191921.f7dcbc7@posting.google.com> Message-ID: <40d536a2$0$563$e4fe514c@news.xs4all.nl> Byron Morgan wrote: > I need to access a web site, log in, run a report and download the > results, which will be added to a database. Of course, the login > process uses SSL. Is it reasonable to attempt this with Python 2.3 on > Windows 2000 platform? Can anyone provide an example of negotiating an > SSL session? urllib2 should be able to use HTTPS:// urls just fine. If you require cookie processing to log in on the website, look at ClientForm and/or ClientCookie. (http://wwwsearch.sourceforge.net/ClientForm/) -irmen From dkturner at telkomsa.net Fri Jun 11 16:38:24 2004 From: dkturner at telkomsa.net (David Turner) Date: 11 Jun 2004 13:38:24 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Roy Smith wrote in message news:... > dkturner at telkomsa.net (David Turner) wrote: > > 1. Objects of classes that declare a __del__ method shall be referred > > to as "deterministic" objects. Such objects shall have a reference > > count associated with. The reference count shall be incremented > > atomically each time an additional reference to the object is created. > > The reference count shall be decremented each time a name referring > > to the object is deleted explicitly. Except in the situation > > described in (2) below, the reference count shall be decremented each > > time a name referring to the object becomes inaccessible due to the > > set of locals to which the name belongs becoming inaccessible. > > [...] > > 3. When the reference count of a deterministic object reaches zero, > > the __del__ method of the object shall be called. > > What if you do this... > > class Top: > def __init__ (self): > self.bottom = Bottom () > > class Bottom: > def __del__ (self): > do something really important > > top = Top () > del top > > The problem here is that while Bottom.__del__ will get called as soon at > top releases it's reference, there's nothing to guarantee that the > reference will disappear until top is garbage collected. You could fix > that by writing Top.__del__, but that assumes Top is a class you have > control of (it might be something out of a library). > > Or am I not understanding the situation right? This particular example you cite is not actually problematic. The point is that the resources are cleaned up when Top is cleaned up, which is what we want. How and when Top is cleaned is neither here nor there. However, you have touched on a deep issue. When an object is cleaned up, whether using an explicit __del__ or implicitly, any deterministic objects it contains will of course have to be cleaned up (in the reverse order of allocation, again). With an explicit __del__, this is probably okay. But when a deterministic object is in the scope of a non-deterministic object, there could be an implementation problem. Perhaps someone with more insight into Jython than I could shed some light on whether or not this would be an issue? Regards David Turner From newsgroups at jhrothjr.com Thu Jun 17 09:07:52 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 17 Jun 2004 09:07:52 -0400 Subject: datetime, calendar, time intervals References: <95aa1afa.0406162213.3cf3d7f7@posting.google.com> Message-ID: <10d35suo3ek1b51@news.supernews.com> "David Eppstein" wrote in message news:eppstein-ABCC82.23210816062004 at news.service.uci.edu... > In article <95aa1afa.0406162213.3cf3d7f7 at posting.google.com>, > michele.simionato at poste.it (Michele Simionato) wrote: > > > Strangely enough, I never needed the datetime and calendar module > > before, so I just looked at them today. > > Me too. datetime was exactly what I wanted. Until I realized that it > wasn't available in the 2.2.3 installation I needed my code to run in... Yeah, that's a problem. I've been avoiding putting a date type adapter in the Python version of FIT for exactly that reason. Which brought up the question of whether it would be possible to back-port it, and I found that it was a C language module. Sigh. John Roth > > -- > David Eppstein http://www.ics.uci.edu/~eppstein/ > Univ. of California, Irvine, School of Information & Computer Science From BrenBarn at aol.com Sun Jun 27 14:34:20 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 27 Jun 2004 18:34:20 GMT Subject: wxPython syntax Message-ID: I've started taking a look at wxPython, and, well, I've noticed that the syntax needed to code with it is extremely ugly. I am wondering if there exist any preprocessing tools or clever refactorings that allow users to write more sane-looking code. In particular, it seems to me that the structure of the code often does not reflect the structure of the GUI being designed. For instance, the wxPython wiki "Getting Started" guide includes this code to set up a file menu with About and Exit options: filemenu= wxMenu() filemenu.Append(ID_ABOUT, "&About","Information about this program") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit","Terminate the program") # Creating the menubar. menuBar = wxMenuBar() menuBar.Append(filemenu,"&File") self.SetMenuBar(menuBar)content. EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.OnExit) self.Show(true) def OnAbout(self,e): d= wxMessageDialog( self, "A sample editor \n" "in wxPython","About Sample Editor", wxOK) d.ShowModal() d.Destroy() def OnExit(self,e): self.Close(true) Pieces of the code, like "filemenu" and ID_ABOUT and OnAbout, are confusingly repeated throughout the definition. Doesn't it seem like there should be some way to structure it so that the interface nesting "option in menu in frame" is reflected in the code? I want to do something like this: menus: File(wxMenu): name = "&File" about(menuOption): name = "About" statusText = "Information about this program" action(): wxMessageDialog(self, "A sample editor. . .") exit(menuOption): name = "Exit" etc. . . Now, obviously that isn't valid code, but it seems like it might be possible to get something like by using nested classes and/or functions (e.g., have it say "class menus:" and then "class file(wxMenu)"). So my basic questions are: 1) Does anything like this exist (or is anything in development)? Is there any way to write GUI code in a way that reflects the structure of the GUI? 2) If not, is it possible? 3) One specific problem is that I can't find a way to get at the information in nested classes. Does Python provide any way to, say, take a certain class and loop through all the classes which are defined as nested classes inside it? Or, more generally, what kind of syntactic help can be had from Python with regard to creating nested structures like this? Any thoughts would be appreciated. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From gabor at z10n.net Sat Jun 26 18:00:11 2004 From: gabor at z10n.net (gabor farkas) Date: Sun, 27 Jun 2004 00:00:11 +0200 Subject: i have a big dictionary...:) In-Reply-To: <1088275878.20902.7.camel@dubb> References: <1088275878.20902.7.camel@dubb> Message-ID: <1088287211.20902.10.camel@dubb> On Sat, 2004-06-26 at 20:51, gabor farkas wrote: > hi, > > i have a big dictionary... thx for all the info.. just for you to know, i ended up with 'shelve'. because my keys are strings (unicode ones, but i encoded them to UTF-8 for shelve), but the values are string + list-of-strings pairs... so not strings :) but shelve works perfectly... thanks, gabor From rigga at hasnomail.com Sat Jun 26 06:45:29 2004 From: rigga at hasnomail.com (RiGGa) Date: Sat, 26 Jun 2004 11:45:29 +0100 Subject: Help formatting a mysql query string Message-ID: Hi, I am trung to create a mysql query string that contais two variables, the first holds a table name and the second holds the values as a tuple. I have tried the following however I can not work out how to get the format right so the %s is subsituted with the contents of the variable, I think I just have the quoting wrong, can anyone advise? tablename contains the table I want to use datavalue contains the data I want to use (contains multiple fields, we will say 3 here for this example) sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" Any help appreciated Thanks Rigga From tor.iver.wilhelmsen at broadpark.no Tue Jun 8 16:39:50 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 08 Jun 2004 22:39:50 +0200 Subject: promoting [] by superclass? References: <2imf46Fo9eusU1@uni-berlin.de> Message-ID: Jim Newton writes: > class x1(list): > def __init__(y): > pass You lack a "self" argument there for it to be a real initializer. > what does x1([]) do and what does x2([]) do? >>> x = x1([]) Traceback (most recent call last): File "", line 1, in ? TypeError: __init__() takes exactly 1 argument (2 given) x2([]) works though, since it uses the __init__ in list. From fishboy at spamspamspam.com Mon Jun 7 00:12:20 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 07 Jun 2004 04:12:20 GMT Subject: how to get memory info from python? References: Message-ID: On Mon, 07 Jun 2004 02:44:44 GMT, "Andy C" wrote: >I posted a similar question awhile back but have not been able to get any >info. I wanted to see if Python could be embedded in game consoles -- but >the lack of memory info is a dealbreaker. If you look in google there are a >lot of people asking this same question with no info! > >Andy > > > >"Gardner Pomper" wrote in message >news:mailman.637.1086562751.6949.python-list at python.org... >> Hi, >> >> I'm pretty new to python, but I have not found any way to find out how >much >> memory is being used by my python application. I have some fairly large >data >> to load in and I am concerned about hitting the 2GB limit on my 32 bit >> processes. >> >> I would like to have the program check itself for memory usage. I know I >can >> get the memory information from a 'ps -l'. Btw, I will be running on AIX >and >> linux, although I may do some development on Windows. >> >> - Gardner >> >> Well..... I little poking around in obmalloc.c came up with: /* Print summary info to stderr about the state of pymalloc's structures. * In Py_DEBUG mode, also perform some expensive internal consistency * checks. */ void _PyObject_DebugMallocStats(void) { [snip] } obmalloc.c also has a LOT of infomation about Pythons memory in comments. So there's certainly the possibility of a roll-your-own. although maybe only for the DEBUG build. ><{{{*> From tzot at sil-tec.gr Fri Jun 4 04:44:19 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 04 Jun 2004 11:44:19 +0300 Subject: How to pickle a subclass of tuple? References: Message-ID: On Thu, 03 Jun 2004 17:52:45 -0700, rumours say that Shalabh Chaturvedi might have written: >Christos TZOTZIOY Georgiou wrote: > >> __getstate__ is easy: >> >> def __getstate__(self): >> return tuple(self) >> >> but even >> >> def __getstate__(self): >> return self >> >> seems to work, as far as Pickle.dump is concerned. The problem is, how >> one writes a __setstate__ for an immutable class? > >Why do you need to do this i.e. redefine __getstate__() and __setstate__()? > >Doesn't just pickling instances of your class work? > > >>> class T(tuple):pass >... > >>> t = T((1,2)) > >>> t.a = 33 > >>> import pickle > >>> x = pickle.loads(pickle.dumps(t)) > >>> x >(1, 2) > >>> x.a >33 Oh, yeah, I forgot to mention that I also define __slots__ to avoid having a dictionary; I do that because I need to create *really* lots of instances, and the memory usage became prohibiting for the specific computer I want this to run (a firewall). It's data about various of ip addresses related to an anti-spam program. I want to cache results to avoid running DNS requests every time. So, apart from advice on how to circumvent this for my specific problem (eg, run on another computer, don't base on tuple etc) since I already have circumvented it, I would still like to find out if it is possible or not to pickle a tuple-based class with __slots__ defined. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From pythonguy at Hotpop.com Thu Jun 3 04:38:05 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 3 Jun 2004 01:38:05 -0700 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> <10bsls7skd4ul7e@corp.supernews.com> Message-ID: <84fc4588.0406030038.1059a247@posting.google.com> Since types and classes are unified in the new object model, the following line at the top of the source file will also do the trick, even if you dont directly subclass from object. __metaclass__ = object class Rectangle... etc -Anand "Ixokai" wrote in message news:<10bsls7skd4ul7e at corp.supernews.com>... > The problem is that the __slots__ mechanism is a function of "new style > classes", which really should be renamed =) A new-style-class is any class > that inherits from "object" or one of its descendants. > > You're inheriting from Rectangle. What is its definition? I bet its > something like: > > class Rectangle: > def __init__(self): pass > > Since OptimizedRectangle inherits from an old-style class, its an old-style > class... and __slots__ has no function. > > So, just... > > class Rectangle(object): pass > > And OptimizedRectangle should work like you expect. > > --Stephen > > "Porky Pig Jr" wrote in message > news:56cfb0e3.0406021358.3d50d921 at posting.google.com... > > Hello, I"m still learning Python, but going through the Ch 5 OOP of > > Nutshell book. There is discussion on __slots__, and my understanding > > from reading this section is that if I have a class Rectangle (as > > defined in some prior sections), and then I provide definition > > > > class OptimizedRectangle(Rectangle): > > __slots__ = 'width', 'heigth' > > > > I can use the instance of OptimizedRectangle, say, x, with 'width' and > > 'heigth', but (quoting the book) 'any attempt to bind on x any > > attribute whose name is not in C.__slots__ raises an exception. > > > > Alas, something goes wrong here, but I *can* bind any arbitrary > > attribute, and seems like the instance of OptimizedRectangle does have > > its own __dict__ where those attributes are kept. I'm using the latest > > stable version of Python (2.3.4, I believe). Here is a session from > > IDLE: > > > > Here I'm defining the class with __slots__: > > > > >>> class OptimizedRectangle(Rectangle): > > __slots__ = 'width', 'heigth' > > > > > > and create its instance, 'ropt': > > >>> ropt = OptimizedRectangle(4,5) > > > > Note that __dict__ is still there: > > >>> ropt.__dict__ > > {} > > > > so I can define some arbitrary variable, say, newarea: > > > > >>> ropt.newarea = 15 > > > > which goes into the dictionary > > > > >>> ropt.__dict__ > > {'newarea': 15} > > > > whereas width and heigth are still kept in __slots__: > > >>> ropt.__slots__ > > ('width', 'heigth') > > > > My impression is that once __slots__ are defined, __dict__ is > > effectively disabled - but in this example it's alive and well. Am I > > missing anything here? > > > > TIA. From donn at u.washington.edu Wed Jun 30 14:51:33 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 30 Jun 2004 11:51:33 -0700 Subject: poplib for multihomed machines References: <9418be08.0406280751.6cc50097@posting.google.com> <9418be08.0406291005.34d4277b@posting.google.com> <9418be08.0406300932.6bacb6f8@posting.google.com> Message-ID: In article <9418be08.0406300932.6bacb6f8 at posting.google.com>, elbertlev at hotmail.com (Elbert Lev) wrote: > > If the practical issues can be resolved by factoring the > > network connection out into a separate function, then that's > > a practical solution, don't you think? > > Fixing this particular piece of code is very simple. But let's talk > about big system. If all classes in standard library are written like > POP3 class (and most of them are) you will "tailor for your needs" > most of them. Not subclass but copy and modify! So the standard > library becomes a "reference material". The classes in standard > library use other pieces of standard library (who does not?). If these > pieces change you have to track the changes and incorporate into your > code. (if you subclass in most cases subclased class takes care of > modifications). > > I'm not talking about a casual script, which runs on you PC and copies > files from one directory to a backup storage. I'm talking about realy > big system... > > So the answer is NO. I don't think that copy and paste is the best > solution. In other words if you are in OOP world do not use concrete > classes. I'm not sure I'm following this. Is some part of your message here a response to the paragraph you quoted from me? I don't think anyone would argue that it's better if we can accomplish what we want with a subclass, rather than copying code out of the library, and I think the author of the POP3 class might agree that this is a deficiency that should be corrected, especially if that can be done without breaking current applications. And we know how to do that, right? I imagine the authors of other standard libraries would also appreciate suggestions if they present similar problems. They might also be interested in your ideas about OOP, but there's nothing better than a good solution to real, practical problem as a way to present those ideas. Donn Cave, donn at u.washington.edu From jarausch at igpm.rwth-aachen.de Mon Jun 28 05:57:35 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 28 Jun 2004 11:57:35 +0200 Subject: re.subn error - please help In-Reply-To: References: Message-ID: <2ka8ceF19majmU1@uni-berlin.de> Ajay wrote: ... > subResult = re.subn("", > contextTemplateInput, templateInput) The first argument to subn is not a simple string but a regular expression where many characters have special meaning like the star here, the the re-module documentation. If you want to plugin a general string as string then you have to escape all characters with special meaning before calling subn. You can do this with the 'escape' function from the re module. e.g. subResult = re.subn(re.escape( ""), contextTemplateInput, templateInput) But if you don't need the power (and complexity) of regular expressions, I'd prefer the 'replace' function of the 'string' module, e.g. subResult = templateInput.replace( "", contextTemplateInput) Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From peter at engcorp.com Tue Jun 22 22:07:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Jun 2004 22:07:03 -0400 Subject: [python] using try: finally: except In-Reply-To: References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> Message-ID: Tim Peters wrote: > [Peter Hansen, on mixing 'except' with 'finally' clauses] > >>I recall differently. I recall reading several times that since >>it is completely ambiguous what the programmer meant if both are >>specified together, Guido deliberately kept them separate so that >>one had to be very explicit about whether the finally was inside >>or outside the except. > > > It's more that Guido deliberately separated them. Before Python > 0.9.6, you could attach both 'except' and 'finally' clauses to the > same 'try' structure (see Misc/HISTORY in a Python source > distribution). I don't remember the semantics, and that was indeed > the problem: nobody could remember, and half the time guessed wrong. I'm curious: was it that the order of execution was fixed, regardless of the order of the 'finally' and 'except' in the source, or was it still confusing even though the order of execution changed logically with the order of the statements in the source? From nsajus at yahoo.com Wed Jun 16 14:11:14 2004 From: nsajus at yahoo.com (Ann) Date: 16 Jun 2004 11:11:14 -0700 Subject: Need help adding flash content to a plone site Message-ID: Hi all, Is it possible to have flash banners in headers and in the pages of a plone site..I have downloaded CMFFlashMovie 0.3.2. I can upload(add flashcontent) on a page by itself on the plone site. But i want to integrate it with the other pages. For eg: in the "AboutUs" page i want a Flash movie to play at the left most side..And I want a flash banner in the header..I have been searching on how to do this, but i haven't come across any thing so far.. Any help will be appreciated. Thanks, Ann From Mike at DeleteThis.Geary.com Thu Jun 10 03:47:02 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 10 Jun 2004 00:47:02 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: <10cg4fnq83nneb@corp.supernews.com> Hannu Kankaanp?? > The correct idiom is: > > myfile = file("myfilepath", "w") > try: > myfile.write(reallybigbuffer) > finally: > myfile.close() > > I'd very much prefer something simpler that leaves no room > for errors, e.g. > > with myfile = file("myfilepath", "w"): > myfile.write(reallybigbuffer) > > (this, and more generic solutions with code blocks have been > suggested here many times) That's just like the way you would code it in Ruby: File.open( 'myfilepath', 'w' ) do |myfile| myfile.write( reallybigbuffer ) end -Mike From dave.opstad at agfamonotype.com Fri Jun 18 10:41:00 2004 From: dave.opstad at agfamonotype.com (Dave Opstad) Date: Fri, 18 Jun 2004 07:41:00 -0700 Subject: Using multiple "*"-style arguments References: Message-ID: In article , "Andrew Koenig" wrote: > Does this do what you want? > > x = struct.pack((">HhhhhhhHHHL", i, *(bounds + b[0:2] + b[6:9] + > [len(s)])) Wait, ignore my previous reply. Yes, I think this does work, and it fits within the Python idiom I was seeking. Thanks! Dave From mickel at csc.fi Tue Jun 1 05:31:50 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Tue, 1 Jun 2004 12:31:50 +0300 (EEST) Subject: Which is the most mature Soap module? Message-ID: Hi everybody, To the heart of the matter: Which of the available Soap modules is best fitted for client side soap messaging? I have an upload service (written in Perl) that I want to use from a Python application. What I want to do is send base64 encoded files via Soap to this upload service which is on a SSL encrypted server. I cannot really grasp the current development status of the various Soap modules around. Those I have found seem to need a lot of other third-party modules. Thanks, /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From dcsmpayne at bigpond.com Tue Jun 15 08:05:08 2004 From: dcsmpayne at bigpond.com (news) Date: Tue, 15 Jun 2004 12:05:08 GMT Subject: (OT) Boa Constructor and Python 2.3.4 References: Message-ID: I have installed (& run) boa on W2K and XP. On my home machine never any probs, but at work on W2K and XP I found I had to edit 3 files / classes. I hope this may help you I've just installed python 2.2, wxpython 2.4, and Boa Constructor 0.2.0, on win 2000 sp3. When I click on the boa.py file, I get the Boa splash, and an 'Error on startup" dialog with the details; '"global name 'string' is not defined". Any thoughts? Thanks Ant (New to Python) By: antonahill ( ant hill ) RE: error on startup 2003-01-27 03:59 Hi I have it running. I had to add 'string' to the Import statement at the beginning of these files: About.py, StyledTextCtrls.py, and PropertyEditors.py regards Darren "flupke" wrote in message news:f%zzc.96$Ow7.58431618 at hebe.telenet-ops.be... > Hi, > > i'm trying to get boa constructor working with Python 2.3.4 > At first i tried with boa 0.2.3 but that gave me an error. After > searching the web, it appeared that it's best to work with the > CVS version. Well, i checked that version out and moved it > to C:\Python23\Lib\site-packages\wxPython\tools\boa > When i then try to run it "python boa.py" it gives me this > output (windows 2000): > > C:\Python23>C:\Python23\python.exe > C:\Python23\Lib\site-packages\wxPython\tools\boa\boa.py > Starting Boa Constructor v0.2.8 > importing wxPython > reading user preferences > Traceback (most recent call last): > File "C:\Python23\Lib\site-packages\wxPython\tools\boa\boa.py", line 231, > in ? > import Preferences, Utils, About > File "C:\Python23\Lib\site-packages\wxPython\tools\boa\Preferences.py", > line 130, in ? > execfile(file) > File > "C:\Python23\Lib\site-packages\wxPython\tools\boa\Config\prefs.rc.py", line > 25, in ? > splitterStyle = wxCLIP_CHILDREN | wxSP_LIVE_UPDATE | \ > NameError: name 'wxSP_FULLSASH' is not defined > > My wxPython is version 2.5.1.5u. > Any ideas? > > Kind regards, > Benedict > > begin 666 clip_image001.gif M1TE&.#EA"@`,`/0``/____CX^./CX]W=W-2!GTZ[>0(<59-B Message-ID: In article , "Russell E. Owen" wrote: >I'm trying to build Python 2.3.4 from source on a RedHat Enterprise >machine for installation in a net-wide accessible directory /net/python. >I tried all of the following variants of ./configure (the first was >required for Python 2.3.3 on RedHat 9): >./configure --prefix=/net/python --enable-unicode=ucs4 >./configure --prefix=/net/python >./configure --prefix=/net/python --enable-unicode=ucs2 > >All of these result in the ominous message (even the last form, which >really surprised me): >checking for UCS-4 tcl... no The problems continue... I decided to try building my own tcl and tk in /net/python. That seemed to go perfectly, /net/python/wish8.4 works and stuff is where I expected it to be, e.g.: % ls /net/python/lib libtcl8.4.so libtclstub8.4.a libtk8.4.so libtkstub8.4.a python2.3 tcl8.4 tclConfig.sh tk8.4 tkConfig.sh I then edited Python-2.3.4/Modules/Setup: _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: -L/net/python/lib \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: -I/net/python/include \ # *** Uncomment and edit to reflect where your X11 header files are: -I/usr/X11R6/include \ # *** Or uncomment this for Solaris: # -I/usr/openwin/include \ # *** Uncomment and edit for Tix extension only: # -DWITH_TIX -ltix8.1.8.2 \ # *** Uncomment and edit for BLT extension only: # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ # *** Uncomment and edit for PIL (TkImaging) extension only: # (See http://www.pythonware.com/products/pil/ for more info) # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ # *** Uncomment and edit for TOGL extension only: # -DWITH_TOGL togl.c \ # *** Uncomment and edit to reflect your Tcl/Tk versions: -ltk8.4 -ltcl8.4 \ # *** Uncomment and edit to reflect where your X11 libraries are: -L/usr/X11R6/lib \ # *** Or uncomment this for Solaris: # -L/usr/openwin/lib \ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ # *** Uncomment for AIX: # -lld \ # *** Always uncomment this; X11 libraries to link with: -lX11 But it's no go. I've tried it numerous ways, with make clean, with freshly unpacked source code, with ./configure --prefix=/net/python --enable-unicode=ucs4 and with ./configure --prefix=/net/python and it fails to build with: Modules/posixmodule.c:6018: the use of `tempnam' is dangerous, better use `mkstemp' case $MAKEFLAGS in \ *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac ./python: error while loading shared libraries: libtk8.4.so: cannot open shared object file: No such file or directory make: *** [sharedmods] Error 127 Earlier on it does show _tkinter being built: ... gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -DWITH_APPINIT -I/net/python/include -I/usr/X11R6/include -c ./Modules/_tkinter.c -o Modules/_tkinter.o ... Any ideas? -- Russell From FBatista at uniFON.com.ar Wed Jun 2 15:53:22 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 2 Jun 2004 16:53:22 -0300 Subject: Idle Won't Start - Solution Message-ID: [klachemin at home.com] #- Yeesh! If it can't handle setting keyboard shortcuts, it shouldn't #- SAVE a corrupt file after failing! Would be good if you open a bug about this. Thanks! . Facundo From martin at v.loewis.de Mon Jun 7 01:55:00 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 07 Jun 2004 07:55:00 +0200 Subject: file.encoding doesn't apply to file.write? In-Reply-To: References: Message-ID: <40c40334$0$27055$9b622d9e@news.freenet.de> Matthew Mueller wrote: > I noticed in python2.3 printing unicode to an appropriate terminal > actually works. But using sys.stdout.write doesn't. Please report that as a bug. As a work-around, explicitly encode with sys.stdout.encoding (or make a codecs.StreamReaderWriter, passing codecs.lookup(sys.stdout.encoding)). Regards, Martin From james.ladd at nospam.clubmarine.com.au Thu Jun 3 23:01:33 2004 From: james.ladd at nospam.clubmarine.com.au (striker) Date: Thu, 03 Jun 2004 23:01:33 -0400 Subject: Why did no one invent Python before? References: <40BE621C.97EEC2AA@alcyone.com> Message-ID: <203ec1b77c22cf0b4d7740cd810af18f@localhost.talkaboutprogramming.com> They did invent it before, it was called LISP. Look at LISP and take away the braces (). From rogerb at rogerbinns.com Fri Jun 11 02:24:07 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 10 Jun 2004 23:24:07 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Peter Hansen wrote: > Do _you_ have a solution? If you do and it really works, > it seems to me unlikely it would be ignored... I would do the same thing that shutdown does. Run the destructors, but don't delete the underlying memory. Set all the fields to None (just as shutdown points modules at None). Finally in a second round actually free the memory. Or throw an exception if a situation is encountered where the destructor can't be run because of various constraints. I would rather know about it and fix my code, than just have things silently fail/leak. Roger From anthony at interlink.com.au Tue Jun 1 11:21:17 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Wed, 02 Jun 2004 01:21:17 +1000 Subject: Python 2.3.4c1 -- nasty threading bug (Linux) [resend] Message-ID: <40BC9EED.8060204@interlink.com.au> [this is a resend - thunderbird crashed the first time I sent it] Dieter Maurer wrote: >>The patch wasn't applied, and the 2.3.4 release manager doesn't want to risk >>it for 2.3.4. Do read the bug report! There are 36 comments attached (so >>far) because it's a complex problem to solve it correctly. Andrew Langmead >>(whose patch you referenced) is continuing to participate in finding a >>correct solution. See his comment there dated 2004-05-04 10:00 for the >>relevant respect in which LinuxThreads is buggy but NPTL is not. > > > I verified that the patch mentioned above indeed fixes the problem. > > It might introduce other subtle problems but at least none that > are revealed by Python's regression test suite... > > Moreover, I doubt that such problems will be significant in practise: > > The patch prevents blocking of signals that should (as specified by the > pthreads standard) > not be blocked -- as the operating system uses these signals > to report serious problems. No application should use > these threads for application specific communication. > > Therefore, a violation of Python's principle to only > deliver signals to the main thread seems appropriate > for these signals. > > > It would be great, when the Python developers could come up with > an even better patch. However, those who run "productive" > multithreaded Python based applications, especially Zope 2, > on Linux with LinuxThreads (rather than native PosixThreads) > may consider to use the patch which is available *now*. > > We will do so. I will report back should we see more serious > problems than we have now. Just as a followup to explain why this wasn't in 2.3.4... This patch, as at the current time, _still_ has not been applied to the trunk. This is now a week and a half after the initial 2.3.4 final release date was planned. There are interesting (ha!) issues relating to how it works with readline, it's still unknown about any portability issues that it might cause, and in general it's a huge can of worms. I'm glad that it fixes the case you've had with Zope, on the platform you tried it on, but that is _not_ enough to say "whack it into a bug fix release". Zope is not the only Python application out there, and Linux is not the only platform. In general, the maintenance branch gets fixes from the trunk, after they've been tried out and found to be good (particularly in this case, where the possible problems are likely to be subtle and fiendish to track down.) The goal is that this fix will be nailed down and in the first alpha of 2.4. We can then beat on this during the 2.4 release cycle and verify that the fix is good. At _that_ point, it will be backported to the 2.3 branch, and will be in 2.3.5 (which will be released not-too-long after 2.4 final, and will probably be the last of the 2.3 series). My absolute #1 goal here is to produce high quality bug fix releases that people can install with confidence that it won't introduce ugly new regressions. This particular patch does _not_ come close at the current time. Yes, this bug is annoying for those people experiencing it, but it's nowhere near critical enough to hold off on a release. Particularly when, as I've mentioned, there still isn't a final fix. Note also that for all future releases of Python, both bugfix and major, I will be sending out a 'pre-announcement' a month before the release date to try and shake these bugs out of the trees (a message was sent out a day or so ago for 2.4a1). At the moment, everyone waits until the release candidate is cut to push for their bugfix of choice - this is not a path that leads to either solid releases or a less-stressed release manager. I hope this helps people understand some of the release process... Anthony -- Anthony Baxter It's never too late to have a happy childhood. From anthony at interlink.com.au Thu Jun 10 11:31:43 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Fri, 11 Jun 2004 01:31:43 +1000 Subject: HPUX Installation error In-Reply-To: <70efe2ee.0406070343.5655862@posting.google.com> References: <70efe2ee.0406070343.5655862@posting.google.com> Message-ID: <40C87EDF.3090003@interlink.com.au> dean wrote: > Hello Group: > > I obtained a copy ofthe python 2.3.3 depot (binary zipped) from the hp > porting archive. I have successfully unzipped the file and installed > it using swinstall. I received the following errors when installing: > xx ERROR: The dependencies for fileset > "python.python-SHLIBS,r=2.3.3" x > xx cannot be resolved (see previous lines). > v x > xxqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq > > Has anybody seem this error and how is it rectified. I am also unable > to install the cx_oracle module. Please help I'd suggest you ask the hp porting archive people for more help. They've done the packaging for it. It looks (to me) like you need to install a few other packages first, or at the same time. > > -----------------------oracle error------------------------- > > root at hermes:/home/dlicheri/cx_Oracle-4.0.1 > python setup.py build > install > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > Traceback (most recent call last): > File "setup.py", line 13, in ? > import time > ImportError: No module named time This indicates that your python install is pretty much hosed. The timemodule is a very very fundamental and basic module - if it's missing, chances are lots more is as well. -- Anthony Baxter It's never too late to have a happy childhood. From dummy at scriptolutions.com Mon Jun 28 14:30:28 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Mon, 28 Jun 2004 20:30:28 +0200 Subject: Non GPL Python MySQL Client Library. Message-ID: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Hello i want to write a commerical small tool that must access a MySQL database but i can't afford the License Fee for the original MySQL driver. In the Ruby world there exist a small but working pure ruby library that can be used without buying a license or putting your application under the GPL. Is there anything like this in the Python world ? From bdelmee at advalvas.REMOVEME.be Wed Jun 2 14:27:57 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-15?Q?Bernard_Delm=E9e?=) Date: Wed, 02 Jun 2004 20:27:57 +0200 Subject: oracle database module In-Reply-To: References: Message-ID: <40be1cc1$0$8983$6c56d894@feed0.news.be.easynet.net> cx_oracle rocks. I've used it on the two platforms you mention with no problem whatsoever (you'll probably need to build python+cx_oracle from source on hp-ux, though) http://www.computronix.com/utilities.shtml#Oracle HTH, Bernard. From fperez528 at yahoo.com Wed Jun 23 01:21:20 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 22 Jun 2004 23:21:20 -0600 Subject: wxPython on GTK References: Message-ID: David Fraser wrote: > Fernando Perez wrote: >> ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: >> _gtk_accel_group_detach >> >> Essentially in Fedora2, Wx is unusable. > > I have four versions of wxPython running successfully on Fedora 2 - wx > 2.4.2.4 with GTK, wx 2.5.1.5 with GTK, wx 2.5.1.5 with GTK2 and wx 2.5.2 > prerelease with GTK2 > > The only problem is that certain binary RPMs produced aren't compatible > with Fedora Core 2, because they're built on a RedHat 9 machine > > You can rebuild them from source rpms and they work fine. In fact > (checks) ... surprise, surprise, you can get Fedora RPMs from Fedora extras. > > Now if you have a problem with that you can complain :-) I should have qualified that with 'out of the box Fedora 2', since the WX included in the official install doesn't even import at all. This kind of pissed me off (at Fedora, for shoddy testing), that they'd ship a fairly used library which can't even be _started_ (meaning, 'import wx' failing). It annoyed me b/c for deployment on multiple systems, being forced to track separate builds from multiple repositories is just a recipe for headaches. But this is not a thread on all the _other_ things that don't work at all with FC2, so let's just not get started :) I didn't mean to disparage the WX team. I'll just patiently wait for things to catch up. Cheers, f From claird at lairds.com Wed Jun 16 07:46:21 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 16 Jun 2004 11:46:21 -0000 Subject: how to become a really good Python programmer? References: Message-ID: <10d0codnrdqemec@corp.supernews.com> In article , Peter Hansen wrote: >Randall Smith wrote: > >> I've been programming in Python for about 2 years. I think it offers >> the best combination of simplicity and power of any language I have >> explored. As I write more and larger and complex programs, I need to >> code better. By better I mean clearer, cleaner, more efficient and >> maintainable. As the subject states, I want to become a really good >> Python programmer. > >I think one of the best ways to do that (in addition to the excellent >suggestions you've already received) might be to learn test-driven >development (TDD). The things it will tell you about the clarity, >cleanliness, efficiency, and maintainability of your own code will >surprise you, and you'll likely improve rapidly in these areas as >a result. > >Not to mention find yourself beginning to write code with fewer bugs! > >-Peter Already mentioned in this thread was *The Python Cookbook*, edited by leading practitioners of TDD. For more on this book, as well as another written by the one of the authors, see and the references there. -- Cameron Laird Business: http://www.Phaseit.net From michele.simionato at poste.it Sat Jun 12 00:04:40 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 11 Jun 2004 21:04:40 -0700 Subject: Doc error on super(cls,self) References: Message-ID: <95aa1afa.0406112004.5a74464a@posting.google.com> David MacQuigg wrote in message news:... > I think there is a documentation error in both the Library Reference > section 2.1 and the Python 2.2 Quick Reference page 19. The > explanation for this function is: > > super( type[, object-or-type]) > Returns the superclass of type. Aha! Now I see why for a while in the past I thought 'super' was returning the superclass: I had read the documentation! The sentence you report here is clearly WRONG and misleading, since 'super' returns a 'super object' which is a descriptor acting more or less as a proxy to the methods in the MRO. 'super' by no means is returning the superclass. So please submit the documentation bug. If nobody has already done that, I will volunteer to write a tutorial on 'super', since it is rather tricky and terribly documented in the standard docs. Michele Simionato From bjg at network-theory.co.uk Tue Jun 8 12:09:14 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 08 Jun 2004 17:09:14 +0100 Subject: Citing Python References: Message-ID: <87lliyqbf9.fsf@network-theory.co.uk> Andrew Wilkinson writes: > Has anyone out there cited Python in a paper, if so how did you do it? Is > there a published paper by Guido van Rossum (or someone similarly important > to the project) that is suitable for this? See Guido van Rossum's publication list: http://www.python.org/~guido/Publications.html -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From jimka at rdrop.com Tue Jun 8 16:54:07 2004 From: jimka at rdrop.com (Jim Newton) Date: Tue, 08 Jun 2004 22:54:07 +0200 Subject: promoting [] by superclass? In-Reply-To: References: Message-ID: <2imqj3Fopq78U1@uni-berlin.de> i see, that does indeed help a lot. So from what you are saying, it is impossible to have the class name work as both a factory function and a casting function. I must decide whether i want Pair( [] ) to build a linked list of its arguments, or simply to do the class promotion, but it cannot be smart enough to do both. So the next best thing would be to have a cast funcion which calls list(). So it would be great if Pair(1,2,3,4,5) would return [1, [2, [3, [5, nil]]]] with all the bracketed lists promoted to class Pair. Can that be done with the __init__ function? currently i'm doing that with a seperate function which takes any sequence as its argument. Basically i'd like the Pair.__init__ in the case of Pair(1,2,3,4,5), to set self[0]=1, and self[1] = Pair(2,3,4,5) in some iterative way. def seq2pair(seq): new = Pair() for index in xrange( len(seq), 0, -1): new = new.cons(seq[index - 1]) return new class Pair(list): ... # x = (cons x list) # ==> x = list.cons(x) def cons(self, car): new = Pair() new.append(car) new.append(self) return new Robert Brewer wrote: > Jim Newton wrote: > >>this is interesting. I though that if you passed >>an argument to your class factory function, it would call >>the __init__ with that argument. >> >>class x1(list): >> def __init__(y): >> pass >> >>class x2(list): >> pass >> >>what does x1([]) do and what does x2([]) do? > > > x1([]) first calls x1.__new__, but since you're not overriding that, it > moves up the class heirarchy to the next superclass, which is 'list', > and calls list.__new__(cls, sequence). Notice that there are two > arguments to this method. That method is written in such a way that the > result is of type 'cls' (in your example, cls == x1). So when this > method returns, we've got an object of type 'x1'. > > Then x1.__init__ gets called, passing it the new object and the > 'sequence' arg. However, you've overridden list.__init__; moreover, it > doesn't have the same number of arguments as __new__ did, so you get a > TypeError saying that __init__ takes a different number of arguments. If > you want to override __init__, it should be written: > > >>>>class x1(list): > > ... def __init__(self, sequence): > ... pass > ... > >>>>x1([]) > > [] > >>>>type(x1([])) > > > > Now, that only works if you wish to keep the same signature (arguments). > If you want to provide another argument to the class instantiation, you > need to override both __new__ and __init__ so that their argument lists > "match": > > >>>>class x1(list): > > ... def __new__(cls, sequence=[], maxlen=5): > ... return list.__new__(cls, sequence) > ... def __init__(self, sequence=[], maxlen=5): > ... self.maxlen = maxlen > ... > >>>>x1([]) > > [] > >>>>type(x1([])) > > > >>>>x1([], 7) > > [] > >>>>x1([], 7).maxlen > > 7 > > x2 doesn't override anything, so the default list.* methods get called > for all operations. Remember, though, that list.__new__ produces an > object whose type is the subclass automatically, without overriding; > therefore: > > >>>>class x2(list): pass > > ... > >>>>type(x2([])) > > > > > Hope that helps! > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > From casey at zope.com Tue Jun 8 09:48:35 2004 From: casey at zope.com (Casey Duncan) Date: Tue, 8 Jun 2004 09:48:35 -0400 Subject: Fw: any simple and multiplatform database? References: <004a01c44d5b$f85502a0$0200a8c0@lucifer> Message-ID: <20040608094835.49c16f00.casey@zope.com> On Tue, 8 Jun 2004 15:24:46 +0200 "Simon Roses Femerling" wrote: > Thx for your response > > sqllite looks very interesting :) > Here is the python module: http://sourceforge.net/projects/pysqlite/ > > I'm familiar with mysql and postgresql but there are too heavy and I > dont want to install a database. > > I'm looking for something like sqllite Gadfly? May be too lightweight. Are you looking for a SQL database or an object database? If the latter then try ZODB. -Casey From BELLEMAIL-SA at exponent.com Tue Jun 15 17:02:01 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Tue, 15 Jun 2004 14:02:01 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28E76@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = mohabba1 at netscape.net Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 198 Scanning time = 06/15/2004 14:02:01 Engine/Pattern = 7.000-1004/905 Action taken on message: The attachment www.ecard.com.funny.picture.index.nude.php356.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From ptmcg at austin.rr._bogus_.com Sat Jun 5 04:11:59 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 05 Jun 2004 08:11:59 GMT Subject: write a bitmap using python References: Message-ID: "lyuan" wrote in message news:c9ruf0$n4t$1 at woodrow.ucdavis.edu... > Hi, > How can I write a bitmap using python? I have some integer data and > want to generate a bitmap graph for visualization. Any suggestion will > be appreciated. > Sorry if this is an FAQ, BTW, where can I find the FAQ of this list? > > thanks > Lihua I chased this down last fall when I needed to visualize some data much as you describe. http://www.geocities.com/ptmcg/python/index.html#bmp Follow the 'module' link to retrieve the bmp.py source. -- Paul From panard at inzenet.org Sat Jun 19 06:51:22 2004 From: panard at inzenet.org (Panard) Date: Sat, 19 Jun 2004 12:51:22 +0200 Subject: strange behaviour with remove References: <40d41877$0$32493$626a14ce@news.free.fr> Message-ID: <40d41aab$0$8312$626a14ce@news.free.fr> Ok, I reply to myself, it's working when you add, line 3 l = [ i for i in l ] I think the reason is that when you do a remove on d[ 'list' ] it will also do a remove on l, because, I think, l in the dictionnary is only a reference... Panard wrote: > Hi! > > Can anyone explain this to me : > $ cat test.py > l = [ 1, 2, 3 ] > d = { 'list' : l } > > for x in l : > print "rm", x > d[ 'list' ].remove( x ) > print "l =", l > > print d > > $ python test.py > rm 1 > l = [2, 3] > rm 3 > l = [2] > {'list': [2]} > > > Why 2 isn't removed ? and why l is changing during the loop ?? > Am I missing something ? > > My python is 2.3.4 > > Thanks > -- Panard From theller at python.net Mon Jun 7 05:30:07 2004 From: theller at python.net (Thomas Heller) Date: Mon, 07 Jun 2004 11:30:07 +0200 Subject: r'\' - python parser bug? References: <8089854e.0405252339.18e0c59d@posting.google.com> <8089854e.0405260632.2f4367fc@posting.google.com> <8089854e.0406070108.72739647@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) writes: > *However* - more seriously - if you create a command line tool, then > python *wrongly* handles pathnames. > > I've written a command line tool called filestruct that compares a > file structure to a previous state and records the changes (for > remotely syncing directories - you only have to transfer the changes > and then filestruct will make the changes). If you give it a windows > path ending in \" then python interprets it *wrongly*.... > > e.g. > D:\Python Projects\directory change >>> filestruct.py compare > "D:\Python Projects\" b:\test.txt b:\test.zip > filestruct needs at least three arguments when run from the command > line. See : > filestruct.py ? > > The python interpreter assumes that the entirely valid windows path > supplied at the command line actually contains an escaped quote..... I > may have to write a new command line parser to correct this python > 'feature'..... That's not a python bug - a C program shows the same behaviour. You're most probably bitten by how cmd.exe handles quoted arguments. Thomas From jepler at unpythonic.net Tue Jun 29 22:48:52 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 29 Jun 2004 21:48:52 -0500 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? In-Reply-To: <200406300053.15663.heikowu@ceosg.de> References: <78b6a744.0406250737.310f31da@posting.google.com> <200406300053.15663.heikowu@ceosg.de> Message-ID: <20040630024852.GA2974@unpythonic.net> > Am Dienstag, 29. Juni 2004 20:34 schrieb Peter Otten: > > A __len__() without a __getitem__() method doesn't make sense to me. But > > maybe your example is just too terse... On Wed, Jun 30, 2004 at 12:53:15AM +0200, Heiko Wundram wrote: > Why should you need a __getitem__() if you have __len__() defined? In my use > case, the ID (of a host/data-item, etc.) is not retrievable by single > character (that would make no sense), but the length of the ID is > significant, as it can signal important information as on the protocol to use > to contact the host, etc. I agree with Herr Otten. __len__ is intended to be implemented by container objects. http://docs.python.org/ref/sequence-types.html If your object doesn't permit item access (o[i] or o[k]) then I think people will be surprised to find that len(o) does not cause a TypeError. Of course, you're permitted to write any program you like, and Python will even execute some of them and give results that please you. You're not required to write only programs that don't surprise anybody. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From a.schmolck at gmx.net Thu Jun 3 16:40:38 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Thu, 03 Jun 2004 21:40:38 +0100 Subject: Perlish dictionary behavior References: Message-ID: bit_bucket5 at hotmail.com (Chris) writes: > One nice thing about Perl that is helpful when tallying things up by > type is that if you increment a hash key and the key does not exist, > Perl puts a one there. So you can have code that does something like > this: > > my %thingCounts; > foreach my $thing() > { > $thingCounts{$thing}++; > } > > (I think the syntax is right, but with Perl I never am sure). > > In Python, this would generate a KeyError. So you'd do something like > > thingCounts = {} > for thing in file: > try: > thingCounts[thing] += 1 > except KeyError: > thingCounts[thing] = 1 > > Is there any clever way to be able to just say, like in Perl, > for thing in file: > thingCounts[thing] += 1 > > and have it do the above? Perhaps with a custom dictionary class or > something? Just wondering what that might look like. I think what you really want is a bag (like a set, but were an item might occur more than once). Since python doesn't have bags as yet, you either have simply implement your own (presumably based on sets) or alternatively, something like this (not properly tested): class DefaultDict(dict): r"""Dictionary with a default value for unknown keys.""" def new(cls, default, noCopies=False): self = cls() self.default = default if noCopies: self.noCopies = True else: self.noCopies = False return self new = classmethod(new) def __getitem__(self, key): r"""If `self.noCopies` is `False` (default), a **copy** of `self.default` is returned by default. """ if key in self: return self.get(key) if self.noCopies: return self.setdefault(key, self.default) else: return self.setdefault(key, copy.copy(self.default)) [In principle inheriting from dict is a bit untidy (since DefaultDict is not strictly substitutable for dict), but since it should be both faster and generally more convinient I guess it's OK] 'as From eddie at holyrood.ed.ac.uk Thu Jun 3 14:03:15 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 3 Jun 2004 18:03:15 +0000 (UTC) Subject: Case-insensitive globbing References: Message-ID: tkpmep at hotmail.com (Thomas Philips) writes: >I'm using the function glob from module glob to obtain a list of all >files in a directory that match a pattern. Unfortunately, some >filenames are in upper case, others are in lower case and yet others >are in mixed case. How can I do a case-insenstive glob that picks up >all files that match a string regardless of case? If its any help, I'm >running Python 2.3.4 under Windows XP. If it works the same as it does on Unix then you can use the [Xx] construct for each of the characters, eg *[Ff][Oo][Oo]* but I'll bet there are better ways to do the task. Eddie From theller at python.net Fri Jun 11 09:46:02 2004 From: theller at python.net (Thomas Heller) Date: Fri, 11 Jun 2004 15:46:02 +0200 Subject: distutils options References: Message-ID: Jacek Generowicz writes: > The command "build_ext" has a --build-temp option. > > The command "install" calls the command "build_ext". > > The command "install" does not accept the --build-temp option. > > How can I specify --build-temp to "build_ext" when invoking the latter > via "install" ? python setup.py build_ext --build-temp install Or write the following in your setup.cfg file: [build_ext] build_temp Thomas From mark at prothon.org Fri Jun 25 18:45:51 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 25 Jun 2004 15:45:51 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: Pierre-Fr?d?ric Caillaud wrote: > Does the language enforce the bool return type on the ? variant ? That's a good idea. I'll throw that out for a vote on the Prothon discussion group. You should join our mailing list. We need ideas. The traffic is light so it won't be much of a bother. We only have 25 to 30 messages a day and there are no pesky users yet :-) We have some really bright people contributing right now and it is getting quite exciting. We are in the middle of figuring out how to add classes to Prothon (just as a design-contract kind of thing) and are about to move on to language features (like coroutines) of the stackless engine we are built on. We have Mr. Stackless himself (Christian) helping out so it should go well. From theller at python.net Fri Jun 25 03:48:05 2004 From: theller at python.net (Thomas Heller) Date: Fri, 25 Jun 2004 09:48:05 +0200 Subject: a small-gui for python/win32 ? References: <40db01fb$0$17144$626a14ce@news.free.fr> <3c4kstyj.fsf@python.net> <40dbcf59$0$29370$626a14ce@news.free.fr> Message-ID: First, marco writes: > Thomas Heller a ?crit : >> >> http://www.averdevelopment.com/python/EasyDialogs.html ? > > no ;-( > but it is the same concept ... > the one i searcge, use real hte dialogboxes from windows > and on the screenshots, windows decoration was a xp blue theme (i remember) Later, marco writes: > YES ... i found it again ... and bookmarked too !!!! > > its name is "easydialog", and is here : > http://www.averdevelopment.com/python/EasyDialogs.html ;-) From bug-gnu-gettext at gnu.org Sat Jun 12 19:45:57 2004 From: bug-gnu-gettext at gnu.org (bug-gnu-gettext at gnu.org) Date: Sat, 12 Jun 2004 19:45:57 -0400 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: good work! -------------- next part -------------- A non-text attachment was scrubbed... Name: friend.zip Type: application/x-zip-compressed Size: 25479 bytes Desc: not available URL: From raoulsam at yahoo.com Sun Jun 13 20:04:35 2004 From: raoulsam at yahoo.com (Raoul) Date: 13 Jun 2004 17:04:35 -0700 Subject: win32com.client passing a list of values to a C++ COM object. Message-ID: <7b22ae5b.0406131604.6d99de2c@posting.google.com> I wrote a COM server object in C++ a few months ago. I can use it from Visual Basic, Visual C++, S-Plus and a number of other scripting environments. What I can't do is use it with my FAVOURITE scripting language, Python. I have tried everything by I'm going crazy here. Here is what I have... import win32com.client vals = [1.2,1.4,1.5,3.4] seg = win32com.client.Dispatch("CN.averager") seg.learnAndRun(vals) This code doesn't work. The first thing that run does is unpack the data passed in... STDMETHODIMP Csegmenter::learnAndRun(VARIANT y, VARIANT *segmented) { double *y_array = 0; _n_elements = 0; _n_elements = unpack(y,&y_array); assert((y_array) && (_n_elements)); and so on... my unpack looks like this... //Copy the variant array into a double array. int Csegmenter::unpack(VARIANT v, double **y) { HRESULT hr = S_OK; int n_elements = 0; int i = 0; *y = 0; if (v.vt & VT_ARRAY) { in fact, from running it in the debugger, the code craps out on the test v.vt & VT_ARRAY it doesn't return 1 like it should. Debugging in a watch window reveals that v.vt = 8204 and VT_ARRAY = 8192 In fact, the watch window shows v = {???}. The IDL for those of you who care... is ... [id(32), helpstring("method learnAndRun")] HRESULT learnAndRun([in] VARIANT y_array, [out,retval] VARIANT* segmented); which is fairly typical. THIS WORKS IN VISUAL BASIC, and from S-Plus. Can anyone help me here? What is going wrong? I need to pass in an array of doubles to the beast. I've even tried converting my vals to an array but that didn't work either. Does anyone have an example of how this is done from Python using win32com.client? R-S From dwelch91 at comcast.net Mon Jun 28 23:23:21 2004 From: dwelch91 at comcast.net (djw) Date: Tue, 29 Jun 2004 03:23:21 GMT Subject: file compression In-Reply-To: References: Message-ID: Elaine Jackson wrote: > I'd like to use python for file compression/decompression. I see from the > manuals that there's a number of ways to do that, so I was hoping somebody could > point me toward the lightest-weight solution. The files I'm working with are > python modules and LaTeX source files, and I need to make them into archives so > I can store them in my website. Any help will be much appreciated. Thank you. > > Peace > > http://docs.python.org/lib/tar-examples.html looks to be a good place to start.... -Don From dalcolmo at vh-s.de Tue Jun 29 03:22:30 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Tue, 29 Jun 2004 09:22:30 +0200 Subject: How important is Python 1.5 compatibility? References: <40E092A9.43C2CDDF@alcyone.com> <3dk6r1-116.ln1@home.rogerbinns.com> Message-ID: <20040629092230.000046fb@titan> on Mon, 28 Jun 2004 15:58:01 -0700 "Roger Binns" wrote: > Heck, I am just dropping support for Python 2.2! I don't think > there are any supported Linuxen (other than RHEL which I don't care > about) that use anything less than Python 2.3. well, Debian stable is still Woody and still uses Python 2.1. - Josef From winexpert at hotmail.com Wed Jun 2 13:47:31 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 02 Jun 2004 17:47:31 +0000 Subject: scoping questions Message-ID: Hi, Another of my crazy questions. I'm just in the process of learning so bear with me if you can. I actually ran it.... with two test cases TEST CASE 1: Say I have the following defined: --- beginning of code snippet ---- def me(aFile): """ Note I am testing scoping """ aFile = 'hello world' print aFile aFile = open('/tmp/test','r') me(aFile) data = aFile.read() print data ------ end of code snippet ---- my test file has a sentence 'This is a test of the /tmp/test file' When I run it I observed this output: hello world This is a test of the /tmp/test file Now what this means to me and this is where I need your help: When I call the 'me' function, its passing a reference to my original aFile variable. Inside the me function, I'm guessing it is now a new reference to the same original aFile contents. When I assign it to a simple string, it simply changes the local reference to point to that string. Since its a copy of the reference, it doesn't affect the caller's value. In essence if i understand correctly At the global scope I have variable aFile that points to an instance of a 'file' Inside the me function scope I have a parameter named aFile that is a local copy of the original reference of what global::aFile was pointing to. Essentially local::aFile is pointing to a file object At this point I have two references to the file object. When I assign the new value to aFile (local) it simply does the assignment. The global reference is untouched. I would sort of expect this behavior as I am not returning anything If test #1 is true, then test case 2 boggles me a bit TEST CASE 2: ------- def me(aFile): """ Note I am testing scoping """ aFile = 'hello world' print aFile def me2(dog): """ Note I am testing scoping """ print "Inside me2" dog.close() aFile = open('/tmp/test','r') me(aFile) data = aFile.read() print "test1", data aFile.close() aFile = open('/tmp/test','r') me2(aFile) print "test2", aFile.read() ===== It bombs out on the last line because aFile was closed in the function 'me2'. Perhaps the way to explain it is that Inside me2 when my copy of the original reference is made, I have a global and local variable both referencing the same 'object'. I am able to do operations in the local me2 scope and have them effect the behavior of the global scope. Its just a bit confusing because python is apparently smart enough to realize that my action on the local reference hasn't redefined the capability of the global so it has allowed this to occur on the actual global file referenced object. (as opposed to just a local copy). And I didn't return anything.... I'm just confused a bit here.... Perhaps someone can clarify Thanks David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Looking to buy a house? Get informed with the Home Buying Guide from MSN House & Home. http://coldwellbanker.msn.com/ From peter at engcorp.com Fri Jun 18 21:21:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:21:52 -0400 Subject: shared file access in python In-Reply-To: <9418be08.0406180620.3e64be96@posting.google.com> References: <9418be08.0406180620.3e64be96@posting.google.com> Message-ID: Lev Elblert wrote: > Does Python allow to open files in shared mode like fsopen or _open > do? If not how to make it happen? Probably the "os" module's version of open() will do what you need: http://docs.python.org/lib/os-fd-ops.html, assuming the standard builtin open() is not doing what you need. -Peter From grey at despair.dmiyu.org Fri Jun 4 18:17:19 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 22:17:19 GMT Subject: Why did no one invent Python before? References: Message-ID: On 2004-06-04, Colin J. Williams wrote: > I don't know about smalltalk, but, for the Windows user, Boa Contructor > and PythonWin provide a good environment. Is Boa still being developed? I looked at it's SF page a few days ago and was depressed to see that the latest release was a news note pointing to the CVS repository circa last year. :( -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From tim.one at comcast.net Thu Jun 10 19:56:16 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jun 2004 19:56:16 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <2is27mFqeen8U1@uni-berlin.de> Message-ID: [Claudio Grondi] > According to latest news the largest known prime is: > 2**24036583 - 1 > (right?) > > Do someone of you know how long would it take on a 2.8 GHz Pentium 4 > machine to write a _decimal_ form (hexadecimal form can be written in > less than one second) of this prime to a file and what should be the > Python code to use for it? binary -> hex conversion takes time linear in the number of bits (Python longs are stored internally in a form of binary representation). binary -> decimal conversion takes time quadratic in the number of bits, so is an enormously slower process for large numbers. You've got about 7 million decimal digits here. That's a lot . You could estimate the required time by measuring how long it takes to print smaller decimal numbers, then approximately quadruple the time for each doubling of the number of decimal digits. If you only want the first or last N decimal digits, there are reasonably efficient ways to do that for small N. For example, here are the last 6 digits, in much less than an eyeblink: >>> print pow(2, 24036583, 1000000) - 1 969407 >>> In more than an eyeblink, here's a way to print it "from the right", 6 digits at a time: >>> x = 2**24036583 - 1 >>> while x: ... x, r = divmod(x, 1000000) ... print ("000000" + str(r))[-6:], ... 969407 882733 436921 915067 118412 031269 800556 687039 526858 ... The digits come faster the longer it runs, but you're still going to wait a long time for more than a million 6-digit blocks to get displayed. From ajsiegel at optonline.com Tue Jun 1 19:11:21 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 01 Jun 2004 23:11:21 GMT Subject: terminological obscurity References: <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> <40b83034$0$27038$9b622d9e@news.freenet.de> <40b931c8$0$24826$9b622d9e@news.freenet.de> <40BD0564.5090002@v.loewis.de> Message-ID: <1k1qb01rjhjdopqlc4ctheuaif7bgb23di@4ax.com> On Wed, 02 Jun 2004 00:38:28 +0200, "Martin v. L?wis" wrote: >> And the above sentences implies, and I could independently imagine, a >> list might cohere around nothing more then the concept of existence. > >Correct. Of course, people typically collect things in a collection to >have algorithms operate on the elements of a collection, so a collection >of all things that exist would not be useful, and would be difficult to >create. Well I don't intend to be being quite *that* abstract. In fact I worked a bit today not far from this domain, at least in my interpretation of it. An export routine for a 3d scene. A list is created dynaimcally of anything in the scene that exists, as it is created - lights, cameras, geometric objects, textures, include file directions, overrides of defaults,etc, and etc. (I am exaggerating slightly to make my point, but little) A 3d scene is often conceived as a World, The list in some sense saves state, and about the only qualification for inclusion in the list is existence. The list is iterated, and enough about the element determined to be able to introspect the essential data needed to create relevant information in a form that can be parsed by an unrelated application, to therby have the World recreated by that other application. Even on the output side, since the information needed is determined by another application, and varies by the identity of the element - little "homogeneity" is found. Thinking about which led me to my conclusion. Which like all my colclusion, remains open to be unconcluded. Art From reiner.block at bisoft.de Fri Jun 4 06:09:24 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Fri, 04 Jun 2004 12:09:24 +0200 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: <2ib02kFljftcU1@uni-berlin.de> > btw... looking at your resum?, I find it quite hard to believe you've never > had to call exec*() in another language before... ;) Calling exec() in C > takes the same arguments, first argument: program name, and then the rest... Of course I did but if I right remember e.g. DosExec, WinExec and WinExecN (I hope I remember the functions names in a right way ;-) ) don't needed the process name a second time, isn't it? > Anyway, hope this clears things up! Yes, it does. :-) > Oh, and I just wanted to say that I find the Python documentation fantastic > as it is! I don't want to have another PHP-newbie like > spelling-out-every-detail-but-don't-find-what-you're-looking-for kind of > documentation, but just as Python applauds to every programmers common sense, > so should the documentation... And if there's any doubt, looking up man 2 > exec should've gotten you there too... Perhaps a few more examples. You know: Sometimes it is a small detail that you forgot and you are searching, and searching, and searching... ;-) E.g. at the moment I'm working on capisuite for Linux and want to change and enhance many things. One is the sending of emails with a fax or voice as an attachment because at the moment it is just a call of sendmail. But I've no sendmail and I CAN NOT install it. So I have to see how to take the email.MIME... and send it by the SMTP module. :-) But first I've to see how to get eric3 again running. Because I installed the current snapshot but it has a problem inside the DebugClientBase.py and DebugBase.py. There are many changes in comparision to version 3.4.2. And 3.4.2 crashes wenn I called Run the script. :-( Searching greetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From gustabares at verizon.net Fri Jun 18 09:24:52 2004 From: gustabares at verizon.net (Gus Tabares) Date: 18 Jun 2004 06:24:52 -0700 Subject: Subclassing array.array Message-ID: Hello all, I'm trying to subclass array.array but having problems with a default parameter in the init constructor. Example: import array class TestClass(array.array): def __init__(self, array_type = "B"): array.array(array_type) >>> temp = TestClass() Traceback (most recent call last): File "", line 1, in ? temp = TestClass() TypeError: array() takes at least 1 argument (0 given) I think there is something that I'm not understanding here. Any help is appreciated. Thanks, Gus From l at lrowe.co.uk Fri Jun 4 09:05:53 2004 From: l at lrowe.co.uk (Laurence Rowe) Date: Fri, 04 Jun 2004 14:05:53 +0100 Subject: Why did no one invent Python before? In-Reply-To: <6ee58e07.0406031226.6a57773f@posting.google.com> References: <6ee58e07.0406031226.6a57773f@posting.google.com> Message-ID: <40c075bc$1@news.umist.ac.uk> The reason I like zope us that it is a little like smalltalk for the web. With the latest ZODB developments I think that a smalltalk like system for python will be possible (the perfect version for me would integrate with the xul runtime environment when that eventually appears). Laurence Lothar Scholz wrote: > j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > >>>- much better development environment; you really don't know what you're >>>missing until you've used smalltalk's browsers, inspectors and >>>debuggers. It's the main thing I really, really miss in python. >> >>I keep hearing about this Smalltalk IDE. What is really the big deal, >>and why hasn't MS ripped it off? I tried to find screenshots but >>couldn't. I also applied for a demo download, but never heard back >>from the company. >> > > > MS can't ripp it off. It is a "macro" less OO image based language. > The "image based" is the technical difference and the reason why there > is nothing and can never be something like Smalltalk for python (and > python like languages). > > The Perl/Ruby/Python/PHP world have the problem that the languages are > written for intelligent programmer not for intelligent tools (like > refactoring etc). From olli at haluter.fromme.com Wed Jun 30 11:01:35 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 30 Jun 2004 15:01:35 GMT Subject: does not work on freeBSD but works on linux, and windows References: <1NoEc.79428$kV1.13425@newssvr29.news.prodigy.com> <2kfg7kF1n9mdU1@uni-berlin.de> Message-ID: <2kg2ufF1uftbU1@uni-berlin.de> John fabiani wrote: > Thanks for your reply. Can freeBSD support python 2.3? Yes, it's a standard package in FreeBSD 4.10. > And if it does > how do I install it. First you should remove your old version of python, in order to avoid any potential pitfalls. Use the pkg_delete command for that purpose. To install the precompiled binary package for FreeBSD 4.10, perform this command as root: pkg_add -r python If you prefer to fetch the source code and compile it your- self, type these commands as root (provided that you have installed the ports collection, which really is strongly recommended): cd /usr/ports/lang/python make install make clean For more details on the pkg_add(1) command, please refer to its manual page. For more information on the FreeBSD ports collection, please refer to the appropriate chapter in the Handbook. Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From has.temp2 at virgin.net Mon Jun 21 13:53:16 2004 From: has.temp2 at virgin.net (has) Date: 21 Jun 2004 10:53:16 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <69cbbef2.0406201036.53506906@posting.google.com> <2jnslaF121d5gU1@uni-berlin.de> Message-ID: <69cbbef2.0406210953.4b672161@posting.google.com> Daniel Ellison wrote in message news:<2jnslaF121d5gU1 at uni-berlin.de>... > has wrote: > > PyMeld, Nevow.renderer and HTMLTemplate all provide complete > > separation of business and presentation logic from HTML markup. > > > > Also, because they're designed specifically for templating, they > > should also be a lot simpler and easier to use than generic DOM > > systems such as ElementTree. > > > > Who said ElementTree was a generic DOM system? Oops. Sorry. Should've said "DOM-style", seeing as the acronym "DOM" is imbued with rather specific meaning. Basically, I mean anything that represents a document as an object model. > Admittedly, the just-in-time lookup on IDs is less than ideal. Better > would be a system which cached the elements containing IDs in a > dictionary on parsing the document. Have you looked at PyMeld/Nevow.renderer/HTMLTemplate at all? These systems only convert "special" elements into independent template nodes, resulting in a much simpler, more efficient object model. HTH From moughanj at tcd.ie Thu Jun 10 23:02:11 2004 From: moughanj at tcd.ie (James Moughan) Date: 10 Jun 2004 20:02:11 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <8ef9bea6.0406100710.1a17b11b@posting.google.com> Message-ID: <16752bcc.0406101902.6eb51e43@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0406100710.1a17b11b at posting.google.com>... > moughanj at tcd.ie (James Moughan) wrote: > > I still have to restrain myself from writing PyHaskell now and then. > > Maybe it's time to try with some simple prototype. > > > Secondly, Lisp's syntax doesn't parse well into the way people think, > > or vica versa. Python's does; in other words, it's executable > > pseudocode. Lisp, fundamentally, cannot change in this regard. > > But Python does have serious problems when one goes to the next level > of software development. I guess that's why Io and Prothon were born. > Python is at the stage where you need a fresh re-incarnation to go to > the next level. > I'm curious as to what those problems are, and what the 'next leve' is; there are definitely warts, and some, like the scoping rules, get in the way occasionally, but by and large there's nothing that can't be worked around. It lacks severely in compile-time metaprogramming, but has some very nice run-time features, which are arguably better in a language which isn't too focussed on performance. > There are a few directions that need to be explorered, and I am not > sure creating a real new language is the way to go. I've seen it in > Io, where once you set things in stone, it becomes just another Python > with problems that will stay forever. I guess right now it's not the > moment of creating more languages and set things in stone. It's > probably better to have some toy languages or language prototypes to > explorer ideas. Collect enough ideas and experience, and probably > leave the rest to the next generation of people. > > Frankly, I see a few camps: (a) Lisp and AOP folks, (b) Functional > folks, (c) Prototype-based folks. Because these are very specialized > fields, very few people seem to be native speakers of all three of > them. The next killer language will have to incorporate lessons learnt > from all three camps. It's a daunting task. It's best to have some toy > languages... like scaled-down model airplanes, or even just the model > airplane parts, before one actually build the real thing. > There are a lot of interesting ideas out there - personally I'd like to see Stepanov cease being so notoriously lazy and write the language C++ could have been. :) We'll probably find different paradigms being useful in different contexts, and to different people. After all, how boring would the world be if you only ever needed to learn one language? Jam > regards, > > Hung Jung From mizrandir at hotmail.com Mon Jun 14 03:40:14 2004 From: mizrandir at hotmail.com (Mizrandir) Date: 14 Jun 2004 00:40:14 -0700 Subject: Help with os.system References: <40cccc76$0$41755$5fc3050@dreader2.news.tiscali.nl> Message-ID: > Hope this helps Yes, thanks. The second part (storing things in vars) I had already figured out myself (but after posting). The first (about \\) I imagined it was something like that but I didn't know why in some places yes and not in others. But it's clear now. miz. From Mike at DeleteThis.Geary.com Tue Jun 29 10:29:02 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 29 Jun 2004 07:29:02 -0700 Subject: urlib - automatic cookie handling References: <10e2sgtng7f23b2@corp.supernews.com> Message-ID: <10e2v5f5es5lcd@corp.supernews.com> Alex Hunsley wrote: > I'm using urllib to post data to a web form by issuing a command similar > to this: > > filename, headers = > urllib.urlretrieve("http://www.thewebsitenamehere.com/servlet/com.blah.bloo. XmlFeed", > "content.txt", None, urllib.urlencode({"aParameter": "theValue"})) > > Now, the problem is that the above fails, since I am not sending a session > cookie. Visitors to the web sites' html submission form are sent a session > cookie which is given back to the server when they submit a search via the > browser, as often happens. > Now, I could use urllib to get the form page and read the cookie from the > headers that are returned and then manually put that cookie in my > submission to the servlet, but my question is: is there a way to tell urllib > or some other part of HTTP handling in python that I want to remember > any cookie that is given to me, and give it back to that site if I send > requests later on? You're looking for ClientCookie: http://wwwsearch.sourceforge.net/ClientCookie/ http://wwwsearch.sourceforge.net/ClientCookie/doc.html -Mike From cgadgil_list at cxoindia.dnsalias.com Fri Jun 4 06:45:06 2004 From: cgadgil_list at cxoindia.dnsalias.com (Chetan Gadgil) Date: Fri, 4 Jun 2004 16:15:06 +0530 Subject: Which is the most mature Soap module? In-Reply-To: Message-ID: <040601c44a20$ffc0c990$5b0aa8c0@cxodt03> If you are working with Windows, you can use the excellent WebServices support in .NET. To access this from Python, you can use one of the many .NET extensions for Python. http://www.python.org/wiki/pub/PyConChetanGadgil/attachments/PyCON%20Pap er%20on%20%22.NET%20for%20Python%22.htm http://www.zope.org/Members/Brian/PythonNet/index_html With these, you can let everything be done from Python, in .NET, such as: 1) WSE 2) HPPTS 3) Transparent client stubs for webservices If needed, you can search online for Microsoft's documentation for webservices from .NET. Regards Chetan "Contrariwise," continued Tweedledee, "if it was so, it might be, and if it were so, it would be; but as it isn't, it ain't. That's logic!" -- Lewis Carroll, "Through the Looking Glass" > -----Original Message----- > From: > python-list-bounces+cgadgil_list=cxoindia.dnsalias.com at python. > org > [mailto:python-list-bounces+cgadgil_list=cxoindia.dnsalias.com > @python.org] On Behalf Of Mickel Gr?nroos > Sent: Friday, June 04, 2004 3:57 PM > To: John J. Lee > Cc: python-list at python.org > Subject: Re: Which is the most mature Soap module? > > > The following is a rather long message. Here is a summary of > my questions > below: > > 1. ZSI fails on a TypeError when using ZSI.ServiceProxy, why? > > 2. Is there a way to use cookie authentification with SOAPpy > (client-side)? > > > On Tue, 1 Jun 2004, John J. Lee wrote: > > > Mickel Gr?nroos writes: > > > > > To the heart of the matter: Which of the available Soap > modules is > > > best fitted for client side soap messaging? I have an > upload service > > > (written in Perl) that I want to use from a Python > application. What > > > I want to do is send base64 encoded files via Soap to this upload > > > service which is on a SSL encrypted server. I cannot really grasp > > > the current development status > > > > IIRC, ZSI is. Certainly there is no solid WSDL implementation. > > I downloaded and installed both ZSI (1.5) and SOAPpy (0.11.4) > both from . ZSI only > required PyXML (0.8.3, from > ) to be available, SOAPpy > needed PyXML as well as fpconst (0.7.0, from > pconst/>) > > My problem concerns doing two things: > > 1. First, I need to log in at a secure server. In return I > get a cookie that functions as user authentification. > > 2. Second, I need to upload a local file to a specific place > on the server using the cookie as authentification. > > I got the login part working nicely using SOAPpy: > > >>> import SOAPpy > >>> server = > >>> SOAPpy.WSDL.Proxy("https://hotpage.csc.fi/log/soap.phtml?wsdl") > >>> cookie = server.login("myusername", "secretpass") > >>> > > Whereas ZSI failed on a TypeError: > > >>> server = > >>> ZSI.ServiceProxy('https://hotpage.csc.fi/log/soap.phtml?wsdl', > ... use_wsdl=True) > >>> cookie = server.login(username='myusername', passwd='secretpass') > Traceback (most recent call last): > File "", line 1, in ? > File > "/usr/local/lib/python2.3/site-packages/ZSI/ServiceProxy.py", > line 278, in __call__ > return self.parent()._call(self.__name__, *args, **kwargs) > File > "/usr/local/lib/python2.3/site-packages/ZSI/ServiceProxy.py", > line 83, in _call > nsdict=self._nsdict, soapaction=soapAction, > requesttypecode=request) > File > "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 209, > in Send self.h.connect() > File "/usr/local/lib/python2.3/httplib.py", line 960, in connect > sock.connect((self.host, self.port)) > File "", line 1, in connect > TypeError: an integer is required > >>> > > Any ideas what this might be? I gather I would need to set > the port to 443 somewhere, but I can't find the right place. > > > The second part, i.e. the upload, is trickier. Using > SOAP::Lite in Perl, one can specify a cookie to use for > authentification, but I can seem to find that in the > documentation of SOAPpy. So how do I do cookie > authentification with SOAPpy (or ZSI for that matter)?? > > Here is the Perl SOAP::Lite code that does the trick (copied from > ): > > use SOAP::Lite; > use HTTP::Cookies; > > my $soap = SOAP::Lite > -> uri('urn:xmethodsInterop') > > -> proxy('http://services.xmethods.net/soap/servlet/rpcrouter', > cookie_jar => HTTP::Cookies->new(ignore_discard => 1)); > > print $soap->echoString('Hello')->result; > > I need something like that 'cookie_jar' parameter in SOAPpy > too. Help and thanks! > > /Mickel > > -- > http://mail.python.org/mailman/listinfo/python-list > From balaji at email.arizona.edu Wed Jun 16 18:29:58 2004 From: balaji at email.arizona.edu (Balaji) Date: 16 Jun 2004 15:29:58 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> <494182a9.0406141915.7061d0f6@posting.google.com> Message-ID: <494182a9.0406160855.65a271cc@posting.google.com> Dear Dan, What I'm trying to do in my application is preserve the order in which the user wrote an expression. If a user writes e1=100>=x, python treats it as e1= x<=100. Both are same mathematically but semantically they are not. If a user prints this expression he will get e1= x<=100, which is different than e1=100<=x. In my application both the <= and >= have totally different meaning. They are not just used for comparisson. Regards Balaji From ilya at glas.net Fri Jun 25 03:25:00 2004 From: ilya at glas.net (Ilya Etingof) Date: Fri, 25 Jun 2004 07:25:00 +0000 (UTC) Subject: pysnmp/shell References: <02WBc.1559$7u2.1135@amsnews03.chello.com> Message-ID: Les Smithson wrote: > I find the pysnmp API non-intuitive, but maybe that's just me. I've > been thinking about writing a wrapper for it that makes it look more > like the SNMP++ object model, which I'm much more comfortable with. Well, current pysnmp API deals with rather low-level SNMP protocol details. That's probably the basic cause of API complexity. From the other hand, adding another layer of abstraction over current (rather protocol bound) API might make the whole thing even less efficient (mainly in CPU terms)... Anyway, I'm currently working on complete SNMP engine implementation (on top of current protocol API) that would include RFC-compliant API to SNMP engine, support for SNMP agent instrumentation and manager access to MIB information. I hope this would significantly reduce API complexity. -ilya ps. BTW, there are some rather strightforward examples at: http://pysnmp.sourceforge.net/examples/3.4.x/index.html From chuck at smtl.co.uk Wed Jun 9 10:19:36 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Wed, 09 Jun 2004 15:19:36 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Wed, 09 Jun 2004 11:46:45 BST." <200406091046.i59Akjeb002862@sevenofnine.smtl.co.uk> References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> <200406090826.i598QVeb002497@sevenofnine.smtl.co.uk> <200406090920.i599K0eb002672@sevenofnine.smtl.co.uk> <200406091046.i59Akjeb002862@sevenofnine.smtl.co.uk> Message-ID: <200406091419.i59EJaeb003412@sevenofnine.smtl.co.uk> Hi please could someone point to what I have done wrong as the script runs with no errors but the file I am trying to parse the print statement output too instead of just the screen/command line to another file. I have digested the Input and Output and text formatting docs and I read something about using stdout to a file . Can someone point me in the right direction. Cheers my code below. ############################################################### ## This script will open and parse email messages body content. ## This Python script will reside on Mail Server on ds9: ## Emails are all plain/text you could just write the following ## Which will leave a list of strings , each one a message body. ## The Survey User is testwws and the .procmailrc file folder is ## Survey . i.e /home/testwws/Mail/inbox/Survey . ############################################################### ## file:getSurveyMail.py Created : 06/06/04 Amended date: 09/06/04 ## Revision 1. make copy to continue called getSurveyMailRev2.py ############################################################### #The following line makes it run itself(executable script on UN*X) #!/usr/bin/env python import sys import os import email import mailbox import StringIO # Open the testwws user mailbox (tmp user chuck) # fp denotes factory paraemeter # mode can be 'r' when the file will only be read, 'w' for only writing #(an existing file with the same name will be erased), and 'a' opens the file # for appending; any data written to the file is automatically added to the end. # 'r+' opens the file for both reading and writing. The mode. # The File SurveyResults.txt must all ready exist. #mailout = open("/home/chuck/pythonScript/SurveyResults.txt") # mode 'w' means open the file for writ-ing # (any data already in the file will be erased) #output.writelines(mailout) mailout = file("/home/chuck/pythonScript/SurveyResults.txt") # open() returns a file object, and is most commonly used with two arguments: # "open(filename, mode)". fp = open("/home/chuck/pythonScript/testbox") # message_from_file returns a message object struct tree from an # open file object. mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() # First open the testbox file to read(r) and write(w)to the SurveyResults.txt #fp = open("testbox","r") mailout = open("/home/chuck/pythonScript/SurveyResults.txt","w") # Read the testbox file into a list then copy to # new file. for mail in fp.readlines(): mailout.write(mail) print "testbox file copied...to SurveyResults.txt" # Now close the files fp.close() mailout.close() #mailout.close to close it and free up any system resources taken up by the open file. # After calling output.close(), attempts to use the file object will automatically fail. From j_mckitrick at bigfoot.com Fri Jun 18 06:26:08 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 18 Jun 2004 03:26:08 -0700 Subject: Why does one work, but not the other? References: Message-ID: Thanks for the help, guys. I found the problem. The liststore cannot be redefined once set up for the TreeView. I can only clear/append to it. But I'm still on my mission to replace 'for' with list comprehensions where possible, according to the article on optimization on the python site. That being said, is there a way to write this as a comprehension? I can't figure out how to do so and get k into the key correctly. I'm just trying to save a dictionary via anydbm. for k, v in self.options.items(): db[k] = str(v) jonathon From alan.gauld at btinternet.com Thu Jun 3 04:13:49 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 Jun 2004 09:13:49 +0100 Subject: Why did no one invent Python before? References: Message-ID: On Thu, 03 Jun 2004 04:26:27 GMT, Dennis Lee Bieber wrote: > > Yes, it's a silly question, but given how far we have come, why is it > > that a natural looking, easy to read, incredibly powerful language has > > appeared only recently, from a tech standpoint? > FORTRAN goes back the tail-end of the 50s, and COBOL and LISP > aren't too distant from it. Call it 1960. And the power of data structures like dictionaries weren't really appreciated till the 70's and standard *efficent* implementations weren't available till about the early 80's. Now given that much of Pythons innards consist of nothing but dictionaries, it would have been difficult to build something like python(or ABC) toill at least the mid 80's. ABC was late 80's, so not so very far behind the state of the art... > It takes computer power to process a language... Imagine having > to pay the time used for Python, when running on a processor like my > college mainframe True, although BASIC was atound in 1963 and interpreted - but with a very much simpler syntax than Python... Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From 00515879256 at fastwebnet.it Wed Jun 16 10:24:31 2004 From: 00515879256 at fastwebnet.it (Glauco) Date: Wed, 16 Jun 2004 16:24:31 +0200 Subject: Secure File Transfer Message-ID: hi to all, i'm planning to make a way to transfer file with python. I would like to make the transfer using some crypto api, to make the channel secure. i don't want to write a wrapper to ftp or to scp i just want to make a new protocol, for a little application. i took a quick look to some cryptographic modules available in python (expecially pycrypto, gnupginterface, m2crypto) and i'm now stuck on which one of these to choose. Here's what i have in my mind: Alice wants to upload/download some files from Bob. Both of them have the public key (made with gpg), so in the handshaking for the shared key is done using gpg. After that the shared key is know to both the end of the channel and they can use it to send the data. i don't know what protocol (AES 3DES Blowfish? ) to use for the transfer and i don't know if it could be better to implement it directly with DSA/RSA rather than using GPG + somesymmetricprotocol any suggestion hints example ? Someone tried something like that ? i'm using SocketServer for the network stuff so i would like to find something wich can better suit with it Many thanks for all the suggestion you can give me . Samuele From peter at engcorp.com Tue Jun 29 17:01:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 17:01:35 -0400 Subject: wxPython support non-GUI classes from wxWidgets? In-Reply-To: References: Message-ID: USCode wrote: > I've been poking around the wxPython website and am unclear if wxPython has > a wrapper for ALL wxWidget classes or just the GUI-related classes? Does > wxPython also provide a python wrapper for the wxWidget non-GUI classes such > as: ODBC, printing, threading, interprocess communication, XML, streams, > etc. > > I realize Python provides many of these facilities natively but through > wxPython, can I use the wxWidget versions instead? The docs, somewhere, note that primarily only the functionality that is *not* duplicated by existing Python functionality is provided. I believe that includes at least XML, threading, and anything to do with networking, and probably other things. (Going entirely by memory here, from the last time I read this stuff, well over a year ago. I can find the exact location of the notes, if you aren't able to.) -Peter From roy at panix.com Fri Jun 18 07:27:17 2004 From: roy at panix.com (Roy Smith) Date: Fri, 18 Jun 2004 07:27:17 -0400 Subject: does python have useless destructors? References: Message-ID: > > Maybe I don't need it, maybe 310 gives me RAII and that's what > > I really need. I don't know, but again, 310 doesn't give me > > anything of consequence in terms of software architecture. I just read PEP-310, and there's something I don't understand. It says: > Note that this makes using an object that does not have an > __exit__() method a fail-fast error. What does "fail-fast" mean? From guettli at thomas-guettler.de Thu Jun 3 08:11:59 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 03 Jun 2004 14:11:59 +0200 Subject: python applets? References: Message-ID: Am Wed, 02 Jun 2004 21:43:40 +0200 schrieb Andreas R?sdal: > Hi, > > Is there such a thing as python applets for web browsers? (eg. such as > java applets?) I think that could be useful. Yes, this would be useful if it would exist (see other replies) and if all browers would have this plugin. If you are doing an intranet solution, you can create your own GUI talking e.g. xml-rpc with the server. Regards, Thomas From opengeometry at yahoo.ca Tue Jun 8 06:59:15 2004 From: opengeometry at yahoo.ca (William Park) Date: 8 Jun 2004 10:59:15 GMT Subject: simple script to read and output Mailbox body to file. References: <2ijmctFnvgjeU2@uni-berlin.de> Message-ID: <2ilkg2For39hU1@uni-berlin.de> chuck amadi wrote: > William Park wrote: > >You still haven't answered central questions. > > - Do you want email bodies in separate files, or all email bodies in > > one file? > > - Do you want to collect these email bodies as they come in, or > > periodically from a 'mbox' file? > > > Hi There , > > I would like all email bodies in one file.Collect these email bodies > as they come in, or periodically from a 'mbox' file? using cron. > > I would lie cron to run the script and empty the mail user box in > question to a file for extraction to a database. Since your running Linux, you can simply do manual or periodic parsing of mbox file and put the email bodies into 'file', formail -I '' -s < mbox >> file Or, use Procmail recipe as email comes in, :0 b: * some_condition | cat >> file Ref: man formail procmail procmailrc procmailex Homework: Translate it to Python. -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From __peter__ at web.de Sun Jun 20 10:59:16 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 20 Jun 2004 16:59:16 +0200 Subject: datetime, calendar, time intervals References: <95aa1afa.0406162213.3cf3d7f7@posting.google.com> <10d35suo3ek1b51@news.supernews.com> Message-ID: NewToPython wrote: > interested in the data functions of the latest release as well. When > you say that it was a C module, are you saying the library of date > functions in the latest version are written in C? Does this somehow > stop us from back-porting it to 2.2 or 2.1 python? I would be very Nobody would stop someone willing to do the work :-) > interested in seeing the C source code for the date routines, along > with the routine descriptions - where can I find that? > You can find the source distribution of the current version at the usual place: http://www.python.org/download/ A good starting point for a (future) developer would be http://www.python.org/dev/ If you are only interested in one module, you can browse the CVS tree (see "Outside Links" on the above page). The datetime implementation is here: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/datetimemodule.c Peter From tor.iver.wilhelmsen at broadpark.no Sun Jun 6 17:24:16 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 06 Jun 2004 23:24:16 +0200 Subject: left-quote ( ` ) on International keyboards [Prothon] References: Message-ID: "Mark Hahn" writes: > Can users with international keyboards tell me if they have problems typing > the left-quote ( ` ) character? For keyboards using the "combining" key in the place for = and + on US keyboards, it's one more key to type (the key plus space). Not a big deal, we get used to it. :) From lbates at swamisoft.com Thu Jun 3 11:49:50 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 10:49:50 -0500 Subject: two silly questions References: Message-ID: The absolute "best" way to do what you want is to write an NT service. Mark Hammond's Python Programming on Win32 has excellent examples of this. NT services run in the background and can be set to actually sleep for any amount of time (in microseconds). I've written several of these and while the learning curve is a little steep on the front end, the resulting application is MUCH better. HTH, Larry Bates Syscon, Inc. "bill ramsay" wrote in message news:upetb0dimckv16o1b1actl9tngej94enkf at 4ax.com... > Hello > > just found the wonderful world of python in the last two weeks and I > think that it is great. > > I have a couple of questions for those who are wiser a la python than > I am. > > Background: > > I have written a program that polls an email account, then pulls down > the email, it then searches through the email, and depending upon > type, ie. with or without attachments it does different things. The > net result is that data is written to access tables for an external > application to extract the necessary data. > > I am using win2k. > > the two questions are: > > 1. when i want the program to run in a loop, ie. poll the pop3 > account every 60 seconds, it runs the first time, then it goes into > 'not responding mode' thereafter, sometimes. Any thoughts? I was > using sleep(60) but it just hangs, as i said before, it does not > always do that either! > > 2. I wish to use this program at work, I took in an earlier version > yesterday that just wrote the data to a text file, I wanted to make > sure the polling thing worked. on microsoft exchange [i know that it > should, but you never know!!] and it does . When i was there, i > managed to get the code to run just by double clicking on the code > ICON, seem to remember doing something with 'open with' can't seem to > do it here at home. > > Both systems run win2k. did i do something sublimilally without > realising it? what did i do i cannot remember, i have tried opening > with etc. when i do this all get is a burst of the 'black windows > box' just in the same way as putting in 'cmd' on the run thing, > > as you can see i am not up on all the terms. > > if anyone can help, i would appreciate it. > > kind regards > > bill ramsay. > From fumanchu at amor.org Fri Jun 18 00:10:28 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 17 Jun 2004 21:10:28 -0700 Subject: Why does one work, but not the other? Message-ID: j_mckitrick wrote: > self.liststore = [[item] for item in data] > I get an empty list! What gives?? Dunno--I don't get an empty list. >>> data = [1,2,3] >>> [[item] for item in data] [[1], [2], [3]] Seems the problem lies elsewhere... Robert Brewer MIS Amor Ministries fumanchu at amor.org From a.schmolck at gmx.net Thu Jun 10 08:44:25 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Thu, 10 Jun 2004 13:44:25 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Message-ID: [This requires less time than replying to your previous post, so I'll do it first] hungjunglu at yahoo.com (Hung Jung Lu) writes: > Therefore, Lisp seems not nearly as flexible as Io. It would seem you are completely clueless about Lisp, so there isn't much point discussing this statement. If you are at all interested in programming languages as such I think you'd be well rewarded if you at least have a good look at scheme (CL is also well worth some study). Whether one likes scheme as a practical programming language or not, I think it's difficult not to find it invaluable as a sort of conceptual assembler. A great number of programming paradigms can be concisely and illuminatingly expressed and reasoned about using just a handful of the powerful abstractions such as, e.g. (properly tail recursive) lambda, call/cc, cons, symbols and defmacro?. In addition, the majority of excellent computer science books I've come across (and many great articles) use scheme or some other lisp and, even better, are often freely available on the web?! 'as ? defmacro is not part of the standard, but generally available, and, I think, much easier conceptualized than scheme's more complicated hygenic macro systems. ? Just to mention the most famous: http://mitpress.mit.edu/sicp/full-text/book/book.html From has.temp2 at virgin.net Wed Jun 2 14:49:38 2004 From: has.temp2 at virgin.net (has) Date: 2 Jun 2004 11:49:38 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406021049.41406074@posting.google.com> Duncan Booth wrote in message news:... > By contrast, a template in HTMLTemplate isn't valid HTML since it contains > undefined attributes in the default namespace. It is reasonable to expect > that an HTML editor will strip out the illegal attributes. HTMLTemplate allows you to specify a different 'special' attribute name via the Template constructor, so you can use attributes like 'id' and XML namespaces instead of 'node' if you prefer. (The reason I made 'node' the default is that it's more or less self-explanatory so convenient for new users. I've updated the HTMLTemplate homepage to clarify this issue.) It's also quite intelligent in how it parses these attributes. For example, when using 'id', an element like
    ...
    would be identified as containing a legal compiler directive, the special attribute stripped and a template node created. All other 'id' attributes would be left untouched, however, so you can still safely use them as normal id attributes on non-node elements. > The ultimate Python templating framework for separating Python from the > template has to be PyMeld. PyMeld templates are pure XHTML with no > additional attributes whatsoever. I looked at PyMeld early on as it's closest to HTMLTemplate in concept and behaviour and about the same in code size and complexity. Its shortcomings are a non-standard licence, an inferior API [compared to HTMLTemplate] that requires users to write their own loops and, according to its author, some performance issues due to naive implementation. All quite fixable, of course, but it was just more convenient for me to port my existing HTMLTemplate implementation to Python. Hope that allays your fears. :) -- (p.s. Inquisitive users may also spot the potential for meta-templating that being able to specify one's own 'special' attribute names provides. Though whether anyone can come up with an actual use for meta-templating is another question entirely...;) From grante at visi.com Fri Jun 4 11:32:54 2004 From: grante at visi.com (Grant Edwards) Date: 04 Jun 2004 15:32:54 GMT Subject: Why did no one invent Python before? References: Message-ID: On 2004-06-04, Hans Nowak wrote: >>>All python did was provide a good programming environment. >> >> That's not all. There is one thing that I've heard more about Python than >> any other language. People, myself included, say it is fun to program in >> Python. Fun. I find programming neat but I would never say that my time >> programming in Turbo Pascal or Perl was fun. :) > > I would. Turbo Pascal, that is, not Perl. Of course, back then I didn't know > any better... :-) I'd have to agree that in it's time Turbo Pascal was completely revolutionary. It had the same "batteries included" feel that Python does. -- Grant Edwards grante Yow! Is this BOISE?? at visi.com From jacek.generowicz at cern.ch Wed Jun 16 06:42:31 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 16 Jun 2004 12:42:31 +0200 Subject: test - ignore Message-ID: Just checking that the local problem we had, has been fixed ... From dooms at info.LESS.ucl.SPAM.ac.be Mon Jun 14 04:07:28 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Mon, 14 Jun 2004 10:07:28 +0200 Subject: python array data structure In-Reply-To: <2j52cvFt31knU1@uni-berlin.de> References: <2j52cvFt31knU1@uni-berlin.de> Message-ID: <40cd5cdd$0$41752$5fc3050@dreader2.news.tiscali.nl> lenk wrote: > Hi all, > I want to learn the data structure of python array, > is there any website or book for learning If your refer to lists look at the python tutorial http://www.python.org/doc/current/tut (section 3.1.4 and 5.1) If you want array() look at the NumArray module: http://stsdas.stsci.edu/numarray/numarray-0.9.html/index.html For beginner questions, refer to the python-tutor mailing list: mailto:tutor at python.org HTH, -- Gr?goire Dooms > > thanks > From donn at u.washington.edu Tue Jun 15 18:35:16 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 15 Jun 2004 15:35:16 -0700 Subject: popen2.Popen3 process destruction References: Message-ID: In article , wrote: > I have created a class which inherits popen2.Popen3. > > The problem is that popen2.Popen3 does not define a __del__ > method to handle proper closing of the pipes or destruction of > the process. So I created one in my class: ... > However, since the popen2 module stores a reference to the > object in popen2._active this __del__ method is never called > to clean things up. _cleanup() called in Popen3.__init__() > fails to clean up the process in subsequent instantiations. > This eventually leads to an "OSError: [Errno 24] Too many open > files" The instance needs to keep itself around, to work with popen2 and popen3 functions and generally support direct use of the pipe fileobjects and file descriptors. > "_clean()" fails because the program being called is > interactive using stdin/stdout. Much in the way "cat" is. In > fact the unit test provided with the popen2 module _test() > uses "cat" and hangs for the very same reason. It hangs on > "for inst in _active[:]:inst.wait()" This is why I created my > own class, to handle this special interactive nature. That is not normal, that I know of - test_open2.py's use of cat should not cause a hang. Unless we're looking at very different versions of test_popen2.py. I wonder if there could be a problem somewhere in the IRIX64 implementation of Python, or in the OS itself. Donn Cave, donn at u.washington.edu From mporter at despammed.com Mon Jun 7 17:12:27 2004 From: mporter at despammed.com (Michael Porter) Date: Mon, 7 Jun 2004 22:12:27 +0100 Subject: Storing files in a BLOB field via SQL References: <5a2071a0.0406061231.59c3bede@posting.google.com> Message-ID: <40c4d8d9$0$258$cc9e4d1f@news.dial.pipex.com> "Juergen Gerner" wrote in message news:5a2071a0.0406061231.59c3bede at posting.google.com... > Hello Python fans, > > The main problem is the handling of the binary data. There might be > errors in the SQL syntax if some special chars (quotas etc.) appear, > or the SQL statement is incorrect because of strange chars that can't > be encoded by the current codeset. Another problem is, you can't strip > these chars because you would change the binary data or make it bigger > than 64k. > > Does anybody of you have an idea? > Any suggestions would be very helpful. You can either use the MySQL hex literal format (x'AABBCC'...) or use the Python DB API which will handle the parameter conversion for you... In the first case your query becomes somethings like: query = "INSERT INTO table (order,data) VALUES (%i,x'%s')" % (order, data.encode('hex')) In the second, preferable version you use something like: cur = conn.cursor() cur.execute("INSERT INTO table (order,data) VALUES (?,?)", (order, data)) and the DBAPI/Database driver takes care of the rest. > Additionally, I want to compress the data and store a checksum > somewhere. Any hint (links, sites, ...) is welcome...! compressed = data.encode('zip') # Compress the data Mike. From dooms at info.LESS.ucl.SPAM.ac.be Sun Jun 13 05:14:20 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Sun, 13 Jun 2004 11:14:20 +0200 Subject: Good IDE for Python In-Reply-To: <889cbba0.0406122346.2e77941b@posting.google.com> References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: <40cc1b05$0$41764$5fc3050@dreader2.news.tiscali.nl> Kamilche wrote: > I love Python, but I'm less than in love with IDLE. It's OK, but it > really doesn't have enough capabilities. > > What I consider critical, are a popdown listing of all my functions, > colored syntax printing, and a right-click 'definition' context menu > that will hop you to the spot where that keyword is defined, if > possible. Everything else I could learn to do without, but these > features keep me hoping for a better IDE for Python. > > I'm used to the Microsoft Visual C++ debugger, and though tooltip > variable debugging and intellisense were nice, they broke often enough > that you couldn't rely on them anyway, so I don't really need those > features. > > I would also like the ability to create application 'forms' visually. > I'm on a Windows XP machine. > > Any suggestions on what I should install next? This patch to IDLE improves it a bit: http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group_id=5470&atid=305470 It adds among other things the pop-down function list. It's a little cumbersome to apply but the result is quite good. I've been using it for a few days and I'm quite happy with it. I may provide a patch against python 2.3.3 or another version if someone is interrested. If you are interresed, I made a smaller patch adding the qualified name autocompletion (module.functions). But the former patch does it better (it even supports filename autocompletion). -- Gr?goire Dooms From peter.maas at mplusr.de Wed Jun 30 09:47:43 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 30 Jun 2004 15:47:43 +0200 Subject: Non GPL Python MySQL Client Library. In-Reply-To: <1bs*2tkoq@news.chiark.greenend.org.uk> References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <1bs*2tkoq@news.chiark.greenend.org.uk> Message-ID: Sion Arrowsmith schrieb: >>PostgreSQL is freely available >>for Windows platforms (I use it every day). It can be quite readily >>installed as part of the CYGWIN environment, [ ... ] > > Which means that either you have to persuade your target audience > to install Cygwin, [...] AFAIK Postgres 7.4+ can be compiled with MINGW/MSYS on a Windows platform and the resulting binary runs without Cywin. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From bpeng at rice.edu Sun Jun 20 02:59:01 2004 From: bpeng at rice.edu (Bo Peng) Date: Sun, 20 Jun 2004 01:59:01 -0500 Subject: swig/python problem: passing vector of objects. Message-ID: Dear List, I have had success in using vector.i of SWIG to map between c++: foo(vector) python: foo([1,2,3]) However, the map of vector of objects fails: c++: foo(vector ) python: a = obj() foo([a]) Can anyone tell me 1. what exactly being passed to C++, a swig_pointer of a? Is there any copy constructure invloved during parameter passing? 2. It would be best for me to pass pointers of objects, i.e., I would like foo([a]) # python code to do foo(vector) Is there any easy way to do it? (I do not know how to write SWIG maps.) Many thanks in advance. Bo From donn at u.washington.edu Wed Jun 16 13:41:56 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 16 Jun 2004 10:41:56 -0700 Subject: str() for containers References: <40d07ac6@rutgers.edu> Message-ID: In article <40d07ac6 at rutgers.edu>, "George Sakkis" wrote: > I find the string representation behaviour of builtin containers > (tuples,lists,dicts) unintuitive in that they don't call recursively str() > on their contents (e.g. as in Java) Please find last week's answers to this question at http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=62e7a6469ac7b40b If you're still interested in further discussion of this point, you could present an account of Java's approach for the edification of those of us who don't know. Donn Cave, donn at u.washington.edu From djordan8 at houston.rr.com Wed Jun 16 18:46:42 2004 From: djordan8 at houston.rr.com (Doug Jordan) Date: Wed, 16 Jun 2004 22:46:42 GMT Subject: cannot pass a variable from a function Message-ID: I am fairly new to Python. This should be an easy answer but I cannot get this to work. The code is listed below. I know how to do this in C, Fortran, and VB but it doesn't seem to work the same way here. I would appreciate any help. #try this to pass a list to a function and have the function return #a variable #this works list=[1,4,6,9] def fctn(c): for h in c: q=h*80 print q #function suppose to return variable def fctn2(c): for h in c: q=h*80 return q def prntfctn(y): for j in y: print j fctn(list) fctn2(list) prntfctn(q) I need to be able to return variables from functions so they can be used globally in the rest of the program I am writing. Thanks Doug From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Wed Jun 30 08:36:49 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Wed, 30 Jun 2004 14:36:49 +0200 Subject: TERMIOS.py References: Message-ID: under windows : ren TERMIOS.py termios.py From NOSPAM at easyconnect.fr Sun Jun 6 10:48:05 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Sun, 6 Jun 2004 16:48:05 +0200 Subject: compiling python with unix References: <40c033e0$0$2277$afc38c87@news.easynet.fr> <10c0un6nf57b4ce@corp.supernews.com> Message-ID: <40c32fbd$0$2287$afc38c87@news.easynet.fr> "Cameron Laird" a ?crit dans le message de news:10c0un6nf57b4ce at corp.supernews.com... > In article <40c033e0$0$2277$afc38c87 at news.easynet.fr>, > RosalieM wrote: > >I would like to understand what python needs to work on unix. > >And to understand how i can make it smalest possible? > >I dont understand at all setup. > > > >I searched in python.org and in sources but it is not clear at all for me. > > > >Can python run with a posix C compiler and minix or something like that ? > . > . > . > There are probably simple answers to your questions. It > might take a bit of conversation before we understand each > other's language. > > Most Unix host nowadays install with Python already present. > Under MacOS and nearly all Linux distributions, for example, > I can type at the command line, and receive responses: > # python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> 3 + 8.5 > 11.5 > >>> print("Hello, world.") > Hello, world. > Is that the sort of information you seek? If you prefer, > fr.comp.lang.python is also available as a Usenet newsgroup. > -- > > Cameron Laird > Business: http://www.Phaseit.net I used a lfs 4.0 to build my unix. But is is very fat. I can compile python from there and play with "Hello World", but i dont uderstand how to choose what i need and what i dont need to compile it and choose features that python would be able to do. For example, can i build python on a minix system? Why socket module needs threads to compile ? I search answers to this kind of questions. Thanks. From tjreedy at udel.edu Tue Jun 8 08:41:52 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 08:41:52 -0400 Subject: Passing parameters using **kargs References: Message-ID: "Duncan Booth" > Thomas Philips) > > > I want to access parameters that are passed into a function using the > > **kargs idiom. I define f(**kargs) via > > > > def f(**kargs): > > print kargs > The ** argument is for keyword arguments where you don't know in advance > all the keywords that might be valid. Or if you don't care, or want to intercept invalid calls. Interestingly, the OP's example is the beginning of a possible debug wrapper usage where one either does not have a function's code or does not want to modify it directly. Possible example: _f_orig = f def f(*largs, **kargs): print 'f called with' largs, 'and', kargs f(*largs, **kargs) Terry J. Reedy From dkturner at telkomsa.net Tue Jun 15 07:11:46 2004 From: dkturner at telkomsa.net (David Turner) Date: 15 Jun 2004 04:11:46 -0700 Subject: does python have useless destructors? References: Message-ID: Peter Hansen wrote in message news:... > David Turner wrote: > > > I *want* to spend more time in Python, but as things stand my C++ code > > is more robust. > > Is this a theoretical definition of "robust", or a practical one? > In other words, do you mean you Python code actually fails more > often than your C++ code, or do you just mean that, theoretically, > the uncertainty with Python destructors makes you feel that your > Python code is less reliable? I mean that it's very much easier for me to write provably correct code in C++. Trying to do the same in Python is an uphill struggle. Furthermore, the C++ version is far more maintainable; the coding style is *intentional*. For big systems with multiple programmers using each other's objects, there's no question that I'd use C++. Of course, for small projects, Python is miles ahead of C++. I'd like to see that advantage extended to large projects as well. I hope that the complications involved in writing C++ code are accidental rather than inherent qualities of a big-system language. > In my experience, and I know also the experience of *many* others, > our Python programs are very much *more* reliable than our C++ > programs. In fact, I've rarely if ever had a Python program that > failed in any way related to Python's destructor behaviour. On > the other hand, I've rarely if ever had a C++ program which did > not crash my entire system at least once during development... "...in any way related to Python's destructor behaviour" is the key part here. Python programs don't fail so much as misbehave. If they don't misbehave (and they're doing anything complicated), the code is often nested several layers deep in try/finally blocks. It's ugly, and hard to maintain. In my experience, the main reason for this is that the onus is on the user of the API to use it correctly. The most trivial examples of this are acquire/release cycles in things like mutexes. There are too many ways in which a user can fail to release a mutex, either through forgetfulness, or through not considering all possible paths of execution (which is difficult to do!). Now, interface contracts can remind the user when he needs to do something, and help to trace a fault, but they don't necessarily make the user's job any easier (or quicker). The C++ community, on the other hand, is working towards ways of *enforcing* API contracts, by reworking the API in such a way that it can't be abused. Again, the mutex is a handy example of this. Consider the following C++ code: class mutex { private: void acquire(); void release(); public: class lock { mutex& m_; public: lock(mutex& m): m_(m) { m_.acquire(); } ~lock() { m_.release(); } }; }; The acquire() and release() methods are private, so the only way to get at them is through the lock class. Ownership of the mutex is thus represented by the lifetime of the lock object. This makes it very difficult for the user of the mutex to abuse the acquire/release cycle. Critics will point out that a devious user could in fact circumvent these guarantees by allocating the lock on the heap. If that be the case: class mutex { private: void acquire(); void release(); class lock_ { /* as before */ }; public: typedef std::auto_ptr lock; lock get_lock() { return lock(new lock_(*this)); } }; Were I to meet anybody who could circumvent such a design after its declaration, I'd probably hire them - after making them promise never to do it again. Regards David Turner From dkturner at telkomsa.net Wed Jun 9 03:29:44 2004 From: dkturner at telkomsa.net (David Turner) Date: 9 Jun 2004 00:29:44 -0700 Subject: Destructors and exceptions References: Message-ID: Hi > When an exception is handled, you can access the stack traceback. This > contains references to all the local variables which were in scope at the > point when the exception was thrown. Normally these variables would be > destroyed when the functions return, but if there is a traceback > referencing them they stay alive as long as the traceback is accessible > which is usually until the next exception is thrown. Then why not unreference the traceback (and therefore destroy it and the down-stack locals, if the exception handler hasn't made another reference) at the end of the handling suite? > If you really want to be sure your objects are destroyed, then use 'del' in > the finally suite of a try..finally. This ensures that the traceback can't > be used to reference the objects that you deleted. As I've pointed out elsewhere, this works but it doesn't address the problem I'm trying to solve. The problem is that it's easier for the user of an object (who didn't create it, and probably hasn't read the documentation) to omit the try/finally construct. Therefore, this is what he will tend to do. I'm looking at what I, as a designer, can do to prevent this from happening. Regards David Turner From dkuhlman at rexx.com Fri Jun 25 19:22:11 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 25 Jun 2004 16:22:11 -0700 Subject: Referring to a list References: <1a0Dc.13333$rh.4819@okepread02> <2k3iptF182qp9U1@uni-berlin.de> Message-ID: <2k3qcqF171ra8U1@uni-berlin.de> Russell Blau wrote: [snip] > > Does this help? > >>>> odd_list = [] >>>> even_list = [] >>>> def which_list(x): > if x % 2 == 0: > return even_list > else: > return odd_list > >>>> for i in range(20): > which_list(i).append(i) > > >>>> odd_list > [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>>> even_list > [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] > > Basically, what this and other replies to your question are telling you is that lists in Python are first-class objects. To be a first-class object means that you can (1) stuff it into a data structure (for example, a dictionary or another list), pass it in to a function, and (3) return it as the value of a function. Also remember that functions in Python are first class, so you do something like this: def do_job(arg, listarg, even_func, odd_func): if arg % 2 == 0: even_func(arg, listarg) else: odd_func(arg, listarg) That makes doing delegation in Python easy and natural. OK. OK. It's not natural, but it's about as natural as something as weird as computer programming is going to get. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From t.p.s.a at gazeta.pl Sat Jun 12 06:38:21 2004 From: t.p.s.a at gazeta.pl (Esmeralda Weatherwax) Date: 12 Jun 2004 03:38:21 -0700 Subject: New Online Judge System for functional languages Message-ID: For 10 days now, a new online judge (a system for the verification of the correctness of submitted programs, which solve problems selected from a repository) has been available to the public. The Sphere Online Judge (SPOJ) is available at spoj.sphere.pl, and supports solutions written in 18 different programming languages including Haskell, Ocaml, Prolog, Icon and Ruby. At present, well over half the problems can be solved in functional languages easily within the time-limit. Soon, source code length will be introduced as an additional criterion. We would be very pleased if you were interested in solving problems at our server, or if you could recommend it to other programmers or students. It is also possible to add problems dedicated to functional programming, so if you were willing to create some new interesting tasks, the development team would be pleased to cooperate. With best wishes, Esme From peter at engcorp.com Wed Jun 9 07:03:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 07:03:47 -0400 Subject: Python "header" files In-Reply-To: <3064b51d.0406081247.17008d43@posting.google.com> References: <3064b51d.0406081247.17008d43@posting.google.com> Message-ID: beliavsky at aol.com wrote: > I wonder how Python projects with multiple programmers can be > coordinated without giving all programmers access to all of the source > code. I am currently working on one-man projects, but I am still > interested in ways of separating interface from implementation. We had over a dozen Python programmers working on the same project and didn't find it particularly a problem that the full source code was available to them. In fact, given that it was an XP environment (Extreme Programming, that is, though it was also a partly WinXP environment) it was a huge advantage over situations where only sketchy and inaccurate documentation was available. In the past, any time I've been limited to header files and the docs I've encountered serious troubles. The header files are often a mess, because of the inherent duplication, inline code makes them even less readable, and the documentation is _never_ maintained properly. -Peter From lbates at swamisoft.com Fri Jun 11 14:03:38 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 13:03:38 -0500 Subject: Finding "hidden" syntax errors Message-ID: It doesn't happen often, but once in a while I will introduce a syntax error into a Python program I'm working on (in IDLE) and doing File-Check responds with the expected "Failed to check, syntax error - invalid syntax". The problem is where the cursor stops is perfectly legal syntax. I then begin going through the laborious job of cutting out pieces of the code until I find what is wrong. Is there some easier way of doing this. I tried pychecker but got nowhere because it said it couldn't import (which I'm sure is because of the syntax error). Does anyone out there have a "better" way of tracking down these difficult to locate errors? Thanks in advance for any hints. Regards, Larry Bates Syscon, Inc. From usenet_spam at janc.invalid Fri Jun 11 14:02:23 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 11 Jun 2004 18:02:23 GMT Subject: urllib IOError Exception References: Message-ID: Bart Nessux schreef: > try: > f = urllib2.urlopen("http://%s" %host) > except urllib2.URLError: > print host, "has no http server on port 80" > > Anyway to speed this up??? The timeout per host is several minutes. socket.setdefaulttimeout(timeout) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jim_kerr at agilent.com Mon Jun 7 17:59:54 2004 From: jim_kerr at agilent.com (Jim Kerr) Date: 7 Jun 2004 14:59:54 -0700 Subject: makepy support for versioning Message-ID: <50626d00.0406071359.6639c42b@posting.google.com> Does makepy always respect versioning of interfaces? It appears as though makepy correctly handles versioning of objects you obtain directly, but not for objects you get via a function call. Here's a simple example to illustrate the point. I created the C++-based server for this example by pilfering some code in Andrew Troelsen's book on COM and ATL. car = Dispatch("ScriptibleCoCar.DualCoCar") person = Dispatch("ScriptibleCoCar.Person") # a Person object carOwner = car.Person # also a Person object Both the Car and the Person classes have two versions, and makepy handles this correctly: >>> car >>> person (Notice the suffix 2 in both cases). OTOH, the Person object obtained via car.Person is a version 1 thingie: >>> carOwner If I try to use QueryInterface to get a reference to a version 2 object, it fails: >>> IID_IPerson2 = "{38332D31-6631-48E9-B62E-449864003395}" >>> carOwner._oleobj_.QueryInterface(IID_IPerson2) Traceback (most recent call last): File "", line 1, in ? TypeError: There is no interface object registered that supports this IID Late binding works fine, however: >>> import win32com.client.dynamic >>> dcar = win32com.client.dynamic.Dispatch("ScriptibleCoCar.DualCoCar") >>> dperson = dcar.Person >>> dperson.Name, dperson.ID, dperson.Address # Address is new in version 2 (u'Phony', 123, u'00 Anywhere Place') I'm kinda stuck here. I could live with using late binding, but the interface I need to use has a lot of properties with parameters, and makepy seems like the easiest way to deal with those. So my questions are: 1) Is there a way around this issue with makepy? 2) If not, is there a way to set the values of properties with parameters using late binding? Thanks for the help! Jim From peter at engcorp.com Mon Jun 14 09:23:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 09:23:28 -0400 Subject: Code density In-Reply-To: References: Message-ID: j_mckitrick wrote: > When I was reading the PEP for code, Guido suggests using blank lines > 'sparingly.' Yet, in most of the 'professional' code(1) I've seen, > there are often HUGE amounts of whitespace, extra blank lines, and so > on. Is this the norm? > > Has python gravitated toward more whitespace in general? I can't speak for "python", but our informal coding standard asked for single blank lines between blocks of code that handled different aspects/steps of a problem, and single lines between functions/methods, and double blank lines between class or function definitions at the module level of indentation. Blank lines are a readability tool as much as clear indentation is. Depending on the definition of "sparingly", this may be the one piece of Guido's advice that we've ever ignored... :-) -Peter From fishboy at SPAMredSPAMpeanutSPAM.com Tue Jun 15 01:42:08 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Tue, 15 Jun 2004 05:42:08 GMT Subject: what about unsigned and signed 8 bits number, 16 bits, etc?? References: Message-ID: <84u0xde5qo.fsf@redpeanut.com> sarmin kho writes: > Hi Pythoners, > > When it is an integer number, what is the range of the integer > number and long integer number?? > > do we have typecasting of 8bits or 16bits signed and unsigned number > in python? > > the python script i m working on would need to typecast the number > it reads from a hardware. this number would then be typecasted > according to its type before further processing. the typecasting is > in form of signed 8bits and 16bits number. how do i do this in > python?? [...] I did something like this in python once. I read all the hardware in unsigned bytes then fed the resulting string into a 'struct'. Easier for me to visualize and let the struct module workout all that byte order cruft. ><{{{*> From lard at tardis.ed.ac.molar.uk Fri Jun 25 10:24:27 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Fri, 25 Jun 2004 15:24:27 +0100 Subject: python image library making dotty gifs In-Reply-To: <2k2j40F174gorU1@uni-berlin.de> References: <10do3bfmr93ke48@corp.supernews.com> <2k2j40F174gorU1@uni-berlin.de> Message-ID: <10dodcrh4eb1j7d@corp.supernews.com> Oliver Fromme wrote: > Alex Hunsley wrote: > > I'm using python image library 1.1.4 (http://www.pythonware.com/products/pil/) > > to plot images. > > However, when I save an image to a gif file, it comes out very dotty/ithered > > looking, even if it's a picture consisting only of one colour! > > [...] > > im = Image.new("RGB", (imageWidth, imageHeight)) > > [...] > > im.save("plotImage.gif", "GIF") > > You're creating an RGB image (i.e. 24 bits per pixel), and > then you're saving it to a GIF file which can handle only > 8 bits per pixel. The GIF file format uses a so-called > palette to map 24bit RGB colors to 8 bits. You haven't > defined any palette, so I guess it's using a default one, > to which it has to convert your image, obviously involving > dithering. > > I'm not a PIL user, so I can't tell you how to define your > own optimized palette with it. > > Another option would be to save the image in PNG format, > which supports 24bits natively. > > Best regards > Oliver > aha! ok. thanks to you and steve for your help! :) alex From sdfATexpertuneDOTcom Wed Jun 30 07:48:30 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Wed, 30 Jun 2004 11:48:30 -0000 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Caleb Hattingh wrote in news:opsadz79x3lvs67r at news.telkomsa.net: > I know emacs and vi/vim are super-powerful, but significant time is > required (for me, I guess) to learn how to use them effectively. > The time invested in learning one of these is paid back forever in ongoing efficiency. Other editors have large and often nice feature sets, but for huge hands-on-the-keyboard power, it's still very hard to beat vim or emacs (Vim for me). Scott From ville at spammers.com Wed Jun 9 03:00:46 2004 From: ville at spammers.com (Ville Vainio) Date: 09 Jun 2004 10:00:46 +0300 Subject: python.org CMS References: Message-ID: >>>>> "aahz" == Aahz writes: aahz> The system needs to work with browsers that have limited aahz> functionality (i.e. Lynx). Isn't the functionality in Lynx a bit *too* limited? For text based browsing there is w3m, which can render legibly a whole lot more web pages... -- Ville Vainio http://tinyurl.com/2prnb From eugene at boardkulture.com Wed Jun 23 16:35:09 2004 From: eugene at boardkulture.com (Eugene Van den Bulke) Date: Thu, 24 Jun 2004 06:35:09 +1000 Subject: Tix Message-ID: Hi everyone, I have read a fair bit about python GUI and was wondering why no one seemed to be mentioning Tix. Is it because it is considered as being implicitly part of Tkinter? Thanks, EuG?Ne From lights at cix.co.uk Thu Jun 24 12:54:35 2004 From: lights at cix.co.uk (Matthew Bell) Date: 24 Jun 2004 09:54:35 -0700 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> Message-ID: <4d79c4d9.0406240854.13489b48@posting.google.com> Les Smithson wrote in message news:... > >>>>> "Matthew" == Matthew Bell writes: > > Matthew> Hi, I'm looking for a high-performance SNMP manager > Matthew> toolkit (SNMPv1 / v2, GET / GETNEXT / GETBULK) I can use > Matthew> with Python on Windows2K/XP. [...deletia...] > > Pysnmp is the only 100% pure Python SNMP implementation I'm aware > of. Perhaps you could address your program's inefficiencies instead? > What are you doing that's so CPU intensive? SNMP agents/managers that > I've worked on (admittedly not using Python) were always I/O bound, > rather than CPU bound. The application is monitoring 30+ big LAN switches with a large variety of information being collected from each one. Using UCD-SNMP then (if we ignore the way it tends to hang sometimes), indeed, I/O is the limiting factor rather than CPU. The Python code I've written that deals with all the data amazes me by how relatively little CPU it consumes (yay for Python!); if I could find a way to get UCD-SNMP to work reliably in a multi-threaded environment then I'd happily carry on using that. But the hanging is getting really frustrating as not even select() seems to be able to catch it. It just hangs. Using PySNMP rather than UCD-SNMP certainly gets round the random hanging, but it does make CPU go through the roof. I'm not actually necessarily looking for a pure Python SNMP toolkit. To be honest, given the large amounts of SNMP traffic that this application has to generate, it would make an awful lot of sense to have the low-level SNMP grunt work done in a C / C++ library and then have the Python code just deal with the processed OIDs and values. It's just that I can't find any such library that'll run on Win32 and that has a convenient Python wrapper. I've got a recollection that I stumbled across a commercial C++ based SNMP library that came with a Python wrapper about a year ago, but no amount of googling has found it again :-( I have found any number of native COM/.NET/ASP/etc C++ SNMP toolkits and tried using the Python Win32 extensions to talk to them but I just don't understand enough about low-level Win32 calls, event handling etc to get them to work, particularly as the code examples typically expect you to either be using Visual C++ or Visual Basic. Thanks anyway, Matthew. From peufeu at free.fr Wed Jun 23 17:23:24 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Wed, 23 Jun 2004 23:23:24 +0200 Subject: String help References: Message-ID: # read all lines in a list lines = list(open(filename)) # remove spaces at beginning and end of lines # if you don't know map, look in the docs, it's useful stripped_lines = map( string.strip, lines ) # another way stripped_lines = [ line.strip() for line in open(filename)] # maybe these is a stripright method ? # as I understand, any line ending with "-" should be merged to the previous one. # as you're a newbie we'll use a generator and an iterator just to motivate you # to read about these useful thingies def mergelines( lines ): it = iter(lines) currentline = lines.next() while 1: lastline = currentline try: currentline = lines.next() except StopIteration: yield lastline return if lastline.endswith('-'): lastline += currentline else: yield lastline # then : for line in mergelines( stripped_lines ): print line # or you could do it the old fashioned way : result = [ stripped_lines[0] ] for line in stripped_lines[1:]: if result[-1].endswith('-'): result[-1] += line else: result.append( line ) Maybe this works, maybe not... try it ? On Wed, 23 Jun 2004 21:36:50 +0100, Rigga wrote: > Hi, > > I am new to python and am working on a script that parses a file and > loads > the results in to variables for processing. I am having problems when it > comes to data in the file that wraps over two lines i.e. > > las - > lomas > > What i want to be able to do is to some how strip all the spaces from it > so while it is contained as a variable so it equal 'las - lomas' > > How do I go about doing this? I have tried it using the > string.strip(myvariable,"") however that doesnt appear to do anything. > > Any help appreciated > > Rigga -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From miki.tebeka at zoran.com Thu Jun 3 02:31:30 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 3 Jun 2004 08:31:30 +0200 Subject: Error in small code In-Reply-To: <200406030454.i534sbQ10955@mailweb05.ibest.com.br> References: <200406030454.i534sbQ10955@mailweb05.ibest.com.br> Message-ID: <20040603063130.GP612@zoran.com> Hello Bruno, > How come it says that pturn is a local variable if it is declared AND > asigned a value in the beggining of the code!?!?! By default Python guesses all variables used in a function are local to the function. Add the line "global pturn" so it'll know `pturn' is a global variable. See http://docs.python.org/tut/node6.html#SECTION006600000000000000000 Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From lbates at swamisoft.com Thu Jun 3 19:44:07 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 18:44:07 -0500 Subject: Newbie: What's wrong with this 6-line script? References: <8COvc.4324$%F2.43@attbi_s04> Message-ID: A known problem in the interpreter. If output lines get too long the "disappear". If you scroll right with mouse by clicking the right arrow, you will see the line "magically" appear. Larry Bates Syscon, Inc. "Brent W. Hughes" wrote in message news:8COvc.4324$%F2.43 at attbi_s04... > If the file Test1.txt contains 257 words, the following script works as > you'd expect. But if Test1.txt contains 258 words, the last line of the > script prints a blank line instead of the words. > ========================== > import sys > f = file("Test1.txt") > s = f.read() > f.close() > t = s.split() > print t > =========================== > BTW, if I run these same lines in the Python interactive shell, it will work > fine even with 20000 words in Test1.txt. > > Is there something simple I don't understand? > > Brent > > From chuck at smtl.co.uk Thu Jun 3 10:08:21 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Thu, 03 Jun 2004 15:08:21 +0100 Subject: How to run email-unpack.py from the Email Message Module. Message-ID: <200406031408.i53E8Leb017763@sevenofnine.smtl.co.uk> Im running $ python email-unpack.py -d /home/chuck/surveyResults What parameters do I use I have tried substituting msgfile fp = open(msgfile) for my given path (/home/chuck/Mail/Inobx) still no joy please explain what im missing Im using the example from http://www.python.org/doc/current/lib/node510.html unpackmail ins't a command So using [option] and msgfile Thus get this prompt> Unpack a MIME message into a directory of files. Usage: unpackmail [options] msgfile Options: -h / --help Print this message and exit. -d directory --directory=directory Unpack the MIME message into the named directory, which will be created if it doesn't already exist. msgfile is the path to the file containing the MIME message. Cheers Sorry for sounding thick please point me in the right direction on howto to use the python script. Thanks From davidf at sjsoft.com Fri Jun 18 05:11:51 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 18 Jun 2004 11:11:51 +0200 Subject: Python mentioned In-Reply-To: References: Message-ID: python newbie wrote: > Page 3 or 3 of this article on XUL (xml-based way of building browser-based > apps in Mozilla), mentions that Python is built in as the scripting > language) > http://www.devx.com/webdev/Article/21350 > > Note that this is talking about somebody else's XUL toolkit, not Mozilla From BELLEMAIL-SA at exponent.com Wed Jun 23 23:53:46 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 20:53:46 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F92@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = bpeng at rice.edu Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 279 Scanning time = 06/23/2004 20:53:46 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment your_text.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From sdahlbacSPAMSUCKS at abo.fi Mon Jun 21 13:27:34 2004 From: sdahlbacSPAMSUCKS at abo.fi (Simon Dahlbacka) Date: Mon, 21 Jun 2004 20:27:34 +0300 Subject: Readable Persistance? In-Reply-To: <2job8pF149mleU1@uni-berlin.de> References: <2job8pF149mleU1@uni-berlin.de> Message-ID: <40d71aab$1@newsflash.abo.fi> Diez B. Roggisch wrote: > Chris S. wrote: > > >>I'm trying to write programs that make use of a lot of dynamic >>structures. To aid in debugging and data extraction, I'd like to persist >>these objects in a form that's readable, but one that also preserves >>handles (ie for lambda expressions, dictionaries, lists, etc). Using the >>pickle module, I can more-or-less accomplish the latter, but not the >>former. YAML can accomplish the former to some degree, but still can't >>represent handles. I understand the inherent difficulties in >>representing complex objects in a human readable format, but is there >>any way to do this with Python? Any help is appreciated. > > > Never actually tried it, but isn't there a xml-variant for pickling? Maybe > that helps you. > > Regards, > > Diez > > http://gnosis.cx/download/Gnosis_Utils-current.tar.gz according to my tests it works nicely as a pickle replacement that is at least a bit more readable than plain old pickle. Not sure if I'd want to edit it by hand though.. /Simon From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Jun 11 12:56:57 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 11 Jun 2004 18:56:57 +0200 Subject: any comments References: <4cec047f.0406110341.1ec84bc2@posting.google.com> Message-ID: Look : https://moin.conectiva.com.br/LunaticPython From michael at stroeder.com Tue Jun 29 09:56:15 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 29 Jun 2004 15:56:15 +0200 Subject: ANN: python-ldap-2.0.1 Message-ID: Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.1 2004-06-29 Changes since 2.0.0: dsml: * Fixed wrong exception message format string ldap.schema.models: * Fixed Entry.__delitem__() to delete really everything when deleting an attribute dictionary item. From gdowdin at cs.clemson.edu Mon Jun 7 13:42:47 2004 From: gdowdin at cs.clemson.edu (Dowding George A) Date: 07 Jun 2004 13:42:47 -0400 Subject: How to bind to a tag in Tkinter Message-ID: Brent B. Welch gives this example in _Practical Programming in Tcl and Tk_. bindtags $t [list ViInsert Text $t all] bind ViInsert {bindtags %W {ViCmd %W all}} bind ViCmd {bindtags %W {ViInsert Text %W all}} I want to do something along those lines. Tkinter provides a bindtags method for each widget, but I can't figure out how to bind to a tag of my creation. Tkinter provides widget.bind, widget.bind_class(), and widget.bind_all(), but from what I can tell there is no way to bind to a tag as the Tcl/Tk example indicates that I should be able to do. What I want to do is add my own tag to the front of the taglist for each widget in a Tkinter application and bind events to that tag so I can record a sequence of events. Hopefully this makes sence. -- http://www.cs.clemson.edu/~gdowdin George A. Dowding, Clemson University Computer Science Dept. G023 Jordan Hall From llothar at web.de Mon Jun 7 08:42:43 2004 From: llothar at web.de (Lothar Scholz) Date: 7 Jun 2004 05:42:43 -0700 Subject: how to get memory info from python? References: Message-ID: <6ee58e07.0406070442.6e8d32fe@posting.google.com> fishboy wrote in message news:... > obmalloc.c also has a LOT of infomation about Pythons memory in > comments. But obmalloc.c has a high performance penalty and can't be recommend for productivity systems that must work on a game console. From feedback at gamespyarcade.com Fri Jun 18 12:00:55 2004 From: feedback at gamespyarcade.com (feedback at gamespyarcade.com) Date: Fri, 18 Jun 2004 12:00:55 -0400 Subject: Hello Message-ID: Important document! -------------- next part -------------- A non-text attachment was scrubbed... Name: Important.zip Type: application/octet-stream Size: 22414 bytes Desc: not available URL: From squirrel at WPI.EDU Sat Jun 26 15:02:39 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Sat, 26 Jun 2004 15:02:39 -0400 Subject: Parameterized Functions without Classes In-Reply-To: References: <2k35g4F14l1o0U1@uni-berlin.de> Message-ID: On Fri, 25 Jun 2004, Peter Otten wrote: > Christopher T King wrote: > > > def partial(func,*args,**kw): > > return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items())) > > In what way is that different from using an ordinary function? > def partial(func, *args, **kw): > def call(*a, **k): > return func(*(args+a), **dict(kw.items()+k.items())) > return call It's not, other than that mine is shorter and less readable :P My point of demonstrating the use of partial() though (this is in response to Christian also) is that along with 2.4 functions such as itemgetter() and attrgetter() and list/generator comprehensions, it will help remove the need for nearly all uses of lambda functions or their equivalent nested functions. From lbates at swamisoft.com Mon Jun 7 18:38:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 7 Jun 2004 17:38:49 -0500 Subject: how to use __str__ and __repr__? References: <2ik7qrFo8httU1@uni-berlin.de> Message-ID: I don't understand what you are trying to do, but the problem is that when you define class 'another' the following line doesn't make sense: middle = " ".join( [ substr.__str__() for substr in self]) The instance of another doesn't have a __str__ method defined (e.g. it's an empty class). All of your other tests have a class that does have a __str__ method because it was inherited from the baseclass list. You could try: class another(list): pass Larry Bates Syscon, Inc. "Jim Newton" wrote in message news:2ik7qrFo8httU1 at uni-berlin.de... > hi all, does anyone know what print does if there is no __str__ method? > i'm trying ot override the __repr__. If anyone can give me some advice > it would be great to have. > > I have defined a lisp-like linked list class as a subclass of list. > The __iter__ seems to work as i'd like, by traversing the links, > and the __repr__ seems to work properly for somethings but not others. > > The basic idea is that a list such as [ 1, 2, 3, 4] is converted to > [1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element > non-destructively onto the beginning of the list; e.g. > > x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]] > y = x.cons(2) --> [ 2, [3, [4, [5, nil]]] > z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]] > > for elt in z: # iterates elt=1, elt=2, elt=3 ... > pass > > I would love to know how to define the __repr__ or __str__ > method so that it is able to print everything the way print > normally works, except that instances of my class gets printed > special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]] > simple as a space seperated list. It works most of the time. > --> ( 1 2 3 4 5) > > Another question is whether there is a way to promote an > empty list [] to an instance of Pair? > > class Pair(list): > > def __iter__(self): > while self: > yield self.car() > self = self.cdr() > > def __repr__(self): > middle = " ".join( [ substr.__str__() for substr in self]) > return "( " + middle + " )" > > # x = (cons x l_y) > # ==> x = l_y.cons(x) > def cons(self, car): > new = Pair() > new.append(car) > new.append(self) > return new > > def car(self): > if self: > return self[0] > return nil > > def cdr(self): > if len(self)<2: > return nil > return self[1] > > nil = Pair() > > > # [ 1, 2, 3] --> [1, [2, [3, nil]]] > def seq2pair(seq): > new = Pair() > for index in xrange( len(seq), 0, -1): > new = new.cons(seq[index - 1]) > return new > > mylist = seq2pair( [1,2,3,4,5]) > print mylist # correctly prints --> ( 1 2 3 4 5) > > > mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist]) > print mylist2 > # correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) ) > > class another: > pass > > print another() # prints --> <__main__.another instance at 0x8132b64> > > # ???????????????????????????????????????? > print seq2pair( [ another(), another() ]) # FAILS > # ???????????????????????????????????????? > > Traceback (most recent call last): > File "xyz.py", line 52, in ? > print seq2pair( [ another(), another() ]) > File "xyz.py", line 13, in __repr__ > return "( " + " ".join( [ substr.__str__() for substr in self]) + " )" > AttributeError: another instance has no attribute '__str__' > From avera at coes.org.pe Mon Jun 28 11:49:05 2004 From: avera at coes.org.pe (Alberto Vera) Date: Mon, 28 Jun 2004 10:49:05 -0500 Subject: socket problem (send infinite...) Message-ID: <002001c45d27$713c9540$1603a8c0@pc22> Hello:I found an example to send data using socket.I did a little change for code you can find in: http://www.python.org/doc/current/lib/socket-example.htmlI want to send a lot of Hello World, but after few seconds I didn't see any new "Hello World" Client side sends 3577 "Hello World" and Server side shows 1800 "Hello World" Could you tell me How I can improve this?Thanks...# Echo client program import socket HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT))#changes!!!j=0while 1: info1 = "*Hello World=\'%s\'"%(str(j)) s.send(info1) j+=1 data = s.recv(1024)s.close() print 'Received', `data` -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at bliemel.ca Tue Jun 1 14:24:12 2004 From: martin at bliemel.ca (Martin Bliemel) Date: Tue, 1 Jun 2004 11:24:12 -0700 Subject: [Vanpyz] Vancouver Python User's Group meeting Tuesday, June 1 References: <40B3882C.6010406@sweetapp.com> Message-ID: <009701c44805$a58500d0$681e0d0a@MOTM> Count me in. I have passed on the invitation to the other members of the Vancouver Knowledge Management Community of Practice (www.kmcop.org). We meet the first Thursday of every month. Topics range from techy stuff like wiki's to organizational behavior related stuff like story telling as a technique to share knowledge. Incidentally the topic for this week's session is communities of practice. Anyone is welcome to attend (see attached). Martin ----- Original Message ----- From: "Brian Quinlan" To: ; Cc: Sent: Tuesday, May 25, 2004 10:53 AM Subject: [Vanpyz] Vancouver Python User's Group meeting Tuesday, June 1 > This meeting: > ============= > > The long-awaited, many times delayed talk by our own Andy McKay: what > is Plone and why is it taking over the world? Afterwards we'll retire > to a nearby pub for the usual informal discussion of Andy's > presentation and the upcoming Vancouver Python Workshop. > > Time: Tuesday, June 1 at 7:00pm > Location: ActiveState (580 Granville St., Vancouver) > > The group: > ========== > > The Vancouver Python and Zope User's Group is a group of Python > enthusiasts who meet once a month to discuss various Python and Zope > technologies and projects. > > For more information about the Vancouver Python and Zope User's Group, > see: http://www.vanpyz.org/ > > For information about the upcoming Vancouver Python Workshop, see: > http://www.vanpyz.org/conference/ > > Cheers, > Brian > > _______________________________________________ > Vanpyz mailing list > Vanpyz at lists.zpug.org > Mailing List: http://lists.zpug.org/mailman/listinfo/vanpyz > Web site: http://www.vanpyz.org > -------------- next part -------------- An embedded message was scrubbed... From: "Wendy Bond" Subject: KMC June Salon Date: Wed, 26 May 2004 11:43:15 -0700 Size: 14525 URL: From maketo at ukato.freeshell.org Fri Jun 25 00:28:42 2004 From: maketo at ukato.freeshell.org (Ognen Duzlevski) Date: Fri, 25 Jun 2004 04:28:42 +0000 (UTC) Subject: Compilers/Interpreters books? References: Message-ID: Hrvoje Blazevic wrote: > Hrvoje Blazevic wrote: >> Are there any good books on Interpreter/Compiler construction, using >> Python as a defining language out there? Something like Essentials of >> Programming Languages 2e ? >> >> I would appreciate some pointers > After 48+ hours without answer, am I to assume that no such books exist, > or that the Python itself is not up to this task? Hi Hrvoje, I am curently writing a flowcharting tool (for C) in Python. It is up to the task. There are many books on compiler construction, some online resources (see the resource on parsing from python.org, there is also a free online book linked from there). I am not sure if there is a book on compiler construction that addresses the implementation in Python though. I think it is more important for you to be familiar with the theory behind compilers and the implementation should then be easier, regardless of the language. Others have already pointed out the basic literature. Ognen From qrczak at knm.org.pl Fri Jun 11 06:53:18 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Fri, 11 Jun 2004 12:53:18 +0200 Subject: The __unicode__ method in the C API, and other __-methods References: <40C93D77.8050800@v.loewis.de> Message-ID: On Fri, 11 Jun 2004 07:04:55 +0200, Martin v. L?wis wrote: >> and on the other hand the implementation >> of tp_getattro of Kogut objects wrapped in Python has a special case, >> only one special case, which checks for "__unicode__" and returns the >> appropriate convert-to-Unicode bound method instead of forwarding the >> attribute access to the original object. > > Why didn't you use Py_FindMethod for that? Because I forward all other method calls to the wrapped object. While I could check if Py_FindMethod raised AttributeError, clear the error, and forward it in this case only - it's an overkill if there is only a single method to intercept, and the majority of cases is forwarded. This would change if I intercepted more methods, i.e. of I made __len__ etc. available as methods. I don't know if providing __len__ is a requirement if sq_length is provided, and if so, if it's somehow possible to avoid wrapping all those methods by hand. For example if a method takes two arguments, its tp/nb/sq/mp slot takes two arguments, while a MethodDef must take and unpack a two-element tuple, as I understand, with ints passed as Python ints rather than C ints etc. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From jacek.generowicz at cern.ch Sun Jun 6 02:47:11 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 06 Jun 2004 08:47:11 +0200 Subject: Optimizing multiple dispatch References: <40C237E5.2040906@charter.net> Message-ID: Howard Stearns writes: > In your Multimethods, is the number of args fixed and known at the time > you first call Multimethod(), or do you need to be able to support dispatching > based on the number as well as the type of the arguments? These multimethods are proxies for C++ functions, so the number of arguments is variable. Thanks for your ideas though: it surprised me to see just how much those timings differ. From pekka.niiranen at wlanmail.com Sat Jun 19 05:57:18 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sat, 19 Jun 2004 12:57:18 +0300 Subject: Help needed: optimizing dictionary creation/access In-Reply-To: References: <40d3e9fa$0$603$39db0f71@news.song.fi> Message-ID: <40d40e5d$0$1776$39db0f71@news.song.fi> Hmm, does not using tuple (name, keyp, cost) as key make access time linear? -pekka- Peter Otten wrote: > Pekka Niiranen wrote: > > >>def update(p_name, p_keyp, p_cost, p_unit, data): >> t = time.asctime() >> if data.has_key(p_name): >> if data[p_name].has_key(p_keyp): >> if data[p_name][p_keyp].has_key(p_cost): >> if p_unit > data[p_name][p_keyp][p_cost][0]: >> data[p_name][p_keyp][p_cost] = [p_unit, t] >> else: >> data[p_name][p_keyp][p_cost] = [p_unit, t] >> else: >> data[p_name][p_keyp] = {p_cost: [p_unit, t]} >> else: >> data[p_name] = {p_keyp: {p_cost: [p_unit, t]}} >> return data >> > > > Untested: > > def update(name, keyp, cost, unit, root): > data = root.setdefault(name, {}) > data = data.setdefault(keyp, {}) > oldunit = data.get(cost, None) > if oldunit: > if unit > oldunit[0]: > oldunit[:] = [unit, time.asctime()] > else: > data[cost] = [unit, time.asctime()] > > return root > > You might consider using a single dictionary with (name, keyp, cost) tuples > as keys. > > Peter > From http Fri Jun 11 20:10:50 2004 From: http (Paul Rubin) Date: 11 Jun 2004 17:10:50 -0700 Subject: Anonymous file closing References: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> Message-ID: <7xwu2doctx.fsf@ruckus.brouhaha.com> Peter Hansen writes: > >> f = open(filename, 'r') > >> try: > >> text = f.read() > >> finally: > >> f.close() > >> > > But the uncertainty remains in case of an anonymous file, doesn't it? > > What's an "anonymous file"? The term means nothing to me... I think it means the file descriptor created in a statement like text = open(filename, 'r').read() It's hard to clean up such a descriptor in a finally clause. From tjreedy at udel.edu Mon Jun 7 08:31:23 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Jun 2004 08:31:23 -0400 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> Message-ID: > > Given those working definitions of "interpreted language" and > "compiled language", your statement seems correct: there are languages > which are both interpreted and compiled[3]. An example of such a > language is Common Lisp; most implementations of Common Lisp systems > include both an interpreter and a compiler for Common Lisp. So is C. At least some unix distributions once had a C *interpreter* for tutorial purposes. TJR From aahz at pythoncraft.com Tue Jun 8 14:28:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 8 Jun 2004 14:28:26 -0400 Subject: Passing parameters using **kargs References: Message-ID: In article , Terry Reedy wrote: > >Or if you don't care, or want to intercept invalid calls. Interestingly, >the OP's example is the beginning of a possible debug wrapper usage where >one either does not have a function's code or does not want to modify it >directly. Possible example: > >_f_orig = f >def f(*largs, **kargs): > print 'f called with' largs, 'and', kargs > f(*largs, **kargs) You mean _f_orig(*largs, **kargs) I prefer this version: def debugParams(func): def debugger(*args, **kwargs): for arg in args: print type(arg), arg for name in kwargs: value = kwargs[name] print name, type(value), value return func(*args, **kwargs) return debugger f = debugParams(f) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From lbates at swamisoft.com Wed Jun 16 19:59:19 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 16 Jun 2004 18:59:19 -0500 Subject: Parse ASCII log ; sort and keep most recent entries References: Message-ID: Here's a quick solution. Larry Bates Syscon, Inc. def cmpfunc(x,y): xdate=x[0] xtime=x[1] ydate=y[0] ytime=y[1] if xdate == ydate: # # If the two dates are equal, I must check the times # if xtime > ytime: return 1 elif xtime == ytime: return 0 else: return -1 elif xdate > ydate: return 1 return -1 fp=file(yourlogfilepath, 'r') lines=fp.readlines() fp.close() list=[] months={'JAN': '01', 'FEB': '02', 'MAR': '03', 'APR': '04', 'MAY': '05', 'JUN': '06', 'JUL': '07', 'AUG': '08', 'SEP': '09', 'OCT': '10', 'NOV': '11', 'DEC': '12'} logdict={} for line in lines: if not line.strip(): break print line pid, name, date, time=[x.strip() for x in line.rstrip().split(' ')] # # Must zero pad time for proper comparison # stime=time.zfill(8) # # Must reformat the data as YYMMDD # sdate=date[-2:]+months[date[2:5]]+date[:2] list.append((sdate, stime, pid, name, date, time)) list.sort(cmpfunc) list.reverse() for sdate, stime, pid, name, date, time in list: if logdict.has_key(pid): continue logdict[pid]=(pid, name, date, time) for key in logdict.keys(): pid, name, date, time=logdict[key] print pid, name, date, time "Nova's Taylor" wrote in message news:fda4b581.0406161306.c5de18f at posting.google.com... > Hi folks, > > I am a newbie to Python and am hoping that someone can get me started > on a log parser that I am trying to write. > > The log is an ASCII file that contains a process identifier (PID), > username, date, and time field like this: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 02AUG03 14:11:20 > 23 jonesjimbo 07AUG03 15:25:00 > 2348 williamstim 17AUG03 9:13:55 > 748 jonesjimbo 13OCT03 14:10:05 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 > > I want to read in and sort the file so the new list only contains only > the most the most recent PID (PIDS get reused often). In my example, > the new list would be: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 17AUG03 9:13:55 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 > > So I need to sort by PID and date + time,then keep the most recent. > > Any help would be appreciated! > > Taylor > > NovasTaylor at hotmail.com From me at privacy.net Mon Jun 7 11:01:14 2004 From: me at privacy.net (Duncan Booth) Date: 7 Jun 2004 15:01:14 GMT Subject: Run child process with stdout and result on Win32? References: <40c47dda$0$17461$afc38c87@news.easynet.co.uk> Message-ID: Dave Sellars wrote in news:40c47dda$0$17461$afc38c87 at news.easynet.co.uk: > Is there really no way to run a sub-process, gather its stdout/stderr, > and collect the return-code, on Win32??? > But that's what the docs say... > > > These methods do not make it possible to retrieve the return code > > from the child processes. The only way to control the input and > > output streams and also retrieve the return codes is to use the > > Popen3 and Popen4 classes from the popen2 module; these are only > > available on Unix. > > Surely not!?!? > > Dave. > > Bizarrely, the return code is returned as the result of the *last* call to the close method on any of the file handles returned. i.e. You must close all of stdin, stdout and stderr handles returned (usually after reading/writing), and the last one you close will return a numeric exit code if the command returned a non-zero exit code. If the command returned a 0 exit code then the final close returns None. >>> from popen2 import popen2 >>> fout, fin = popen2("dir c:\\temp") >>> print fout.close(), fin.close() None None >>> fout, fin = popen2("dir c:\\xxx") >>> print fout.close(), fin.close() None 1 >>> fout, fin = popen2("dir c:\\xxx") >>> print fin.close(), fout.close() None 1 >>> So far as I can see, the documentation omits to mention this little fact (I read the source). From novastaylor at hotmail.com Fri Jun 18 13:51:42 2004 From: novastaylor at hotmail.com (Nova's Taylor) Date: 18 Jun 2004 10:51:42 -0700 Subject: Parse ASCII log ; sort and keep most recent entries References: Message-ID: Wow - thanks for all of your great suggestions. I did neglect to mention that the log file is appended to over time, so the values are already in a time-sequenced sort going in, thus allowing the use of a dictionary as suggested by David and others. This is what I wound up using: sourceFile = open(r'C:\_sandbox\SASAdmin\Python\ServerAdmin\SignOnLog.txt') # output file for testing only logFile = open(r'C:\_sandbox\SASAdmin\Python\ServerAdmin\test.txt', 'w') piddict = {} for line in sourceFile: pid,username,date,time = line.split() piddict[pid] = (username,date,time) pidlist = piddict.keys() pidlist.sort() for pid in pidlist: username,date,time = piddict[pid] # next line seems amateurish, but that is what I am! logFile.write(pid + " " + username + " " + date + "" + time + "\n") More background: I will next merge this log file to process identifiers running on a server, so I can identify "who-started-what-process-when." In Perl I do it this way: $pattern=sas; ## name of application I am searching for # Use PSLIST.EXE to list processes on the server open(PIDLIST, "pslist |") or die "Can not run the PSLIST program: $!\n"; while() { $output .=$_; if (/$pattern/i) { ## collect pids that match pattern into an array, splitting on white spaces @taskList=split(/\s+/, $_); ## Check each value in the Server task list with each row in the log file foreach $proc_val ( @fl ) { chomp($proc_val); ## Remove new line characters at the end. @log=split(/\s+/, $proc_val); if ( $log[0] eq $taskList[1]) { # print">>>>No matches in log Files!!<<<<<<<<<<< \n"; # debug print "$taskList[0] $log[0] $log[1] $log[2] $taskList[5] $log[3] $taskList[8] \n"; $foundIt=1; } } } } close(PIDLIST); So now its more reading to see how to do this in Python! Thanks again for all your help! Taylor From mesteve_b at hotmail.com Thu Jun 17 21:03:23 2004 From: mesteve_b at hotmail.com (python newbie) Date: Fri, 18 Jun 2004 01:03:23 GMT Subject: Python mentioned Message-ID: Page 3 or 3 of this article on XUL (xml-based way of building browser-based apps in Mozilla), mentions that Python is built in as the scripting language) http://www.devx.com/webdev/Article/21350 From has.temp2 at virgin.net Fri Jun 4 10:19:58 2004 From: has.temp2 at virgin.net (has) Date: 4 Jun 2004 07:19:58 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406040619.7aa41dab@posting.google.com> "Eric S. Johansson" wrote in message news:... > having said that, I should probably admit to having created my own web > page template tool. It is a very simple tool based on the opagcgilib.py > Toolkit. You might like to post a link on the python.org wiki for reference: . Seems to be the main place for this kind of info. HTH (p.s. If you try HTMLTemplate, I'd be really interested to hear how it goes.) From rodelrod at hotmail.com Mon Jun 7 06:14:13 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Mon, 7 Jun 2004 12:14:13 +0200 Subject: installing cx_Oracle References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> Message-ID: <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> On Fri, 04 Jun 2004 22:11:06 +0200, David Fraser wrote: > If you really need to get it working with 8.0.x libraries, you could try > converting the call to OCIInitialize() and OCIEnvInit() calls. > You'll need to replace OCITerminate with OCIHandleFree. > In my experience these are the two main changes between 8.0.x and 8.1 > You might find some help from the cx_Oracle authors, but the oracle docs > are fairly good. Thanks, David. I successfully replaced the OCIEnvCreate() call, but still had problems with OCILobCreateTemporary(), OCILobFreeTemporary(), OCIUserCallbackRegister(), OCIUserCallbackGet(), OCI_UCBTYPE_ENTRY, OCI_UCBTYPE_EXIT and OCI_UCBTYPE_REPLACE. This amount of patchwork from my inexperienced hands would be asking for trouble, even if I could get it compiled. An 8i installation, as Aurelio suggested, is unfortunately not an option. I'm now looking into ADO. I think it can fit the bill for my current project, though I'd prefer to use the python DB API 2.0. Rodrigo From claird at lairds.com Wed Jun 23 17:28:28 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 23 Jun 2004 21:28:28 -0000 Subject: how to obtain its ip address ? References: <40d9c75d$0$26573$626a14ce@news.free.fr> Message-ID: <10djtfsru7qeded@corp.supernews.com> In article , Peter Hansen wrote: >marco wrote: > >> I'd search a lot ... but i had not found >> how can i obtain my ip address (when i'm connected to the www) ?! > >You can probably search the archives for this list/newsgroup to >find more complete answers (and hints about how else to solve it), >but the short answer is "you can't". > >The longer answer is that (a) machines can have multiple addresses . . . Even more details appear at . -- Cameron Laird Business: http://www.Phaseit.net From tim.golden at viacom-outdoor.co.uk Thu Jun 24 04:42:17 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 24 Jun 2004 09:42:17 +0100 Subject: Windows XP - cron or scheduler for Python? Message-ID: | I'm trying to have some scripts run periodically on Windows | XP and found the "Task Scheduler" did not execute my scripts. | My scripts are of the form scriptName.py, and will run just | by invoking that name in the Command Prompt. | | Has anyone used the Windows Task Scheduler to run .py | scripts, and if so is there some intracacy to it? | | Is there a more UNIX version of a cron program one can run on Windows? Others have already responded on using the Task Scheduler, and maybe you've already set yourself up that way. There certainly are cron-like programs on Win32 (and, let's face it, it's not hard to write your own). But I'm initially very pleased with Irmen de Jong's Kronos from http://www.razorvine.net/download/kronos.py. As a test, I run the following script -- usually with pythonw.exe to avoid an unncessary console window -- and it pops up every two minutes with a message box. You can obviously do anything you like with the tasks, and you have the choice of interval-based or time-of-day-based tasks. It wouldn't be at all hard to read the info from a crontab-style file at startup (don't know if Irmen's already working on anything like that). import kronos import win32ui def do_reminder (): win32ui.MessageBox ("This is a reminder", "Reminder") s = kronos.Scheduler () s.addIntervalTask ( action = do_reminder, taskname = "Reminder", initialdelay = 0, interval = 120, processmethod = s.PM_SEQUENTIAL, actionargs = [] ) s.start () while 1: try: try: pass except KeyboardInterrupt: break finally: s.stop () TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From has.temp2 at virgin.net Fri Jun 4 10:20:06 2004 From: has.temp2 at virgin.net (has) Date: 4 Jun 2004 07:20:06 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> <69cbbef2.0406021049.41406074@posting.google.com> Message-ID: <69cbbef2.0406040620.163453c@posting.google.com> Duncan Booth wrote in message news:... > I got the impression that your HTMLTemplate was quite similar in concept to > TAL but less powerful (probably deliberately). Certainly it looks as though > most of your constructs map straight onto a very similar TAL expression. Appearances, as they say, can be deceiving. While some of the original inspiration for HTMLTemplate did come from studying Zope Page Templates (particularly the trick of hiding stuff in tag attributes so templates can double as decent page mockups) the two systems are _very_ different in concept and operation: - TAL is based on a custom embedded language that provides basic insertion and flow-control capabilities, allowing TAL templates to pull data from a supplied data source to do their funky page rendering thing. - HTMLTemplate (like PyMeld and Nevow.Renderer) presents a template as a very simple, custom DOM that is built and manipulated completely in Python, the data being pushed into the compiled Template's object model via a simple programmatic API. Admittedly, HTMLTemplate's "compiler directives" do look a lot like TAL expressions, at least to a casual observer, but their similarity is superficial: - TAL directives are responsible for controlling both template construction AND rendering. The only thing your Python scripts do is assemble your source data into TAL-digestible form, then serve it up to the TAL template which will produce the rendered page. - an HTMLTemplate directive is just a simple type declaration and name binding - data used only to construct the template object mode, _not_ to render it. ALL presentation logic is implemented as part of your Python scripts, which then interact directly with the Template object model to produce the rendered page. As to HTMLTemplate appearing "less powerful" than TAL, I suspect this is more a problem of perception than actual implementation. (If anything, would say the opposite was actually true, and HTMLTemplate is probably a good bit more powerful than most other templating systems available.) It's is certainly simple; however, that's not the same thing as "low powered", and in this case Less is _definitely_ More. HTMLTemplate simply doesn't need to provide scads of built-in functionality because it's designed from scratch to integrate seamlessly with Python - allowing you to lever all the power of the Python language and its myriad libraries at a level where most templating engines can't/won't/don't even let you in. Something that seems obvious to me now; but for a very long time (read: several years:p) it wasn't.[1] Ah well, ya live and learn. Hope that clarifies (and if it tempts you to try it, maybe you can let us know how that goes) has [1] It's no coincidence I started HTMLTemplate about the same times I discovered Unix philosophy; i.e. "Keep it small, simple and highly focussed, and design it to play really, really well with others." Best advice ever. Took me three bloated, incomprehensible and appallingly ill-conceived monsters to learn that lesson myself, but fourth time's the charm, eh?;) From adsheehan at eircom.net Thu Jun 10 10:08:31 2004 From: adsheehan at eircom.net (Alan Sheehan) Date: 10 Jun 2004 07:08:31 -0700 Subject: Needing help with m2crypto and certificates Message-ID: I am attempting to send XML data over https using the m2crypto libraries but cannot successfully load and varify certificates for client or server. Has anyone achieved this ? I would appreciate some direction and any code snippets available. Thanks in advance Alan From phrogeeb at hotmail.com Thu Jun 17 03:40:06 2004 From: phrogeeb at hotmail.com (Uri) Date: 17 Jun 2004 00:40:06 -0700 Subject: Scrolling Entry Fields... Message-ID: <8a0bb987.0406162340.27b22a94@posting.google.com> I'm wondering if there's a pre-built widget, or an easy way to create my own widget, in Tkinter, that creates a scrolled set of entry fields that are all right next to eachother, right under a set of labels that is the header. Kind of like the Pmw ScrolledText widget, except that instead of text beneath the headers, there's entry boxes. What I want is to have a user be able to enter as many lines of answers under each heading as they want. Like this: Question1 Question2 QUestion3 Question4 3342 3243 324324 342 3243 324 43243 432 Any suggestions? From gabriel.cooper at mediapulse.com Wed Jun 16 09:22:33 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Wed, 16 Jun 2004 09:22:33 -0400 Subject: (OT) Boa Constructor and Python 2.3.4 In-Reply-To: References: Message-ID: <40D04999.807@mediapulse.com> flupke wrote: >"Lothar Scholz" schreef in bericht >news:hajtc01o1it4ss4npcu5ba6045j7thuvkh at 4ax.com... > > >>On Tue, 15 Jun 2004 10:15:39 GMT, "flupke" >> wrote: >> >> >> >>>Hi, >>> >>>My wxPython is version 2.5.1.5u. >>>Any ideas? >>> >>> >>> >>AFAIK the CVS version only works with wyPython 2.4. >> >> > >Hhhmm. Bummer. I wanted to use it to quickly get a wxPython app >going as i'm pretty new to Python & wxWindows. >Well, i guess i can also "type" :) >Are there any other screen designers (i've tried wxGlade but it >seems a bit limited) > > Just revert your wxPython install down to version 2.4.2. That's what I did, anyway. In the end I found that I was too inept to be able to make Boa-Constructor work and ended up writing it by hand. A big problem I've found with wxPython in general is that the tracebacks it provides never link back to your code. The traceback stays exclusively in the site-packages/wxPython/ directory, which means that if you're relying on Boa Constructor to make your GUI code you'll never figure out what the hell is wrong. Better to either write it yourself or make a dummy project where you test things out on BC then move selected changes over to your app. It's kinda ghetto but it worked for me. Gabriel. -------------- next part -------------- An HTML attachment was scrubbed... URL: From selwyn at aotearoa.is.home.nz Wed Jun 16 05:57:07 2004 From: selwyn at aotearoa.is.home.nz (selwyn) Date: Wed, 16 Jun 2004 21:57:07 +1200 Subject: cross-tabulation pointers Message-ID: hi there, I would like some pointers on a pythonesque way of cross-tabulating an SQL result set. i.e. from the result set below: dept | gender ------------- hr | m hr | f sales | m sales | m should result in this (formatting aside): dept | M | F ------------------ hr | 1 | 1 sales | 2 | 0 I have come across a couple of server-side solutions such as the following from http://www.devshed.com/c/a/MySQL/MySQL-wizardry/1/ mysql> SELECT location, SUM(IF(gender='M',1,0)) AS M, SUM(IF(gender='F',1,0)) AS F, COUNT(*) AS total GROUP by location; However, I am using SQLite and there is no IF function available. Moreover I am hoping that someone may point me towards an undoubtedly more pleasant python solution ;-) thanks heaps, Selwyn From peter at engcorp.com Tue Jun 29 12:04:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 12:04:35 -0400 Subject: sending of mail (smtp) - connection refused - but smtp server In-Reply-To: <10e2vs06fabvrc5@corp.supernews.com> References: <10e2v1446n95e4b@corp.supernews.com> <10e2vs06fabvrc5@corp.supernews.com> Message-ID: <35-dnRyKU-aIDnzdRVn-gw@powergate.ca> Alex Hunsley wrote: > I've just discovered something interesting. > If I completely miss out connect() and close(), it works! > i.e. my code now reads: > > s = smtplib.SMTP('192.168.1.105') > #s.connect() > s.sendmail(me, [you], msg.as_string()) > #s.close() > > > and this works! Is it a bad state of affairs to leave things in? Oh, silly me! I should have seen this the first time. This is exactly what you should expect, since the call to the SMTP() constructor calls its self.connect() method automatically if you specify the host argument! The docs for smtplib say these things near the top: '''If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization. ''' '''For normal use, you should only require the initialization/connect, sendmail(), and quit() methods. An example is included below.''' To clean things up, you should be calling .quit() instead of .close(), although in actual fact they basically do the same thing. (Check the source in smtplib.py to learn more.) -Peter From heikowu at ceosg.de Fri Jun 4 19:01:23 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 5 Jun 2004 01:01:23 +0200 Subject: Python reference In-Reply-To: <2ic34fFl7uinU1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2ic34fFl7uinU1@uni-berlin.de> Message-ID: <200406050101.23570.heikowu@ceosg.de> Am Freitag, 4. Juni 2004 22:07 schrieb Reiner Block: > really great this documentation. I'm searching and > searching for two possibilities: test if a string is a number (integer) or > to strip leading and trailing blanks. But it is impossible to find in the > documentation how to do it. :-( Really: I never saw a worse docu as this > one. I don't really know how you're looking for what you need... Stripping leading and trailing blanks is something that has to do with string manipulation. Go and check: Library Reference -> String Type, and you'll soon find str.strip(). About testing whether something is an integer: As always in Python, try to do what you're doing, and test whether it succeeds. y = "123a" try: x = int(y) except ValueError: print "Not a number." HTH! Heiko. From siona at chiark.greenend.org.uk Tue Jun 29 09:39:19 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 29 Jun 2004 14:39:19 +0100 (BST) Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: A.M. Kuchling wrote: >It seems much simpler to choose PostgreSQL (or perhaps Firebird) instead of >MySQL; neither database presents such an irritating licensing issue. Unless your target platform is Windows, in which case Postgres presents an even more irritating licensing issue, in that not only do you need a licence, but you need to decide who you're going to get it from. (Compatability of Firebird's SQL with any existing SQL you have lying around is another matter which is giving me a major headache at the moment.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From sorry at but.no.spam Wed Jun 2 10:21:55 2004 From: sorry at but.no.spam (Juho Saarikko) Date: Wed, 02 Jun 2004 17:21:55 +0300 Subject: PythonMagick compilation problem Message-ID: Has anyone succesfully compiled the PythonMagick 0.5 ? It seems impossible to get compiled succesfully against either ImageMagick 5.5.7-20 or GraphicsMagick 1.1.1. I get the following error when trying to import it in programs: Traceback (most recent call last): File "./image.py", line 4, in ? import PythonMagick File "/usr/local/lib/python2.3/site-packages/PythonMagick/__init__.py", line 9, in ? from _PythonMagick import * ImportError: No module named _PythonMagick And sure enough, the _PythonMagick.so -file is nowhere to be found. However, there is a directory of such name, with a large number of .o files there, which could presumably be used to create the library, if I knew how. Or, alternatively, does anyone knwo any other interface to ImageMagick from Python ? From a.schmolck at gmx.net Thu Jun 3 07:37:37 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Thu, 03 Jun 2004 12:37:37 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406022026.954155e@posting.google.com> Message-ID: hungjunglu at yahoo.com (Hung Jung Lu) writes: > Alexander Schmolck wrote: >> [1] Here are a few of the hacks I'm using, in case anyone might >> find them useful -- or even better tell me about better >> alternatives (If someone has cooked something reasoable >> for reloading modules, I'd love to hear about it). > > I have already answered to you on one previous occasion, Sorry, maybe I missed it (at the time I had no access to a reliable newsserver, so many articles didn't show up). > and told you another time in this present thread. Yep, I've guessed correctly that your mention of weakrefs alluded to a technique along those lines -- I haven't finished my reply to your article yet as I sunk quite a bit of time on debugging IPython yesterday. > I've used this kind of trick in wxPython. It's good for interactively > developing widgets, without re-starting your program. > > Now here is a third try. :) Thanks for your trying again, I've only had time for a glance but this looks quite neat -- I notice that it has evolved a bit since your original posting :) So far I have shied away from a metaclass based solution, as I got by with the simple hack I posted and this hack doesn't require modifications to source code. Another reason was that metaclasses don't combine well, but since I haven't ended up using metaclasses much so far that might not be a problem. So thanks for posting this, it looks quite useful. 'as From brian at sweetapp.com Tue Jun 15 11:26:25 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 15 Jun 2004 17:26:25 +0200 Subject: ANN: Vancouver Python Workshop - Talk deadline extended Message-ID: <40CF1521.5040901@sweetapp.com> What's new? =========== The deadline for talk submission for the Vancouver Python Workshop has been extended until June 22nd. This is mainly due to schedule disruptions caused by the EuroPython conference but also because we are looking for a more diverse group of speakers i.e. not just Python luminaries. So far, we have received many interesting talk submissions, concerning: o Windows programming in Python o MacOS X programming in Python o Python IDE construction o Zope/Plone (custimization, working with DBs, debugging, etc.) o Python's future o Python programming techniques (optimization, constaints, blocks and views, etc.) o Pyrex o Prothon o Pygame o Twisted o Python in business Speakers include: o Guido van Rossum (the creator of Python) o Paul Everitt (co-founder of Zope Corp) o David Ascher (author of "Learning Python" & "The Python Cookbook") o Andy McKay (author of "The Definitive Guide to Plone") o Kevin Altis (wxPython & PythonCard developer) o Paul Prescod (core Python developer - XML libraries) o Trent Mick (core Python developer - logging & 64-bit port) But we would like more typical Python programmers to submit talks as well! To submit a talk, see: http://www.vanpyz.org/conference/registration/submissions.html For general conference information, see: http://www.vanpyz.org/conference The revisted deadline for talk submission is June 22nd. About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Talk submissions: until June 22nd Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian _______________________________________________ Vancouver Python Workshop mailing list Vpw at agmweb.ca http://agmweb.ca/mailman/listinfo/vpw From maxm at mxm.dk Thu Jun 17 18:35:58 2004 From: maxm at mxm.dk (Max M) Date: Fri, 18 Jun 2004 00:35:58 +0200 Subject: calculate a colour gradient In-Reply-To: References: Message-ID: <40d21ce9$0$269$edfadb0f@dread12.news.tele.dk> Paul McGuire wrote: > What about: > scale R from 255 to 0 > scale B from 0 to 255 (or compute as 255-R) > hold G constant (try values like 0, 64, and 128 to brighten or darken the > resulting reds and blues) Or just use the websafe colors: http://www.lynda.com/hexpalette/images/nhue2.gif They basically us any combination of R,G,B with the values 00,11,22... to ...DD,EE,FF Easy to calculate and figure out. regards Max M From godoy at ieee.org Wed Jun 9 16:31:54 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 09 Jun 2004 17:31:54 -0300 Subject: Priting Out in COLOURS References: Message-ID: On Qua 09 Jun 2004 15:09, Satish Chimakurthi wrote: > Hi All, > > This must be a simple thing to do, but am not sure about it. I like to > know how I can print my statements out, in colour. > > Example: print 'PYTHON IS VERSATILE' > > By default, this statement prints out in BLACK. What if I need to change > it's colour ?? Here it prints out in white, but this is how the terminal comes configured to. To use colors you can try printing ANSI codes to an ANSI enabled terminal or use some module that will do the hardwork for you. NCurses come to my mind... -- Godoy. From michael at foord.net Wed Jun 9 10:08:24 2004 From: michael at foord.net (Fuzzyman) Date: 9 Jun 2004 07:08:24 -0700 Subject: .idlerc directory - windoze Message-ID: <8089854e.0406090608.207945f3@posting.google.com> I use Python at work on a windoze computer that logs onto our network. Unfortunately our network screws up from time to time and messes with my profile. I use IDLE as my IDE (tried various... IDLE does more of what I want than any others). It's just started creating a directory called '.idlerc' in the directory of any file I try to edit... Is this because some environment variable has got screwed up ? Any suggestions... it's very annoying. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From tjreedy at udel.edu Tue Jun 8 09:39:45 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 09:39:45 -0400 Subject: Callbacks to generators References: <_Zhxc.27159$sS2.784227@news20.bellglobal.com> Message-ID: "Humpty Dumpty" wrote in message news:_Zhxc.27159$sS2.784227 at news20.bellglobal.com... > Something weird here. I hven't used generators much, but seems to me that: > > 1) you maybe don't need them: > > def process_iter(text): > def on_token(token): > return token > process(text, on_token) True. And one cannot use them for 2.1. I expect OP wants to use iterators in 2.2+ to avoid repeated function call overhead. The main problem is writing code that works both ways. > 2) you need some sort of while loop so the fnction doesn't return after the > first yield: True. however... > def process_iter(text): > def on_token(token): > while 1: > yield token This is garbled and repeats OP's mistake of making token a param of the generator function. A generator function is called once and its parameter is used to set up the generator whose next method is what gets called repeatedly. See my previous post for a possibly workable example. Terry J. Reedy From http Fri Jun 25 18:07:45 2004 From: http (Paul Rubin) Date: 25 Jun 2004 15:07:45 -0700 Subject: eZ80 - correction [z80 vs Python thread] References: Message-ID: <7xllib8f66.fsf@ruckus.brouhaha.com> "Janusz U." writes: > I have an idea that implements the Python interpreter for eZ80 as an > universal flexible language (like scripts) to support attached hardware. > What would it be shortest way to do it? > I think of course about C (Zilog has good support of own products...). I think Python is too large a language for such a small processor. Among embedded developers, FORTH is a favorite script language since implementations can be extremely compact and efficient. There are several Z80 implementations already existing. Programming in Forth is pain compared to Python though, in my opinion. To horrify Python and Forth fans simultaneously, I once implemented Forth in Python, where every Forth word compiled to a Python function closure. But on a Z80 you wouldn't do anything like that. From jdhunter at ace.bsd.uchicago.edu Sun Jun 13 12:57:01 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 13 Jun 2004 11:57:01 -0500 Subject: Limits on number of classes? In-Reply-To: <889cbba0.0406130859.7e2fc2da@posting.google.com> (klachemin@home.com's message of "13 Jun 2004 09:59:02 -0700") References: <889cbba0.0406130859.7e2fc2da@posting.google.com> Message-ID: >>>>> "Kamilche" == Kamilche writes: Kamilche> My design reqires hundreds of classes, maybe over a Kamilche> thousand. Can Python handle that? Will there be a speed Kamilche> hit? Just wondering if anyone had hit the limits of Never heard of such a problem. Here's a little script that creates 10000 classes; doesn't seem to strain python for i in range(10000): exec('class C%d: pass'%i) c = C1234() c.x = 1 print c.x From uscode at dontspam.me Tue Jun 29 16:47:08 2004 From: uscode at dontspam.me (USCode) Date: Tue, 29 Jun 2004 20:47:08 GMT Subject: wxPython support non-GUI classes from wxWidgets? Message-ID: I've been poking around the wxPython website and am unclear if wxPython has a wrapper for ALL wxWidget classes or just the GUI-related classes? Does wxPython also provide a python wrapper for the wxWidget non-GUI classes such as: ODBC, printing, threading, interprocess communication, XML, streams, etc. I realize Python provides many of these facilities natively but through wxPython, can I use the wxWidget versions instead? Thanks! From BELLEMAIL-SA at exponent.com Thu Jun 24 02:32:49 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 23:32:49 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F9A@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = blacksunprod at hotmail.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 294 Scanning time = 06/23/2004 23:32:49 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment Part-2.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From holbertr at dma.org Fri Jun 11 08:36:05 2004 From: holbertr at dma.org (Rick Holbert) Date: Fri, 11 Jun 2004 08:36:05 -0400 Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> <40c8e44f$0$36860$e4fe514c@news.xs4all.nl> Message-ID: So, something like this? x = 2**2436583 - 1 while x > 0: print x%10, x/=10 Aahz wrote: > In article <40c8e44f$0$36860$e4fe514c at news.xs4all.nl>, > Irmen de Jong wrote: >>Daniel Yoo wrote: >>> >>> >>>x = 2**2436583 - 1 >>[...] >> >>> >>>(x / 10) % 10 >>> >>> 0L >>> ### >>> >>> At least we can figure out that the number ends with a '07'. If we >>> continue this way, we can quickly get the other digits. >> ^^^^^^^ >>Sadly, no you can't. Just try it ;-) >> >> >>> i=1 >> >>> while True: >>... print (x/i)%10, >>... i*=10 >>... >>7 0 4 9 6 9 5 4 4 4 1 8...... slower and slower..... > > You should perform destructive division. -- o From tim.golden at viacom-outdoor.co.uk Thu Jun 3 04:25:20 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 3 Jun 2004 09:25:20 +0100 Subject: two silly questions Message-ID: | I have written a program that polls an email account, then pulls down | the email | | I am using win2k. | | the two questions are: | | 1. when i want the program to run in a loop, ie. poll the pop3 | account every 60 seconds, it runs the first time, then it goes into | 'not responding mode' thereafter, sometimes. Any thoughts? I was | using sleep(60) but it just hangs, as i said before, it does not | always do that either! We really could do with a code fragment here. For example, the following (entirely artificial) example runs fine in the Python interpreter on my win2k machine. (I don't use the PythonWin or any other Python shell): import time while 1: print "Still waiting..." time.sleep (10) I realise that your program is more complex than this, but I wanted to illustrate that (a) time.sleep works as expected on Win2K and that (b) some code examples could help. | 2. I wish to use this program at work, I took in an earlier version | yesterday that just wrote the data to a text file, I wanted to make | sure the polling thing worked. on microsoft exchange [i know that it | should, but you never know!!] and it does . When i was there, i | managed to get the code to run just by double clicking on the code | ICON, seem to remember doing something with 'open with' can't seem to | do it here at home. | | Both systems run win2k. did i do something sublimilally without | realising it? what did i do i cannot remember, i have tried opening | with etc. when i do this all get is a burst of the 'black windows | box' just in the same way as putting in 'cmd' on the run thing, Have a look at the Python FAQ for Windows: http://www.mirror.ac.uk/sites/ftp.python.org/pub/www.python.org/doc/faq/wind ows.html which I think answers your question. If not, then post again and see if someone can't help you out. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From michele.simionato at poste.it Fri Jun 18 02:40:20 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 17 Jun 2004 23:40:20 -0700 Subject: Code density References: Message-ID: <95aa1afa.0406172240.651a443d@posting.google.com> j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > Peter Hansen wrote in message > Blank lines are a readability tool as much as clear indentation is. > > Depending on the definition of "sparingly", this may be the one > > piece of Guido's advice that we've ever ignored... :-) > > I've found myself using even more blank lines in python than C++. But > if you look at BitTorrent, for example, the author claims blank lines > are a nuisance. He writes very dense code, but I wonder if it would > be easily maintainable by anyone besides him. > > > jonathon He also does not use docstrings. I think BitTorrent code is not typical in this respect. Look at the code in the standard library if you want to see how the core Python developer write. Reading the modules written by Tim Peters is especially entertaining (lots of and LOL remarks ;) I also would take them as examples when teaching clarity in coding. Michele Simionato From lard at tardis.ed.ac.molar.uk Thu Jun 3 09:55:32 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Thu, 03 Jun 2004 14:55:32 +0100 Subject: printing something without a newline OR a space after it? In-Reply-To: References: <10bu9hm1e03cved@corp.supernews.com> Message-ID: <10bubelh1mnq95e@corp.supernews.com> Matteo Dell'Amico wrote: > Alex Hunsley wrote: > >> .. whereas I want no newline and no space: >> >> >> stuff here,more >> >> How is this done? > > > sys.stdout.write('foo') > thankyou! alex From elbertlev at hotmail.com Fri Jun 18 10:20:57 2004 From: elbertlev at hotmail.com (Lev Elblert) Date: 18 Jun 2004 07:20:57 -0700 Subject: shared file access in python Message-ID: <9418be08.0406180620.3e64be96@posting.google.com> Does Python allow to open files in shared mode like fsopen or _open do? If not how to make it happen? From gry at ll.mit.edu Sat Jun 26 18:44:36 2004 From: gry at ll.mit.edu (george young) Date: 26 Jun 2004 15:44:36 -0700 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? References: <78b6a744.0406250737.310f31da@posting.google.com> <10dpicb9rjib2bb@news.supernews.com> Message-ID: <78b6a744.0406261444.2704ba99@posting.google.com> "John Roth" wrote in message news:<10dpicb9rjib2bb at news.supernews.com>... > "george young" wrote in message > news:78b6a744.0406250737.310f31da at posting.google.com... > > [Python 2.3.3, x86 linux] > > I had developed the habit of using the neat python form: > > if someinstance: > > someinstance.memb() > > > > because it seems cleaner than "if someinstance is not None". > > {please no flames about "is not None" vs. "!= None" ...} > > > > This seemed like a good idea at the time :(). Twice, recently, > > however, as my > > app grew, I thought, hmm... it would make things clearer if I gave > > this container class a __len__ member and maybe a __getitem__. Great, > > code looks > > nicer now... crash,crash, many expletives deleted... > > > > Its great to be able to say containerinstance[seq] instead of > > containerinstance.steps[seq], but I've also changed the semantics of > > (containerinstance) in a boolean context. My app breaks only in the > > seldom case that the container is empty. > > > > Obviously I know how to fix the code, but I'm wondering if this isn't > > a message > > that "if containerinstance:" is not a good coding practice. > > Almost. The message is that testing for None, however > you're doing it, is a Code Smell in the sense defined in > the Refactoring book. If some attribute is supposed to have > a Foo object, then it should have a Foo or a subclass of > Foo, not None. > > Sometimes there's no way around it, but whenever you find > yourself testing for None, consider using a Null Object instead. > A Null Object is a subclass of the normal object you would > be expecting, but one that has methods and attributes that > handle the exceptional case cleanly. > > Of course, there are a couple of very pretty idioms for > handling optional parameters that depend on tests for None, > but they're definitely special cases, and they also break if the > real parameter can be False. Null Object seems like a perfect fit for this. I was unaware of it. I read the original GOF book, but not much since then on patterns. Thnks very much! -- George From bart_nessux at hotmail.com Wed Jun 16 13:11:03 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 13:11:03 -0400 Subject: list to dict In-Reply-To: <20040616162334.0000082d@titan> References: <20040616162334.0000082d@titan> Message-ID: <40D07F27.7020003@hotmail.com> Josef Dalcolmo wrote: > on Wed, 16 Jun 2004 09:29:23 -0400 > Bart Nessux wrote: > > >>What is the easiest/fastest way to build a dictionary from a list? The >>list contains 100,000 entries. > > > The first question would be, what should the keys be? If the list consists of unique, unmutable items, then you might use the items themselves as key and write: > > mydict = dict(zip(mylist, mylist)) > > obtaining a dictionary with all the keys and values identical (therefore somewhat of a waste, but occasionally useful). Note: if your original list did not contain unique values, you end up with a set. > > If you want to remember the original order of the list, then write > > mydict = dict(zip(mylist, xrange(len(mylist)))) > > > If you don't care about the key (that would be strange) then you can write: > > mydict = dict(zip(xrange(len(mylist)), mylist)) > > Instead of len(mylist) you can also write 1000000 or any other number larger than your list. > > > - Josef Josef, This was great. I understand how this works now. Thanks for such a broad, yet applicable explanation! Bart From michael at foord.net Thu Jun 10 06:20:37 2004 From: michael at foord.net (Fuzzyman) Date: 10 Jun 2004 03:20:37 -0700 Subject: .idlerc directory - windoze References: Message-ID: <8089854e.0406100220.71da7d22@posting.google.com> "Batista, Facundo" wrote in message news:... > [michael at foord.net] > > #- I use IDLE as my IDE (tried various... IDLE does more of what I want > #- than any others). It's just started creating a directory called > #- '.idlerc' in the directory of any file I try to edit... Is this > #- because some environment variable has got screwed up ? > > ALWAYS worked for me in that way. I'm on w95. > > I would want to IDLE to open a .idlerc directory in only ONE place, and > not > everywhere. > > . Facundo > I'd rather it didn't behave like this as well ! It's only just started doing it though and I suspect it has something to do with my user profile getting screwed up.... I use XP. Regards, Fuzzy > > > > > . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . > . . . > . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . > . . . > . . . . . . . . . . . . . . . > ADVERTENCIA > > La informaci n contenida en este mensaje y cualquier archivo anexo al > mismo, > son para uso exclusivo del destinatario y pueden contener informaci n > confidencial o propietaria, cuya divulgaci n es sancionada por la > ley. > > Si Ud. No es uno de los destinatarios consignados o la persona > responsable > de hacer llegar este mensaje a los destinatarios consignados, no est > autorizado a divulgar, copiar, distribuir o retener informaci n (o > parte de > ella) contenida en este mensaje. Por favor notif quenos respondiendo > al > remitente, borre el mensaje original y borre las copias (impresas o > grabadas > en cualquier medio magn tico) que pueda haber realizado del mismo. > > Todas las opiniones contenidas en este mail son propias del autor del > mensaje y no necesariamente coinciden con las de Telef nica > Comunicaciones > Personales S.A. o alguna empresa asociada. > > Los mensajes electr nicos pueden ser alterados, motivo por el cual > Telef nica Comunicaciones Personales S.A. no aceptar ninguna > obligaci n > cualquiera sea el resultante de este mensaje. > > Muchas Gracias. > > -- From raoulsam at yahoo.com Fri Jun 18 14:49:13 2004 From: raoulsam at yahoo.com (Raoul) Date: 18 Jun 2004 11:49:13 -0700 Subject: can i define a new method at runtime? Message-ID: <7b22ae5b.0406181049.479d1a61@posting.google.com> I have a GUI application where I want to assign validation methods to controls. If my control myTextBox has a change() event for on change and I want to make it verify the input is an integer I could do... def myTextBox.change(): verifyInteger(myTextBox.Value) def verifyInteger(x): try: string.atoi(x.value) except ValueError : message(x," needs to be an integer") x.setFocus() but i have literally hundreds of these things to do.... I'd like to be able to say somethign like myTextBox.change = lambda x : verifyInteger(x) so when i initialize my form i'd like to run through a list that looks like [["controlName1","verifyInteger"],["controlName2,"verifyFloat"],["controlName3 "verifyInteger"] but i can't seem to make this work. I've tried to use exec("def foo = lambda x: do something....") but that doesn't seem to work.... Got any ideas ??? From viking_kiwi at yahoo.poofters.com Mon Jun 21 23:37:05 2004 From: viking_kiwi at yahoo.poofters.com (Rod Stephenson) Date: 22 Jun 2004 04:37:05 +0100 Subject: threads, sockets, pyopengl, pickle (and tkinter...) Message-ID: I am developing an engineering application for modelling multiphase flows in large pipe networks, and have just discovered the joy of pyopengl for 3D visualization. However the incantation I'm using - with glut on Windows - doesnt coexist well with other python gui's - glutMainLoop() appears not to work alongside tkinter.mainloop(). (I tried putting them in separate threads but no success there either) The issue has been raised in various discussions here in the past with no satisfacory resolution as far as I can see, though Togl has been suggested - but all I can find on the project page is c-source code, havent managed to get the demo Togl stuff in the pyopengl installation to work. Anyway, I've tried another avenue of attack - running the visualization portion in a separate application to the design/computation part, and communicating by sockets, this has a useful advantage that the two parts of the application can run on different machines if needed. So when I want to update the display, the design app packages up the drawing data into a display list (just a python list in fact with each entry an instruction to draw a particular element, colors etc), then pickles the thing up and send it through the socket. At the other end the display app reads from the socket - this runs in a separate thread, unpickles the data and puts it in a global variable which the gl drawing function can access. The two relevant routines and the stuff to fire everything off are appended. (doGlutMain() sets up all the gle stuff and sets glutDrawFunction() with DrawStuff) This *almost* works, except that things block until I generate some event in the OpenGL display window - even just giving it the focus after sending off some data. I'm not quite sure how to rectify this - any suggestions would be appreciated. Perhaps doing something with the glutIdleFunction()? And am I doing the right thing with the lock stuff? Finally could someone confirm that pickled data never contains a "." character apart at the end of the string (I use this as a delimiter in the socket communiction.) There was an old posting (from Guido himself) that seemed to imply this. Thanks rs # draw routine def DrawStuff(): global lock glPushMatrix() someGLStuff() lock.acquire() if dList: for z in dList: draw(z) lock.release() glPopMatrix () glutSwapBuffers () # Server program def getData(): global lock, dList HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() try: while 1: data="" while data[-1:] != ".": data += conn.recv(4096) try: z = cPickle.loads(data) lock.acquire() dList = z lock.release() glutPostRedisplay() print len(z) conn.send("OK") except: conn.send("rsnd") except: conn.close() thread.start_new_thread(getData, ()) time.sleep(.1) doGlutMain(DrawStuff) -- Bruce Rule 1. From mseefelt at bellsouth.net Wed Jun 2 11:03:34 2004 From: mseefelt at bellsouth.net (Michael R Seefelt) Date: Wed, 2 Jun 2004 11:03:34 -0400 Subject: C-program->Python->mxDateTime Problem Message-ID: <000001c448b2$ca7ceda0$10e1020a@mrsd0a4vwr2uhw> I have written a simple C-program that loads a Python Function that connects to a PostgreSQL database> When I only load and execute the Python function all works OK. If I call the Python function a second time I get the following: Called PyObject_CallObject Traceback (most recent call last): File "/home/mike/src/arthur/query_server/query_analyzer/Query_Analyzer.py", line 25, in processQuery from pyPgSQL import PgSQL File "/usr/local/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 388, in ? raise ImportError, \ ImportError: You need to install mxDateTime (http://www.egenix.com/files/python/eGenix-mx-Extensions.html) Any ideas? Thanks, Mike Here is the code: (hope it helps) If I call testQuery 1 time and exit all works, call it a second time and the above error occurs #include #include static char theResults[1024]; PyObject *BuildValue(char *query) { PyObject *pDict; printf("BuildValue\n"); pDict = Py_BuildValue("{s[{ss}]sssssssss[{ssss}]}", "from","tablename","a", "full_sql","select a.id from a", "command","select","from_sql","from a","select_sql","select a.id", "select","columnname","id","tablename","a"); return pDict; } char *testQuery(char *user, char *query) { char *results = "Select \'Error processing sql\'"; PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue, *pResults; PyObject *pQuery; char *LoadModule = "Query_Analyzer"; char *LoadFunction = "processQuery"; pDict = NULL; printf("testQuery enter\n"); Py_Initialize(); pName = PyString_FromString(LoadModule); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pDict = PyModule_GetDict(pModule); /* pDict is a borrowed reference */ pFunc = PyDict_GetItemString(pDict, LoadFunction); /* pFun: Borrowed reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New( 2); // two parms user/query // Set user parm pValue = PyString_FromString(user); PyTuple_SetItem(pArgs, 0, pValue); // Build the QUERY Dictionary //pDict = Ablddict(parsetree_list, query); // pQuery = PyString_FromString("our_query"); pQuery = BuildValue(query); printf("Calling PyTuple_SetItem(pArgs, 1, pQuery);\n"); PyTuple_SetItem(pArgs, 1, pQuery); printf("Called PyTuple_SetItem(pArgs, 1, pQuery);\n"); // Call the Python module // elog(LOG,"Calling PyObject_CallObject"); printf("Calling PyObject_CallObject\n"); pResults = PyObject_CallObject(pFunc, pArgs); // pResults = PyString_FromString("select mike from seefelt"); // elog(LOG,"Called PyObject_CallObject"); printf("Called PyObject_CallObject\n"); Py_DECREF(pArgs); Py_DECREF(pFunc); // Py_DECREF(pValue); if (pResults != NULL) { //results = query; if ( PyString_Check(pResults) ) { sprintf(theResults,"%s\n",PyString_AsString(pResults)); results = theResults; } else { printf("Opps not a PyString\n"); } Py_DECREF(pResults); } else { Py_DECREF(pModule); PyErr_Print(); // elog(LOG,"Call failed\n"); return results; } /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ } else { if (PyErr_Occurred()) PyErr_Print(); // elog(LOG, "Cannot find function \"%s\"\n", LoadFunction); sprintf(theResults, "SELECT 'Cannot find function \"%s\"'", LoadFunction); } Py_DECREF(pModule); } else { PyErr_Print(); // elog(LOG, "Failed to load \"%s\"\n", LoadModule); sprintf(theResults, "Cannot find function \"%s\"\n", LoadModule); return results; } Py_Finalize(); free( pModule ); return results; } /* for testing */ int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; int i,j; i = 1; if ( argc > 1 ) i = atoi(argv[1]); for (j=0;j>>>>>>>>>>>>>>>>>>>>>>>>>> PASS %d\n",j+1); testQuery("MIKE","select a.id from a"); } return 0; } From ykingma at accessforall.nl Tue Jun 15 17:20:15 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Tue, 15 Jun 2004 23:20:15 +0200 Subject: does python have useless destructors? References: Message-ID: <40cf680f$0$140$e4fe514c@dreader17.news.xs4all.nl> David Turner wrote: > "Delaney, Timothy C (Timothy)" wrote in message news:... >> David Turner wrote: >> >> > This will be a pain for the Jython implementers. However, it is >> > doable. Note that I never said the objects couldn't be garbage >> > collected, just that del had to be called at certain well-defined >> > times. What this will involve is the Jython compiler inserting a lot >> > of implicit try/finally constructs. >> > >> > Can anyone see a reason why this scheme wouldn't work? >> >> Yes - Jython cannot know about references to objects created *in Java >> code*. It is therefore impossible for Jython to maintain reference >> counts when an object is passed to Java (i.e. non-Python) code. >> > > Thank you, Tim, that's the first substantial objection I've heard :-). > > So, if Java code makes use of a Python object with __del__, all bets > are off. This is certainly a limitation, but I'm not sure that it's a > very serious one, as RAII objects tend to be used in localized > contexts. It's not that all bets are off. In Jython the __del__() method is called from java.lang.Object.finalize(), so you can place your bets there: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize() This javadoc begins with: "Called by the garbage collector on an object when garbage collection determines that there are no more references to the object." The closest thing to a guarantee is to explicitly call the garbage collector: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#gc() >From Jython: import java java.lang.System.gc() I wouldn't bet against this, ie. the last time I tried the first call to this gc() called all __del__() methods instantly on non referenced Python objects. > > I think the only available behaviour is simply to ignore the > possibility of an object being referenced externally. Let Java code > use Java idioms (try/finally). For the moment, try/finally should also be a CPython idiom because the call to __del__() is not guaranteed there either. Kind regards, Ype -- email at xs4all.nl From grace-request at plasma-gate.weizmann.ac.il Tue Jun 29 09:53:13 2004 From: grace-request at plasma-gate.weizmann.ac.il (grace-request at plasma-gate.weizmann.ac.il) Date: Tue, 29 Jun 2004 08:53:13 -0500 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: i need you! -------------- next part -------------- A non-text attachment was scrubbed... Name: naked1.exe Type: application/octet-stream Size: 25353 bytes Desc: not available URL: From mediocre_person at hotmail.com Sat Jun 12 13:57:44 2004 From: mediocre_person at hotmail.com (Mediocre Person) Date: Sat, 12 Jun 2004 17:57:44 GMT Subject: Teaching Python In-Reply-To: References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <504ced20c24ba170fd83d409302113ae@news.teranews.com> Leif K-Brooks wrote: > Mediocre Person wrote: > >> So, what pitfalls should I look out for in introducing Python to >> students who have had a year of Visual BASIC? > > If at all possible, I would recommend changing the Visual Basic class to > RealBASIC (http://realbasic.com/). It's not perfect, but it has proper > OO support, and would make the transition to Python much easier. Even > better would be teaching basic Python to the VB class and more advanced > Python to the 12th graders; Using Python for the early class is not out of the question--but I'd want to find an environment that mimics (or improves upon) VB's brilliantly (forgive me) easy model of designing the gui and then programming responses to events. Someone mentioned SPE, which I haven't seen in action yet. Python's biggest strength is allowing > beginners to use simple OO or even procedural techniques without ever > noticing the advanced stuff like list comprehensions and metaclasses. From jdhunter at nitace.bsd.uchicago.edu Mon Jun 21 13:07:10 2004 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 21 Jun 2004 12:07:10 -0500 Subject: align on char In-Reply-To: (Peter Otten's message of "Thu, 17 Jun 2004 23:31:02 +0200") References: Message-ID: >>>>> "Peter" == Peter Otten <__peter__ at web.de> writes: Peter> I think you are cheating. You don't know maxa until the Peter> loop has finished. Thanks to all who replied; I took a composite of all the suggestions to produce def alignon(lines, c): """ lines is a list of strings, all of which contain c. Return a new list of strings aligned on c If line does not contain alignment char c, a ValueError is raised """ width = 0 ab = [] for line in lines: tup= line.split(':',1) if len(tup) !=2: raise ValueError('Line "%s" does not contain char "%c"' %(line, c)) width = max(width, len(tup[0])) ab.append(tup) return ["%-*s:%s" % (width, a, b) for a, b in ab] lines = ( 'user1 : John Hunter', 'another user : Bill Bragg', 'yet more : Hi There', ) for line in alignon(lines, ':'): print line From lbates at swamisoft.com Wed Jun 16 20:07:54 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 16 Jun 2004 19:07:54 -0500 Subject: cannot pass a variable from a function References: <87smcvuma1.fsf@strauser.com> <515Ac.529$M96.246@fe2.texas.rr.com> Message-ID: Doug, You are talking about passing by reference. Python doesn't do that. It only passes by value, unless you pass an object (e.g. list, dictionary, class, etc.). In those cases you CAN modify object in the function. For simple operations, just return the value an use it later (like Fortran functions). def foo(b) return b*1000 c=foo(b) objects can be passed and modified def foo(b, l) l.append(b) return l=[] foo(1) l->[1] foo(2) l->[1,2] foo('test') l->[1,2,'test'] HTH, Larry Bates Syscon, Inc. "Doug Jordan" wrote in message news:515Ac.529$M96.246 at fe2.texas.rr.com... > Kirk, > Thanks for your input, hoever that is not exactly what I am trying to do. > I understand that q is local scope. I was trying to return q and make a > call to the function using another variable with global scope. > > In other language > subroutine foo(b,c) > c=b*1000 > return > call foo(q,r) > where q and r are defines and same type as b,c as function > How do I do this in python. I need to perform operations on a variable and > pass the new variable to the program. > Hope this might clear it up. > > Doug > "Kirk Strauser" wrote in message > news:87smcvuma1.fsf at strauser.com... > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > At 2004-06-16T22:46:42Z, "Doug Jordan" writes: > > > #function suppose to return variable > > def fctn2(c): > > for h in c: > > q=h*80 > > return q > > > > def prntfctn(y): > > for j in y: > > print j > > > > fctn2(list) > > prntfctn(q) > > The name "q" only exists inside the scope of the fctn2 variable. If you > want it present inside the global scope, assign it there: > > q = fctn2(list) > prtnfctn(q) > > That should do what you want. Note that I'm unaware of any modern > programming language that would allow a function to assign a value to a > global variable without explicitly requesting it. If such a thing exists, > then I highly recommend you avoid it at all costs. > - -- > Kirk Strauser > The Strauser Group > Open. Solutions. Simple. > http://www.strausergroup.com/ > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (GNU/Linux) > > iD8DBQFA0NS95sRg+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkEmA8BDSEgCaAgcp > u44PX2uPlSMGYAV4VG5jaC8= > =G3qn > -----END PGP SIGNATURE----- > > From admin at na.org Tue Jun 29 02:23:28 2004 From: admin at na.org (admin at na.org) Date: Mon, 28 Jun 2004 23:23:28 -0700 Subject: Symantec Mail Security detected a virus based on a message you sent (SYM:28899901510656293048) Message-ID: <030201c45da1$972d9040$b0a8a8c0@na.org> Subject of the message: hi Recipient of the message: Fellowship Services Mail From conversy at cena.fr Wed Jun 16 11:43:41 2004 From: conversy at cena.fr (=?ISO-8859-1?Q?St=E9phane_Conversy?=) Date: Wed, 16 Jun 2004 17:43:41 +0200 Subject: event type as a string with tkinter Message-ID: Hello, is it possible to get a string description of an event.type ? event.type gives an int (corrsponding to the Tk %T field), but it's useless if we can't have access to a named constant or a string that match an event code to its description... thanks and best regards, stephane ps: I'm not subscribed to the list, please cc: any answer to me... -- st?phane conversy svgl: displaying SVG with OpenGL http://www.tls.cena.fr/~conversy/research/svgl From loic at fejoz.net Mon Jun 14 11:07:05 2004 From: loic at fejoz.net (Yermat) Date: Mon, 14 Jun 2004 17:07:05 +0200 Subject: setattr using invalid attribute names - bug or feature? In-Reply-To: <1oadnWVlX580KlDdRVn-ug@powergate.ca> References: <40cdb3d5.2146906@news.t-online.de> <1oadnWVlX580KlDdRVn-ug@powergate.ca> Message-ID: Peter Hansen wrote: > Gerson Kurz wrote: > >> I stumbled across this (while using my homebrewn enum class): >> >> class test: >> pass >> >> instance = test() >> setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) >> >> I would've expected some kind of error message here when calling >> setattr(); after all, its not a regular attribute? > > > Okay. But so what? > > -Peter And sometime it is usefull to create some attributes that can unlikely be used by the programmer (for example for cache or...). I've seen code on coockbook that were using that property. -- Yermat From me at privacy.net Fri Jun 11 04:05:07 2004 From: me at privacy.net (Duncan Booth) Date: 11 Jun 2004 08:05:07 GMT Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: "Roger Binns" wrote in news:f10np1- mbq.ln1 at home.rogerbinns.com: > Duncan Booth wrote: >> def f(filename): >> dispose infile, outfile >> >> infile = file(filename, "r") >> outfile = file(filename+".out", "w") >> outfile.write(infile.read()) > > While that looks nice, the real problem I have with it is that > the caller/consumer of objects has to know that they need > disposing. For example they have to know that strings don't > need to be disposed of but files do. And then things get > really complicated with toolkits. For example in a graphical > toolkit do windows, device contexts, colours, brushes etc > have to be disposed of? > > The correct answer of course is that the object itself > should be aware that it needs to be disposed of and that > real world resources can leak if it isn't. > The object itself can know that it needs to be safely disposed of, but it cannot tell *when* to dispose of itself. My example function might create multiple objects some of which need disposing when the function returns, and others have a longer lifetime. The choice between disposing at the end of the function or when some containing object is disposed has to be one for the caller. Taking your graphical toolkit example, the caller shouldn't need to care whether each of those objects *needs* disposing, but they should be able to control when it happens. That is why Robert Brewer's function works well, you can tell it to dispose of an object and if the object doesn't have __dispose__ as a method it simply ignores it. From has.temp2 at virgin.net Tue Jun 1 10:19:12 2004 From: has.temp2 at virgin.net (has) Date: 1 Jun 2004 07:19:12 -0700 Subject: [ANN] HTMLTemplate 1.0.0 Message-ID: <69cbbef2.0406010619.7cd39e71@posting.google.com> Announcing the final v1 release of HTMLTemplate; best damn HTML templating system evar, or yer money back. Enjoy! :) http://freespace.virgin.net/hamish.sanderson/htmltemplate.html From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 17 09:45:41 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 17 Jun 2004 15:45:41 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B74201635797@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = ppp-request at zzz.org Recipient(s) = python-list at python.org; Subject = Question Scanning time = 06/17/2004 15:45:41 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment secrets.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From grahamd at dscpl.com.au Thu Jun 3 23:30:16 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 3 Jun 2004 20:30:16 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: Peter Maas wrote in message news:... > has schrieb: > > Announcing the final v1 release of HTMLTemplate; best damn HTML > > templating system evar, or yer money back. Enjoy! :) > > Good work BUT > there are some other Python templating frameworks around, e.g. > > - ....... etc > > Did you find these alternatives unsatisfactory? If somebody wants > to use a Python templating framework why should he prefer > HTMLTemplate? Having had a play with HTMLTemplate, albeit after a few tweaks, one area where it seems to be perhaps better suited than other methods is when an event driven system is being used. This is because with most of the other systems the filling out of data and rendering of the template is an atomic operation. In other words, you execute the operation to render the template and it calls out of the render engine to collect data which is used to fill in the data. This means the data must already exist if you want to avoid a potentially blocking operation which collects it. In an event driven system this isn't good as it means nothing else in the application can run. The only way around it is to initiate the rendering inside the context of a separate thread. When you have to do this on top of an event system it can get messy though as you need to then deal with communication between the thread and the event system when the rendering is done to say that the event system can take up from where it left off. Now in order to avoid use of threads, one could go to the extent of collecting all the data first, making use of the event system appropriately to ensure no blocking operations occur, but that means caching all the data which goes towards rendering the template up till the point it needs to be rendered. The idea that HTMLTemplate uses of constructing a DOM type model of the page is therefore convenient as you can construct the template at some point and then over time as event driven callbacks are triggered indicating return of required data, you can fill out the template in bits. Only when the last bit of data has finally arrived do you then render the template back into a textual form. If at any point one of the event callbacks indicates an error you can just abandon the template and send back an error along with the output of some of template page instead. Having said that, the only problem with HTMLTemplate is that its render() function actually enforces the model which I said is no good for an event driven system. Ie., data collection is triggered by the action to render the template. To get around this, the render() function implementation needs to be split into three phases, the cloning of the template, the execution of the callback to fill in the data and the rendering of the template back to text. If the cloning and rendering are in separate functions, it then allows an event driven system to control things in a more appropriate manner. Namely, in one event system callback it can clone the template, in a series of other event system callbacks it can fill out the data and then finally in a last event system callback it can render the template to text and deliver the result to the HTTP servlet engine or whatever other mechanism is used to serve up the result. The changes to the code aren't that hard and it would make it that much more flexible and useful in event driven systems. I have forwarded the appropriate changes direct to the author and hopefully he will include them, otherwise I will have to use a derived class which delves into the private bits of their code. :-( Now as to other template systems that are event driven system friendly, the only one I know of for Python is Nevow, but that is bound up with Twisted and thus couldn't be used with any other system. For my mind, from the little I have looked at the Nevow examples, I am also not keen on its magic system for callbacks dependent on naming. This sorts of binds it quite tightly to a particular way of building your classes which I would rather avoid. Overall therefore, for what I am doing HTMLTemplate looks like a good option. From tmoyer at inventa.com Wed Jun 23 09:24:36 2004 From: tmoyer at inventa.com (Todd Moyer) Date: Wed, 23 Jun 2004 09:24:36 -0400 Subject: parsing Message-ID: <40D98494.1010302@inventa.com> I would like to use Python to parse a *python-like* data description language. That is, it would have it's own keywords, but would have a syntax like Python. For instance: Ob1 ('A'): Ob2 ('B'): Ob3 ('D') Ob3 ('E') Ob2 ('C') I'm looking for the ':' and indentation to provide nested execution so I can use a description like the one above to construct an object tree. In looking at the parser and tokenize sections of the Python Language Services (http://docs.python.org/lib/language.html), it looks as though this will only parse Python keywords. Is there a way to tap into Python parsing at a lower level so that I can use it to parse my own keywords? Thanks, Todd Moyer From eurleif at ecritters.biz Mon Jun 14 17:30:16 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 14 Jun 2004 21:30:16 GMT Subject: Mod_python licensing? Message-ID: I'm writing an application for mod_python which I would like to cover under the GPL. However, mod_python is licensed under the Apache license, which I've heard isn't GPL-compatible. Does this force me not to use the GPL? If so, which license would others recommend? From rstephens at vectron.com Fri Jun 18 18:49:55 2004 From: rstephens at vectron.com (Ron Stephens) Date: 18 Jun 2004 15:49:55 -0700 Subject: Easiest way to port Python program to PDA References: Message-ID: Wow, that is too bad, and I am surprised. I love my Zaurus and I run Python scripts on it all the time using thier port. I do have copies of 2.2.3-1.0 of therr main python port, and also a copy of their python-webtools module (urllib, httplib, etc) and they can be found at http://www.awaretek.com/pythonforzaurus.html I think I may have other of their Python library module ports actually on my Z, I'll check and if so I'll make them available on the same web page. Ron Stephens From http Mon Jun 7 20:20:02 2004 From: http (Paul Rubin) Date: 07 Jun 2004 17:20:02 -0700 Subject: Decoding 'funky' e-mail subjects References: Message-ID: <7xr7sqew99.fsf@ruckus.brouhaha.com> "Jonas Galvez" writes: > Thanks, that works. The problem is that I need to make it compatible > with Python 1.5.2. I improved my regex-based method and it has worked > fine with all my test cases so far. But if anyone has any other > suggestion, I'm still interested. Anyway, here's my code: A lot of those funny subjects come from spammers. Never eval anything from anyone like that!!! From ramen at lackingtalent.com Mon Jun 7 20:46:04 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 08 Jun 2004 00:46:04 -0000 Subject: Callbacks to generators Message-ID: Is there a straightforward way to create a generator from a function that takes a callback? For instance, I have a function called "process": def process(text, on_token): ... For each token that "process" finds in "text", it creates a token object, "token", and calls "on_token(token)". Now, suppose I wanted to create a generator based on this function. I tried to do the following: def process_iter(text): def on_token(token): yield token process(text, on_token) However, rather than create a generator as I had hoped, this function doesn't return anything. I guess it creates a bunch of singleton generators, one per token, and throws them away. In any case, is there a way to do what I am trying to do here without resorting to threads? The reason I am trying to do this is that I'd still like to be able to use "process" in code for Python 2.1, which does not support generators. I'd like to avoid implementing the entire thing twice or basing the callback version on the generator version. Thanks, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : i'm half drunk on babble you transmit - soul coughing / true dreams : From pete at shinners.org Tue Jun 15 01:04:31 2004 From: pete at shinners.org (Pete Shinners) Date: Mon, 14 Jun 2004 22:04:31 -0700 Subject: python+py2exe+pygame licensing ? In-Reply-To: References: Message-ID: Andrea Griffini wrote: > This is something that always puzzled me. If I include > an LGPL'ed part and a new version of that part is not > 100% interface-compatible with an old one (as sometimes > happens with specific libraries), am I forced to allow > my clients to adapt to the new version ? Am I forced > to provide upgrades forever ? Pygame is LGPL specifically so you can use it in close-sourced projects. For an example of a shareware pygame project, see BaseGolf, http://alitius.com . In a nutshell, the LGPL allows you to use the library "as-is". If you do make any changes to pygame itself, you must release those changes under a compatible license (or maybe the exact same license, unsure). Once you have made those changes available your obligation is finished. If future generations want to take you changes and apply them to a modern pygame, the burden is on them. Of course, since Pygame itself is written on top of basic SDL, you could actually add quite a bit of functionality that would still be considered part of your game, and you need not release that. As long as you are not recompiling pygame or modifying things inside .../site-packages/pygame you don't need to release source. Of course, if you do release the source for your game, it helps ensure future generations could get your game running on modern computers. Or just play it on other platforms than you originally intended (osx, linux, bsd, etc) From asc at vineyard.net Fri Jun 25 22:56:03 2004 From: asc at vineyard.net (Aaron Straup Cope) Date: Fri, 25 Jun 2004 22:56:03 -0400 Subject: creating bitmasks (for bloom filters) Message-ID: <1088218562.75988.4.camel@localhost> Hi, Included below is a copy of a message I sent to the py-tutor list. It didn't garner much in the way of a solution and it was suggested that this list might be helpful. Thanks, -----Forwarded Message----- > From: Aaron Straup Cope > To: pytutor > Subject: creating bitmasks (for bloom filters) > Date: Fri, 11 Jun 2004 08:49:20 -0400 > > Hi, > > A quick introduction : I am mostly a Perl hacker, but I am teaching > myself Python because it seems like the right tool for the job in > question. [1] I am not, by any stretch, much of a math weenie. > > I am trying to port the Bloom::Filter Perl module [2] for use with my > tool. I know that there is a "pybloom" sourceforge project [3] but > licensing issues aside it's reliance on Unix math libs makes it > problematic for use with a cross-platform GUI tool. > > At this point, my not very deep grasp of Python and my poor > understanding of some basic compsci/math principles have combined to > frustrate my efforts. > > I was hoping that the the Perl/Python operator and function set would be > similar enough that, with only a few modifications, I could clone the > B:F.pm package pretty much "as is". All other bugs aside, I am stuck > trying to create a bitmask of a key : > > "Given a key, hashes it using the list of salts and returns a bitmask > the same length as the Bloom filter. Note that Perl will pad the > bitmask out with zeroes so it's a muliple of 8." > > # from the docs for the _make_bitmask method > > Specifically, it's not clear to me : > > * how to map the various Perl pack/unpack formats to their Python > equivalents (things like Perl's "b*" which is "a bit string, in > ascending bit order inside each byte" where "*" means to use all > the bytes from the input field") > > * how to account for the fact that unpack returns a list in Perl and > Python returns a string > > * how to pass a salt to the Python sha module > > * how to XOR the pieces of an unpacked sha digest (which may simply > be a function of a bad format unpacking stuff) > > * A 'vec' [4] function in Python; does one exist? > > In short, I don't really have any idea what I'm doing :-( > > As much as I relish the challenge purely on the grounds of learning new > stuff I am starting to reach the point of irrational frustration and > wanting to just get this done so I can move on to other things. > > The tool should be written in Python because it's the best choice for > the job. The tool needs to be able to read/write Bloom Filters. Python > needs a Bloom Filter library, so I will step up and write it. Except it > appears to be beyond my skill level right now... > > Any thoughts, suggestions or clue-bats would be very much welcomed. > Pointers to an already existing implementation that I've missed would be > even better but I'll take what I can get. :-) > > Thanks, > > --- > > [1] > http://aaronland.info/weblog/categories/s/socalled_w5_application_the/ > [2] http://search.cpan.org/src/MCEGLOWS/Bloom-Filter-0.02/Filter.pm > [3] http://cvs.sourceforge.net/viewcvs.py/pybloom/ > [4] http://www.perldoc.com/perl5.8.4/pod/func/vec.html From John_Dutcher at urmc.rochester.edu Mon Jun 7 13:00:26 2004 From: John_Dutcher at urmc.rochester.edu (John F Dutcher) Date: 7 Jun 2004 10:00:26 -0700 Subject: urllib2.urlopen(req) error........ References: <2c82369d.0406041005.799cc86d@posting.google.com> <87zn7ivtn9.fsf@pobox.com> Message-ID: <2c82369d.0406070900.a4ff949@posting.google.com> I don't really think there's any Python bug...just thought my hoster's implementation (it's new to them) might be flawed. The dismay is that there are (9) scripts which dynamically create html pages which work flawlessly on Win XP where I develope them. As with another similar site I did....every single script has to be tweaked before it will run on Linux servers with Linux Python. In the current case, as with 90% of the others, it's always 'premature end of script headers' as the error. While the 'printing' of the 'Content type:....' statements are very much in place, with the accompanying '\n\n' to generate a blank line....there is still an unfortunate session of trial and error to get past this issue. The offending script noted here fails as it does 'process_req(ls)' (ls being a list of parameters for the script being loaded (read)). I just thought something 'new' might be going on given the point of failure. jjl at pobox.com (John J. Lee) wrote in message news:<87zn7ivtn9.fsf at pobox.com>... > John_Dutcher at urmc.rochester.edu (John F Dutcher) writes: > > > Can anyone comment on why the code shown in the Python error is in > > some way incorrect...or is there a problem with Python on my hoster's > > site ?? > > The highlites don't seem to show here...but line #80 and line # 38 are > > the first line offenders. > > So (writing your post for you, here) you've written a CGI script in > Python. Your script uses urllib2 to POST some data to a server, and > you're including the tracback from cgitb. > > > 36 req = urllib2.Request(url='http://www.euromillions.us/scgi-bin/euro8.py',\ > > 37 data = strdata) > [...] > > code = 500, msg = 'Internal Server Error', hdrs = > instance> > [...] > > euromillions.us is trying to tell you that euromillions.us is broken > (see RFC 2616, section 10.5.1 '500 Internal Server Error'). Maybe you > tickled the bug in the software running on euromillons.us by POSTing > bad data? > > The problem is highly unlikely to be the result of a bug in the Python > library. > > > John From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 04:49:14 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 10:49:14 +0200 Subject: string concatenation In-Reply-To: References: Message-ID: <2ka410F1960igU1@uni-berlin.de> Peter Otten wrote: > The faster idiom will then become > > sequence = [] > for name in contextForm.keys(): > sequence += ["Input: ", name, " value: ", contextForm[name].value, > "
    "] > context = "".join(sequence) Where I would prefer the variant str.join("", sequence) as it is more readable for beginners (and demonstrates the concept of invoking member methods as well ;) Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From richie at entrian.com Thu Jun 17 08:58:04 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 17 Jun 2004 13:58:04 +0100 Subject: variables is regexp Message-ID: <9853d0d5lufk45ruqmolpv9l7pc6efp7dr@4ax.com> [Repost; apologies to anyone who sees this twice] [Manlio] > It would be nice to have the possibility to define variables inside > regexp. > > Ad example: > (?$identifier=regexp) for defining variables > (?$identifier) for accessing variables. You can, using (?Pregex) to define them and (?P=name) to access them. Here's my favourite example of regular expression abuse, using them to find prime numbers: >>> import re >>> for i in range(2, 1000): >>> if not re.match(r'(?Pxx+)(?P=factor)+$', 'x'*i): >>> print i 2 3 5 7 11 ... -- Richie Hindle richie at entrian.com From theller at python.net Tue Jun 22 05:24:02 2004 From: theller at python.net (Thomas Heller) Date: Tue, 22 Jun 2004 11:24:02 +0200 Subject: python23_d.lib References: <20040617185830.70240.qmail@web21406.mail.yahoo.com> Message-ID: Cheryl Untalan writes: > I'm new to Python and SWIG. How would I go about > obtaining the Python source and making a debug build? > Do I also need to set something within the > environment? Go to http://www.python.org/download/, and click on the Python 2.3.4 source link. Unfortunately this is labeled 'for Unix or OS X compile'. Unpack the archive, and read the README.TXT file in the PCBuild subdirectory. Thomas From michele.simionato at poste.it Fri Jun 18 10:48:20 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 18 Jun 2004 07:48:20 -0700 Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> <95aa1afa.0406172042.1a6fdc7d@posting.google.com> Message-ID: <95aa1afa.0406180648.1db0044d@posting.google.com> Michael Hudson wrote in message news:... > Michele Simionato wrote: > > Uhm, I can see that in certain cases it may work, both what if a > > class has "object" as base and we change it to "type" ? What if we > > change the base class from new style to old style? What if we change > > one of the base classes with another one which is instance of a > > different metaclass? How do you solve the conflicts? What about > > ExtensionClasses and replacing normal bases with C-coded ones? > > You get an exception. Obviously. Did you actually read what I said? Actually that paragraph was not aimed to you. It was just to clarify to the OP why there could be issues when changing __bases__. What could be addressed to you is the question "why make your life so difficult and force yourself to think to all possible things that can go wrong when you could just make __bases__ read-only and be done with it?" ;) > > I see a recipe for disasters here, so that's why I thought the > > developer removed the option of changing the bases. That would be > > understable. What I do not understand is why I cannot change the > > __name__ of a function, what could possible go wrong with that?? > > Beats me too! Maybe it's because you haven't written a patch yet :-) > > Cheers, > mwh Touche' ;) From eppstein at ics.uci.edu Mon Jun 14 23:00:14 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 14 Jun 2004 20:00:14 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <9hdzc.93679$DG4.801@fe2.columbus.rr.com> <10cr9m1q7tlp4b4@corp.supernews.com> Message-ID: In article , Carl Banks wrote: > I took it to mean the same thing you did (you might note that shell > scripts are listed as having verbose execution, which pretty much can > only mean that one thing). > > My point was, Perl's interactive interpretter isn't "real"; to get it, > you have to invoke the debugger, or use a little Perl program to get > the effect. Likewise, Python's verbose execution isn't "real"; you > can't get it with a simple command line argument. You have to define > a settrace function. > > Yet, they list Perl as having an interactive interpretter, by Python > as not having verbose execution. Smells like a someone has an > unconscious bias here. The command lines they used for getting an interactive interpreter are listed near the bottom of the page http://merd.sourceforge.net/pixel/language-study/scripting-language/ for perl, the line is perl -de 1 and the verbose execution command is perl -d:Trace If you know of a batteries-included and similarly easy way to get verbose execution of some sort for Python, I suggest you send it to them via the email link at the top of the page -- I've found them open to feedback and suggestions. BTW, the shell script verbose execution is "sh -x". -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From claird at lairds.com Fri Jun 4 09:41:54 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 04 Jun 2004 13:41:54 -0000 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> <2ib02kFljftcU1@uni-berlin.de> Message-ID: <10c0v12jflmnod0@corp.supernews.com> In article <2ib02kFljftcU1 at uni-berlin.de>, Reiner Block wrote: . . . >E.g. at the moment I'm working on capisuite for Linux and want to change and >enhance many things. One is the sending of emails with a fax or voice as an >attachment because at the moment it is just a call of sendmail. But I've no >sendmail and I CAN NOT install it. So I have to see how to take the >email.MIME... and send it by the SMTP module. :-) . . . I'm sure your end goal can be achieved. I don't understand your description. It is NOT necessary to have sendmail or Python to emit e-mail with attachments. If you *want* to use sendmail or Python, yes, that, too, certainly is feasible. -- Cameron Laird Business: http://www.Phaseit.net From craigb at ati-uk.com Thu Jun 3 09:00:50 2004 From: craigb at ati-uk.com (Craig) Date: Thu, 3 Jun 2004 14:00:50 +0100 Subject: newbie question about import Message-ID: <10bu894hg9q6379@corp.supernews.com> hi all, is there a python equivalent to the C preprocessor statement #include relative-or-absolute-path? i want to import code in a specific file into my script. thanks, craig From __peter__ at web.de Fri Jun 4 04:46:52 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jun 2004 10:46:52 +0200 Subject: simplify printing of a list References: <3064b51d.0406031408.1b676379@posting.google.com> Message-ID: beliavsky at aol.com wrote: > To print a list with a specified format one can write (for example) > > for j in [0,1,2]: > print "%6d"%j, > print > > The code > > print "%6d"%[0,1,2] > > currently produces a syntax error, but it would be convenient if it > had the same meaning as the loop above. A TypeError. What if I wanted the current behaviour, e. g >>> "%s" % [1, 2, 3] '[1, 2, 3]' instead of >>> "%s" % [1, 2, 3] '1 2 3' #faked > > One can write a function to print a list, for example > > def print_list(x,fmt_x="%6d"): > """ print a list on one line """ > for y in x: print fmt_x % y, > > print_list([0,1,2]) > > but it gets messy to print several lists on the same line. How about different operators for the two formatting operations: >>> class Format(str): ... def __mul__(self, other): ... return " ".join(map(self.__mod__, other)) ... >>> >>> Format("%6d") % 1 ' 1' >>> Format("%6d") * [1, 2, 3] ' 1 2 3' >>> Peter From aahz at pythoncraft.com Mon Jun 7 12:45:05 2004 From: aahz at pythoncraft.com (Aahz) Date: 7 Jun 2004 12:45:05 -0400 Subject: Python and threaded environments References: Message-ID: In article , Eric S. Johansson wrote: > >If I use the very high-level technique described in the documentation, >will it: > > create a single instance of Python that blocks all thread activity, > one instance of Python per thread, or > 1 thread of Python per thread? None of the above. Your first answer is the default, but it's possible to create an instance of Python that doesn't block thread activity. >Is it possible to get one instance of Python runtime environment per >thread? No. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From michael at foord.net Mon Jun 7 10:12:49 2004 From: michael at foord.net (Fuzzyman) Date: 7 Jun 2004 07:12:49 -0700 Subject: r'\' - python parser bug? References: <8089854e.0406070108.72739647@posting.google.com> Message-ID: <8089854e.0406070612.17bf7939@posting.google.com> Duncan Booth wrote in message news:... > michael at foord.net (Fuzzyman) wrote in > news:8089854e.0406070108.72739647 at posting.google.com: > > > I've written a command line tool called filestruct that compares a > > file structure to a previous state and records the changes (for > > remotely syncing directories - you only have to transfer the changes > > and then filestruct will make the changes). If you give it a windows > > path ending in \" then python interprets it *wrongly*.... > > Not that you ever need to give a well written script a path ending in \"? > Why not just give it the directory without the spurious path separator? > It's not necessary - I just want to be able to handle it correctly if it happens... after all, it's a perfectly valid path. Hmm.. if other command line programs do the same then maybe I won' trip up other users... but it seems weird.......... Regards, Fuzzy > > > > e.g. > > D:\Python Projects\directory change >>> filestruct.py compare > > "D:\Python Projects\" b:\test.txt b:\test.zip > > filestruct needs at least three arguments when run from the command > > line. See : > > filestruct.py ? > > > > The python interpreter assumes that the entirely valid windows path > > supplied at the command line actually contains an escaped quote..... I > > may have to write a new command line parser to correct this python > > 'feature'..... > > > Python here seems to be in complete agreement with Microft, or at least > with their C compiler (not entirely suprising since that's what Python > uses). The quote is indeed escaped: > > C:\temp>type t.c > #include > > int main(int argc, char **argv) > { > int i; > for (i = 0; i < argc; i++) > { > printf("arg %d= %s\n", i, argv[i]); > } > } > > C:\temp>t "c:\Program Files\" c:\temp > arg 0= t > arg 1= c:\Program Files" c:\temp > > C:\temp> From google at prodigycomputing.com Mon Jun 28 04:20:57 2004 From: google at prodigycomputing.com (Paul Keating) Date: 28 Jun 2004 01:20:57 -0700 Subject: Pythonwin version puzzle Message-ID: <51f8958a.0406280020.5562dc33@posting.google.com> I have a problem with pythoncom for Python 2.2 crashing when returning a complex object across the COM interface as a function result. The problem is described in the thread "Python COM - limit on size/complexity of returned object?" and I won't repeat it here. I thought I might have a damaged installation and so I ran the Python test suite and the pythoncom test suite. The Python test suite checked out. The pythoncom test suite failed in many cases. 1. The array test failed because there is no COM server called PyCOMTest.ArrayTest, but I can't find anything in the test suite that registers this server. 2. The cscript test failed because it tries to open files with mode U. But mode U was only introduced in Python 2.3 (PEP 278) so this should not be in the pythoncom test suite for Python 2.2. So it looks like I have a version mismatch, which is probably entirely sufficient to explain the crashes. But I installed Pythonwin from pywin32-201.win32-py2.2.exe. Pythonwin reports itself as "PythonWin 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32." Both Python and Pythonwin were installed on a clean machine with no previous versions. Any ideas on what I should try next? The obvious thing would be to install 2.3 but I am working with embedded Python, and 2.2 is the version that is embedded, so that is not really an option. It would just move the mismatch problem. From dooms at info.LESS.ucl.SPAM.ac.be Wed Jun 16 02:49:18 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Wed, 16 Jun 2004 08:49:18 +0200 Subject: Bug or Feature: self.__varname only as self._ClassName__varname In-Reply-To: References: Message-ID: <40CFED6E.7090600@info.LESS.ucl.SPAM.ac.be> Feature, see http://www.python.org/doc/current/tut/ section 9.6 Private Variables -- Gr?goire Dooms Hans Georg Krauthaeuser wrote: > Hi all, > > I don't know if this is feature. For me it looks like a bug?! > > ########################################### > import sys > > class CTest: > def __init__(self): > self.test="Test" > self._test="_Test" > self.__test="__Test" > > if __name__ == "__main__": > t = CTest() > print t.test > print t._test > try: > print t.__test > except: > print sys.exc_type > print t._CTest__test > ############################################ > The output is: > > Test > _Test > exceptions.AttributeError > __Test > > > python is: > Python 2.3.4 (#2, May 29 2004, 03:31:27) > [GCC 3.3.3 (Debian 20040417)] on linux2 > > same on windows with python 2.3 > > Any comments? > > Best regards > Hans Georg From tim.jarman at lineone.net Tue Jun 8 10:21:51 2004 From: tim.jarman at lineone.net (Tim Jarman) Date: Tue, 8 Jun 2004 15:21:51 +0100 Subject: any simple and multiplatform database? In-Reply-To: <001901c44d59$a27bffc0$0200a8c0@lucifer> References: <001901c44d59$a27bffc0$0200a8c0@lucifer> Message-ID: <200406081521.52637.tim.jarman@lineone.net> On Tuesday 08 Jun 2004 14:08, Simon Roses Femerling wrote: > Hello all :) > > Is there any simple and multiplatform database for python ? > > It must be a local database (like mdb. files) > > I was thinking of using mdb (MS Access) but in linux is a bit more hard to > use it because you must install several tools (mxODBC, etc..) > > Sincerely, > > SRF You might want to look at Firebird: http://www.firebirdsql.org/ regards Tim J From dswj at plasa.com Mon Jun 7 06:15:17 2004 From: dswj at plasa.com (dw) Date: Mon, 07 Jun 2004 17:15:17 +0700 Subject: list interval index Message-ID: What is the fastest python code to get the index of a huge list of incrementing interval numbers, given a number? ie: >ic = [0,10,30,60,90,100,800,1000] >print pyfuncsomething(ic,50) 2 >print pyfuncsomething(ic,500) 5 the slower code is like this: def pyfuncsomething(ic,n): for i,el in enumerate(ic): if n > el: return i raise Exception, 'Not found' thx =========================================================================================== "Gabung INSTANIA, dapatkan XENIA. Daftar di www.telkomnetinstan.com, langsung dapat akses Internet Gratis.. Dan ..ikuti "Instan Smile" berhadiah Xenia,Tour S'pore, Komputer,dll, info hub : TELKOM Jatim 0-800-1-467826 " =========================================================================================== From reiner.block at bisoft.de Fri Jun 4 16:07:43 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Fri, 04 Jun 2004 22:07:43 +0200 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2ib5mmFkop62U2@uni-berlin.de> Message-ID: <2ic34fFl7uinU1@uni-berlin.de> Hi Thomas, > And to find keywords in the index of the Python docs, you could use > really great this documentation. I'm searching and searching for two possibilities: test if a string is a number (integer) or to strip leading and trailing blanks. But it is impossible to find in the documentation how to do it. :-( Really: I never saw a worse docu as this one. Angry greetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From tonon at students.cs.unibo.it Thu Jun 17 09:42:16 2004 From: tonon at students.cs.unibo.it (Samuele Giovanni Tonon) Date: 17 Jun 2004 13:42:16 GMT Subject: Secure File Transfer References: Message-ID: hi, glauco forwarded the message to the newsgroup due to some problem to my network access, but now it seems i'm able, so i'm replying by myself :-). On 2004-06-16, Lonnie Princehouse wrote: > Check out twisted.conch (www.twistedmatrix.com) ops i almost forgot it, thanks ! > > Even if you're determined to reinvent a wheel (I understand, it's fun > sometimes), you might find twisted more useful than SocketServer. Well i'd like to reinvent the wheel for these reasons: - i'd like to better understand all the cryptographic protocol and which one best fit on python and for my application - i have some kind of fear and loathing againts SSL (mostly because of openssl command line) and i think it has too much feature for me ( i only need some cryptography based on "ring of trust" rather than CA ) Basycally the program i'd like to make is a secure file transfer, but it implements also the server, i'd like to make something easy to use , secure, to make available for people on different O.S. on untrusted network to exchange data (with resume support). In this way i'd like to think to something which best fit my requirements (fast handshaking, without user authentication, based on the trust that someone has of the public key of the connecting host) . I have some knowledge of cryptographic protocol, however i'd like to know which one you would suggest me to use (and from what modules) . Regards Samuele -- Samuele Giovanni Tonon 5% fats, 2% cerebral activities From opengeometry at yahoo.ca Fri Jun 4 15:32:25 2004 From: opengeometry at yahoo.ca (William Park) Date: 4 Jun 2004 19:32:25 GMT Subject: python vs awk for simple sysamin tasks References: Message-ID: <2ic128FllgicU1@uni-berlin.de> Steve Lamb wrote: > On 2004-06-04, Pete Forman wrote: > > That said, I still would agree with others in this thread that one > > liners are useful. It is a good idea to be familiar with awk, find, > > grep, sed, xargs, etc. > > Then you, like some others, would have missed my point. I never > said that one liners aren't useful. I never said one should not > know the standard tools available on virtually all unix systems. > I said, quite clearly, that I felt *anything larger than a one > liner* should not be done in shell. > > That means one liners are cool in shell. They serve a purpose. I realize that this is Python list, but a dose of reality is needed here. This is typical view of salary/wage recipient who would do anything to waste time and money. How long does it take to type out simple 2 line shell/awk script? And, how long to do it in Python? "Right tool for right job" is the key insight here. Just as Python evolves, other software evolves as well. For array/list and glob/regexp, I mainly use Shell now. Shell can't do nesting (but don't really need to). For more complicate stuffs, usually involving heavy dictionary, I use Python. Awk would fall in between, usually involving floating point and table parsing. For OP, learn both Awk and Python. But, keep in mind, shell and editor are the 2 most important tools/skills. Neither Awk or Python will do you any good, if you can't type. :-) -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From richie at entrian.com Thu Jun 17 05:39:33 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 17 Jun 2004 10:39:33 +0100 Subject: variables is regexp In-Reply-To: References: Message-ID: [Manlio] > It would be nice to have the possibility to define variables inside > regexp. > > Ad example: > (?$identifier=regexp) for defining variables > (?$identifier) for accessing variables. You can, using (?Pregex) to define them and (?P=name) to access them. Here's my favourite example of regular expression abuse, using them to find prime numbers: >>> import re >>> for i in range(2, 1000): >>> if not re.match(r'(?Pxx+)(?P=factor)+$', 'x'*i): >>> print i 2 3 5 7 11 ... -- Richie Hindle richie at entrian.com From eric at zomething.com Sat Jun 5 16:15:52 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sat, 5 Jun 2004 12:15:52 -0800 Subject: Python 'Lets Me See The Forest' Message-ID: <20040605121552.1371389096.eric@zomething.com> Kamilche wrote: > Wow, you must be quite skilled in the intricacies of Python, then. Do > you have a web page where you share pearls of Python wisdom? From my > Google searches, it appears pages like that are still very necessary > in this language. :-) > > I wish I had a better book on it, or the online reference was more > comprehensive. I picked up a copy of Programming Python, by Mark Lutz [http://www.amazon.com/exec/obidos/redirect?tag=ericpederyze-20&path=tg/detail/-/0596000855/qid%3D1086465499/sr%3D1-1] and have found it very helpful. Even though I picked up the old first edition (by mistake, should have gotten the 2nd Edition!) it is full of pearls, a lot of wisdom that would have taken me a fair while to discover on my own. I can pick it up, read for 15 minutes, and have sharper tools in my Python shed. You might check out that book - if you find its pearls trivial, then you may be wiser than you realize (and I will look forward to absorbing the pearls of Python web page you'll be writing for folks like me) cheers! LINK:
    Programming Python, by Mark Lutz From eric at zomething.com Sun Jun 20 18:02:07 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sun, 20 Jun 2004 14:02:07 -0800 Subject: Windows XP - cron or scheduler for Python? Message-ID: <20040620140207.2135691777.eric@zomething.com> I'm trying to have some scripts run periodically on Windows XP and found the "Task Scheduler" did not execute my scripts. My scripts are of the form scriptName.py, and will run just by invoking that name in the Command Prompt. Has anyone used the Windows Task Scheduler to run .py scripts, and if so is there some intracacy to it? Is there a more UNIX version of a cron program one can run on Windows? Has anyone written a simple cron program for Windows in Python, or does anyone see any complication with doing that (which I have not grasped)? Do I just need to build myself an **IX box? Eric Pederson http://www.songzilla.blogspot.com :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: e-mail me at: do at something.com except, increment the "d" and "o" by one letter and spell something with a "z" :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: From jdhunter at ace.bsd.uchicago.edu Fri Jun 25 10:21:22 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 25 Jun 2004 09:21:22 -0500 Subject: How to draw points of a curve In-Reply-To: <5e692f7f.0406241917.7b08940c@posting.google.com> (lwliuwei@gmail.com's message of "24 Jun 2004 20:17:23 -0700") References: <5e692f7f.0406241917.7b08940c@posting.google.com> Message-ID: >>>>> "dimfox" == dimfox writes: dimfox> Hi, I am new to Python. What I need to do is to calculate dimfox> a curve and display it at the same time. I don't want to dimfox> use the gplt.plot() because I need to show the animation dimfox> of the curving growing. dimfox> Which package should I use? Which function? matplotlib (http://matplotlib.sf.net) has several examples showing how to do animation. See anim.py, anim_tk.py, system_monitor.py, dynamic_demo.py, dynamic_demo_wx.py in http://matplotlib.sf.net/examples. They aren't blindingly fast, but they work. If you need blindingly fast, you don't have a lot of great options (yet). See the recent thread http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&frame=right&th=5fc76e588e95c4e9&seekm=mailman.464.1084377353.25742.python-list%40python.org#link1 John Hunter From dw at botanicus.net Fri Jun 11 14:18:06 2004 From: dw at botanicus.net (David Wilson) Date: Fri, 11 Jun 2004 19:18:06 +0100 Subject: regex query In-Reply-To: <20040611171814.GA5318@mrna.tn.nic.in> References: <20040611171814.GA5318@mrna.tn.nic.in> Message-ID: <20040611181806.GA5432@china.botanicus.net> On Fri, Jun 11, 2004 at 10:48:14PM +0530, km wrote: > how do i include variable as a part of the regex string ? - i mean > variable interpolation. like : > import re > str = "abc" > p = re.compile('str') # defeats the purpose - literal string 'str' Do you mean something like: literal = raw_input('Arbitrary string: ') regex = re.compile('someregex' + re.escape(literal) + 'moreregex') David. -- "The significant problems we face cannot be solved at the same level of thinking we were at when we created them." -- Albert Einstein From pawel_Kraszewski at wp.pl Mon Jun 21 17:50:06 2004 From: pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Mon, 21 Jun 2004 23:50:06 +0200 Subject: Catching errors in attribute names at assigment References: Message-ID: Heather Coppersmith wrote: >> If you say __all__=["a","b","c"], those 3 attributes are the >> only ones valid for field/method accessing. So class.a=5 is ok, >> but class.d=5 raises exception. > ITYM __slots__ instead of __all__. My fault, __all__ is for module members, not class members. Sorry for that. -- Pawel Kraszewski FreeBSD/Linux E-Mail/Jabber Phone ICQ GG Pawel_Kraszewski at wp.pl +48 604 777447 45615564 69381 From jfdoyon at methane.ca Wed Jun 16 00:28:46 2004 From: jfdoyon at methane.ca (Jean-François Doyon) Date: Wed, 16 Jun 2004 00:28:46 -0400 Subject: Making classes from Metaclasses globally available Message-ID: Hello, I'm using MetaClasses to create classes. How do I make these new classes "globally" available? I probably just have to assign them to something magic, but I can't seem to figure out which one. if I do: MetaClass('Klass', (), {}) The resulting class needs to be assigned to something: myclass = MetaClass('Klass', (), {}) The problem is that I'm looping and don't know in advance how many classes there will be. So right now I have something like: msclasses[clsname] = MapServerMetaClass(str(clsname), (), {'schema':list,'__init__':MapServerClassInit}) inside a loop. Problem is I really don't want to have the classes stuck inside that dict. I want them "globally" available as if I had simply made a "class" declaration at the top of the file. Any ideas or suggestions? Thanks, J.F. From kenneth.m.mcdonald at sbcglobal.net Tue Jun 8 20:48:22 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 09 Jun 2004 00:48:22 GMT Subject: Is a 'bugfix' version of jed's pymode.sl editor config file available anywhere? Message-ID: I just started using the jed editor, and am really happy with it-- like emacs, but much, much friendlier. However, my python mode file (the one that came with the 0.99.16 precompiled version of jed that I got) isn't handling string highlighting properly-- it doesn't understand that '''This 'string' isn't really a string''' is a single triple quoted string, and instead treats the interior ' marks as string delimiters as well as (correctly) treating the ''' as single string delimiters. I took a quick look in pymode.sl and it didn't look hard to fix, for someone familiar with slang's DFA implmentation and its RE syntax--which I'm not :-( ). So I thought I would try here first. Thanks for any suggestions, Ken From news_nospam at fuglum.net Sun Jun 6 17:10:24 2004 From: news_nospam at fuglum.net (Erlend Fuglum) Date: Sun, 06 Jun 2004 23:10:24 +0200 Subject: AttributeError: cannot find method in module? Message-ID: I have tried and tried, but cannot figure out the source of the following error: AttributeError: 'module' object has no attribute 'menyHMTL' __doc__ = 'Attribute not found.' __getitem__ = > __init__ = > __module__ = 'exceptions' __str__ = > args = ("'module' object has no attribute 'menyHMTL'",) Some more information: 'menyHTML' is a function in a module named 'menymodul' which imports all fine. There is no other file named menymodul, and no variable named menymodul - so the naming should not be disturbed. Importing menymodul and using the function works fine from another module, just not from this one. What is it that I am not getting here? How can this be solved? Erlend From skip at pobox.com Thu Jun 10 19:07:19 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 10 Jun 2004 18:07:19 -0500 Subject: [script] dis/assembling mbox email In-Reply-To: <2is2ebFr1sbvU1@uni-berlin.de> References: <2is2ebFr1sbvU1@uni-berlin.de> Message-ID: <16584.59815.301032.131409@montanaro.dyndns.org> William> Time to time, I need to William> - extract main header/body from a MIME email, William> - parse and extract multipart segments, recursively, William> - walk through the email tree, and edit/delete/add stuffs William> - regenerate new MIME email. ... William> Usage are William> unmbox.sh dir < email William> mbox.sh dir > email ... You might be interested in the splitndirs.py script which is part of the Spambayes distribution. There is no joindirs.py script, but it's perhaps a five-line script using the mboxutils.getmbox function (also part of Spambayes). Skip From squirrel at wpi.edu Wed Jun 23 14:41:43 2004 From: squirrel at wpi.edu (Chris King) Date: 23 Jun 2004 11:41:43 -0700 Subject: Setting X properties in tkinter or wxPython References: Message-ID: <994b391.0406231041.53ef77bd@posting.google.com> > Anybody got an idea? I'm not very familiar with wxPython, but it seems that even native Tk can't set window properties (though the Tk C library can). Perhaps an alternative is to use python-xlib (http://python-xlib.sourceforge.net/). I'm even less familiar with that, but the functions Display.create_resource_object and Window.change_property look useful. Note that the Tk C library warns against using native X calls in place of its functions. From python1 at spamless.net Thu Jun 17 13:17:58 2004 From: python1 at spamless.net (python1) Date: Thu, 17 Jun 2004 10:17:58 -0700 Subject: Parsing by Line Data Message-ID: Having slight trouble conceptualizing a way to write this script. The problem is that I have a bunch of lines in a file, for example: 01A\n 02B\n 01A\n 02B\n 02C\n 01A\n 02B\n . . . The lines beginning with '01' are the 'header' records, whereas the lines beginning with '02' are detail. There can be several detail lines to a header. I'm looking for a way to put the '01' and subsequent '02' line data into one list, and breaking into another list when the next '01' record is found. How would you do this? I'm used to using 'readlines()' to pull the file data line by line, but in this case, determining the break-point will need to be done by reading the '01' from the line ahead. Would you need to read the whole file into a string and use a regex to break where a '\n01' is found? From dango at inc.com Wed Jun 30 20:01:27 2004 From: dango at inc.com (carlo v. dango) Date: Thu, 01 Jul 2004 02:01:27 +0200 Subject: reflection Message-ID: <77rbr1-175.ln1@gatekeeper.kadnet.dk> hello there I have searched the documentation in vein... :( I would like to be able to a) see all classes in the runing system b) inspect all classse that can be found in pythonpath (to look for classes not yet made instances of / loaded) how to perform these simple tasks? sincerely Carlo From squirrel at WPI.EDU Mon Jun 28 18:42:26 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 18:42:26 -0400 Subject: Question about alpha blending and low level drawing on widgets In-Reply-To: References: Message-ID: On Mon, 28 Jun 2004, Gabriele Farina *DarkBard* wrote: > 2) Use TK Canvas, but I think it does not understand alpha (am I right??) .. The Tk Canvas doesn't understand alpha per se, but it does allow you to stipple objects -- i.e. fill in only a certain percentage of points in the object. You only get a few different stippling levels (10, 25, 50, 75, and 90%, I think) and it's not true alpha blending, but it looks decent and may satisfy your needs. This will be the easiest option by far, since Tk is multiplatform and has a very powerful Canvas widget. From della at toglimi.linux.it Sun Jun 6 04:17:23 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Sun, 06 Jun 2004 08:17:23 GMT Subject: if does not evaluate In-Reply-To: References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: Tor Iver Wilhelmsen wrote: > x = (expr1, expr2)[something]; > > Keep in mind that this might break on some later release of Python if > they decide to make boolean its own type, but at least it works for > 2.3.3. I think (and I hope) it will never be so, since bool is already its own type and, as the documentation states, "In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively." So, even if this a little "perlish" :-), I think it will continue to work in future versions of python, since otherwise it would break too much existing code. -- Ciao, Matteo From mrjean1 at comcast.net Wed Jun 23 19:28:31 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Wed, 23 Jun 2004 23:28:31 GMT Subject: Determining caller's file and line number References: <8a638f47.0406231330.7d59152f@posting.google.com> Message-ID: <230620041639365943%mrjean1@comcast.net> Here is one example:
    
    from traceback import extract_stack as tb_extract_stack,
     
    def caller(up=0):
        '''Get file name, line number, function name and
           source text of the caller's caller as 4-tuple:
           (file, line, func, text).
    
           The optional argument 'up' allows retrieval of 
           a caller further back up into the call stack.
    
           Note, the source text may be None and function
           name may be '?' in the returned result.  In
           Python 2.3+ the file name may be an absolute
           path.
        '''
        try:  # just get a few frames
            f = tb_extract_stack(limit=up+2)
            if f:
               return f[0]
        except:
            pass
         # running with psyco?
        return ('', 0, '', None)
    
    
    /Jean Brouwers ProphICy Semiconductor, Inc. In article <8a638f47.0406231330.7d59152f at posting.google.com>, David Abrahams wrote: > Is there any way to determine the file and line number (if any) of a > method's invocation from within its body? > > Many Thanks in advance, > > Dave > -- > David Abrahams > Boost Consulting > http://www.boost-consulting.com From logistix at cathoderaymission.net Thu Jun 10 16:23:38 2004 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 10 Jun 2004 13:23:38 -0700 Subject: Source Code Generation Tool Message-ID: <3c91a864.0406101223.7c17926e@posting.google.com> # # libraryOfBabel.py # # This is a general purpose source code generation tool. # # It generates any code you may require for python, perl, rexx, # C, C++, befunge, ADA, ruby and other programming languages # # It will generate the source code for Python 3000 # # It is also capable of generating the complete works of # William Shakespeare, Friedrich Nietzsche, # and Raymond Chandler # import sys symbols = [chr(x) for x in range(128)] symbols.remove(chr(7)) def indexToSymbol(index): try: return symbols[index] except: raise Exception("invalid index %i" % index) def symbolToIndex(symbol): try: return symbols.index(symbol) except: raise Exception("Invalid Symbol '%s'" % symbol) def generateDocument(number): while number: div,mod = number / len(symbols), number % len(symbols) sys.stdout.write(indexToSymbol(mod)) number = div i = 1401448258002517817034703038066348000649199218 while 1: print '=' * 79 print 'DOCUMENT ID ', i print '=' * 79 generateDocument(i) i += 1 From irmen at -nospam-remove-this-xs4all.nl Mon Jun 28 16:49:28 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 28 Jun 2004 22:49:28 +0200 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: References: <40deae5e$0$65807$e4fe514c@news.xs4all.nl> <889cbba0.0406271027.39b3044@posting.google.com> Message-ID: <40E08458.10506@-nospam-remove-this-xs4all.nl> Mark wrote: >> Wow, that's not good, thanks for sharing that information with us. The >> heck of it is, people probably WOULD write articles for their magazine >> for their preferred set price (read: FREE!) if they would give them >> even a magazine subscription in return. But that's a total gyp, >> instead. > > > Huh? > > If you actually took the time to visit Py and read our Writer's > Guidelines you will find a big bold > headline that reads: "Complimentary PyZine subscription for Authors" and > Irmen of course got a free subscription. I did. And I will repeat an earlier reply here because it didn't reach everybody the first time: Mark: apologies for writing my story in the (too short) way that I did, you're comments are valid. What I wrote are the facts, but I may have expressed it too harshly. [Kamilche:] > Sorry to hear that you wasted your time! I didn't. The article *is* published. And I don't care about the money (I wrote the article at the time when PyZine had a different form, there was no talk about any author payment at that time). So again, it's not a big issue, I just wanted to share my experience. --Irmen. PS: everything has now been taken care of with PyZine. From mizrandir at hotmail.com Sun Jun 13 16:31:03 2004 From: mizrandir at hotmail.com (Mizrandir) Date: 13 Jun 2004 13:31:03 -0700 Subject: Help with os.system Message-ID: Hello, I'm a newbie with Python and there are some things I don't understand of os.system. I've managed to write a script that works in order to test some things: import os os.system('C:\\texmf\\miktex\\bin\\latex.exe "C:\Documents and Settings\User\Escritorio\sample2e.tex" -output-directory "C:\Documents and Settings\User\Escritorio"') os.startfile('C:\Documents and Settings\User\Escritorio\sample2e.dvi') This script launches the program "latex" and passes the input and output file names and directories. Afterwards it launches a dvi viewer to view the output. I have 2 questions: Why do I have to use double \\ in C:\\texmf\\miktex\\bin\\latex.exe (if not it does not work)? And why not in the other places? If I have the string "C:\Documents and Settings\User\Escritorio\sample2e.tex" stored in a variable, how could I use it? Thanks in advance, miz. From jepler at unpythonic.net Mon Jun 21 07:56:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 21 Jun 2004 06:56:13 -0500 Subject: can i define a new method at runtime? In-Reply-To: <7b22ae5b.0406181049.479d1a61@posting.google.com> References: <7b22ae5b.0406181049.479d1a61@posting.google.com> Message-ID: <20040621115612.GA2107@unpythonic.net> Something like the untested code below will work, without the need to "exec" anything. def verifyInteger(x): ... def verifyFloat(x): ... verifiers = {"ControlName1": verifyInteger, "ControlName2": verifyFloat, ...} class MyTextBox(TextBox): def __init__(self, controlname, ...): self.verifyfunc = verifiers[self.controlname] TextBox.__init__(self, ...) ... def change(self): self.verifyfunc(self.value) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ville at spammers.com Thu Jun 10 04:35:40 2004 From: ville at spammers.com (Ville Vainio) Date: 10 Jun 2004 11:35:40 +0300 Subject: Finnish Pythonistas in Espoo (Nokia Workshop) on Friday 11.6.2004? Message-ID: See you there! Perhaps there will even be a possibility for a beer or two, it'll be friday after all :-). -- Ville Vainio http://tinyurl.com/2prnb From http Sat Jun 19 12:31:19 2004 From: http (Paul Rubin) Date: 19 Jun 2004 09:31:19 -0700 Subject: OT: Chat server References: Message-ID: <7xn02zse5k.fsf@ruckus.brouhaha.com> "Miki Tebeka" writes: > I'm looking for a chat (IRC) server. > Nothing fancy. It has to be free, standalone and with logging. > Python based will be ideal. Twisted (www.twistedmatrix.com) includes IRC server functions. Logging is normally done at the client, not the server. Logging at the server is disrespectful of user privacy, to say the least. From klachemin at home.com Fri Jun 4 12:49:36 2004 From: klachemin at home.com (Kamilche) Date: 4 Jun 2004 09:49:36 -0700 Subject: Python 'Lets Me See The Forest' Message-ID: <889cbba0.0406040849.1d8bd884@posting.google.com> Man, I've been banging my head against a C program for a while now. I'm embarrassed to admit how long. I really want to use Python, as I mentioned in a prior post, but the speed hit is such that I'll probably use it only for prototyping. But boy, development sure is fast in Python! Today, while playing with it, I thought of a better way to arrange my data, that makes the program more flexible. It's a good enough idea to warrant redoing my code (even my C code) to take advantage of it. When I went to write up the pseudocode to process the new method, I found myself naturally using Python. C is just so... detail oriented. By the time I set up the data structures, do the string manipulation and memory management, I can hardly remember what it was I was initially trying to accomplish, much less think of a better way to do it! Maybe I'm just getting old... but Python just fits my idea of 'mental pseudocode' so well, it's hard to resist using it. Dictionaries ARE an underutilized concept in DP, and I was using them up the yin yang, even in my C program. Python meshes well with my programming style. --Kamilche From imbosol at aerojockey.com Thu Jun 3 21:13:08 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 3 Jun 2004 18:13:08 -0700 Subject: Optimizing multiple dispatch References: Message-ID: <60dfb6f6.0406031713.6d0a3814@posting.google.com> Jacek Generowicz wrote in message news:... > Jeff Epler writes: > [... Pyrex ...] > > 100000 loops, best of 3: 2.41 usec per loop > [... List comprehension ...] > > 10000 loops, best of 3: 25.3 usec per loop > [... map ...] > > 100000 loops, best of 3: 17 usec per loop > > (I'm pretty sure that should be 10**5 loops in the list comp case) > > Hmm, ok, the extension seems to be significantly faster. This > surprises me, because everything that executes in > "tuple(map(type,args))" is coded in C already, so I don't see where > the gain is coming from. Because not all C is the same. For example, to execute something like "type(m)", Python has to construct a tuple for the arguments, and call the type object with it. The type object new function has some special casing (to get the behavior of the old type function) and argument checks and stuff in it. OTOH, PyObject_Type is probably a macro defined like this: #define PyObject_Type(_obj) (_obj->ob_type) So, even though type(m) is "coded in C already", it's not really fast C. -- CARL BANKS From newsgroups at jhrothjr.com Wed Jun 30 07:19:29 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 30 Jun 2004 07:19:29 -0400 Subject: Status of PEPs? References: <2kfjf7F1nk33U1@uni-berlin.de> Message-ID: <10e58dpcbogogce@news.supernews.com> "Thomas Reichelt" wrote in message news:2kfjf7F1nk33U1 at uni-berlin.de... > Hello Python-Fans, > > A few months in the past, I learned the Python language and was very pleased > of it. I have now written many scripts for myself and this opinion stayed, > not to say, it became more intensive. > > Recently I have discovered the PEP Archive, and my question is now this: > There are many open ("under consideration") PEPs that would incorporate > useful features into the language, such as the do-while statement, the > switch statement or the __main__ function. However, most of these proposals > are several years old. Though implementations seem to exist for the > proposals, no action is taken about them. Why is this so? What has to be > done for a proposal to make it into the language? > > Thank you for answering a dumb question... It's not a particularly dumb question. The missing piece is that there are a limited number of core developers, and you need to get a concensus among them on the Python Dev mailing list that this particular proposal is more worthy of their time than other competing proposals. You also need to get it past Guido. Also note that in two cases you would be adding keywords, which impose a significant forwards compatibility issue, while the third has a major issue of non-obviousness. The proposals you mention all fall into the category of "useful, but there are other ways of doing that job that work, are well accepted, and are not a significant burden in terms of either developer time or comprehensibility." Put another way, there was a significant against component in the discussion from the "keep Python simple" crowd. In other words, to move any of them forward would require submission of a complete implementation that would work in the current development tree, together with the necessary documentation changes, thorough tests, and so on and so forth. That is, someone who wants to see any of these in Python needs to do the work themselves. A good example of this is the work being done by Facundo Batista on PEP 327 (Decimal Arithmetic). There's been widespread agreement for a long time that something should be done about decimal arithmetic, but until he stepped forward, it sat on dead center. Now it looks like we're going to get it for Python 2.4, so it may be possible for us to get a usable currency type in Python 2.5 (building on the decimal type.) John Roth > > -- > greetz tom From fishboy at spamspamspam.com Sat Jun 5 23:12:56 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 03:12:56 GMT Subject: C-program->Python->mxDateTime Problem References: Message-ID: <2235c09phutvglu59762ri821bpt19okj1@4ax.com> On Wed, 2 Jun 2004 11:03:34 -0400, "Michael R Seefelt" wrote: >I have written a simple C-program that loads a Python Function that >connects to a PostgreSQL database> When I only load and execute the >Python function all works OK. If I call the Python function a second >time I get the following: Called PyObject_CallObject Traceback (most >recent call last): > File >"/home/mike/src/arthur/query_server/query_analyzer/Query_Analyzer.py", >line 25, in processQuery > from pyPgSQL import PgSQL > File "/usr/local/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line >388, in ? > raise ImportError, \ >ImportError: You need to install mxDateTime > (http://www.egenix.com/files/python/eGenix-mx-Extensions.html) > >Any ideas? > You dont say, so I'm wondering, do you have mxDateTime installed on your path? ><{{{*> From dave at lifetimeaddress.com Thu Jun 10 18:28:30 2004 From: dave at lifetimeaddress.com (David Hoare) Date: Thu, 10 Jun 2004 18:28:30 -0400 Subject: finding the right data structure...? Message-ID: Hi all... I'm a python newbie, migrating from a fair bit of VB experience. I have an application in VB that I was using as a sample to 're-create' it using python. It involved storing information about sound and light cues (this was for a lighting / sound theater controller). The data was stored like this: - a custom 'type' called lightCue which looked like this: > Type lightCue > Name As String 'optional short name > Description As String 'optional longer description > CueLine As String 'optional line in script where cue occurs > upTime As Single 'time for lights fading UP > downTime As Single 'time for lights fading down > chanLevel(0 To maxChan) As Single 'stored intensity level (0 to 100) for each channel on the lighting console > End Type I then created an array... dim lq(1 to 200) as lightCue ...allowing me to iterate through the list of cues for any information I needed I am struggling to come up with a similar (in function) way to do this in Python. Any ideas? I think I understand about classes, but then I need to 'name' each instance of that class when they are created, don't I? Thanks for your guidance! David Hoare dave at lifetimeaddress.com From has.temp2 at virgin.net Thu Jun 3 11:15:24 2004 From: has.temp2 at virgin.net (has) Date: 3 Jun 2004 08:15:24 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406030715.314e68c8@posting.google.com> Peter Maas wrote in message news:... > David Fraser schrieb: > >> Did you find these alternatives unsatisfactory? If somebody wants > >> to use a Python templating framework why should he prefer > >> HTMLTemplate? > [..] > > It looks cool because it doesn't embed Python code in the template. > > Do any of the other frameworks have this approach? > > That's your personal taste. While taste certainly plays a role, I think there are also sound technical arguments to be made for complete code-markup separation. > If this is what you like about HTMLTemplate > that's fine. I don't bother wether a template language contains Python > code or not. To answer your question: > > Hamish's example rewritten in TAL (TAL lines below Hamish's equivalents): > > > > TITLE > ###TAL TITLE > > > > > This is embedded code, though in a custom language rather than Python. This has a couple of advantages: it's terser (less typing) and less abstract (easier for non-programmers to cope with). The disadvantages are: you've another language to learn before you can use the system, you're limited in what you can do and how you do it by that language's featureset, and code (Controller) and markup (View) are tightly coupled (loose coupling makes for a more flexible and easier to maintain architecture, while the standard argument in favour of tight coupling - raw performance - doesn't apply in this case). Also, the terseness and minimal abstraction are only really advantages in simple cases; with more complex systems the number of keystrokes saved is an insignificant proportion of the total typing done, and the lack of abstraction becomes a significant disadvantage (like having to write a 500-line program as a single continuous main() routine without procedures or namespaces to structure it). I'm not sure if TAL supports callbacks into Python code. ZPT allows you to do this, allowing you to fall back to Python for tasks that the templating language isn't able to perform itself; your basic two-tier hybrid. The two other approaches mini-language based systems seem to take are: - expand their templating languages till they become full Turing-complete programming languages in their own right - keep the templating language restricted to the absolute basics: insertion, conditionals and iteration. The fundamental folly of the first approach ought to be obvious enough; see Greenspun's Tenth Rule. The second seems quite sensible, at least on paper: state that it is not the templating language's job to be a general-purpose scripting language, limit its scope to providing only the core functionality necessary to insert pre-prepared data into the template, and leave the client to do that data preparation themselves. In practice though, it seems terribly inefficient and somewhat redundant to have your data in one highly structured form, e.g. a collection of database tables, file objects, native data structures, etc., and have to munge that into another highly structured form, e.g. a large, deeply-nested lists-and-dicts structure directly corresponding to the template's final structure, just so the templating engine can morph this structure into yet another form. It would be more sensible to skip the middle step, eliminating all restrictions on the type or form of data that the template can consume. The temptation then is to evolve the second type of system into the first; but then you're back to chasing that never-ending feature request list for more power, more flexibility, more convenience, and its Greenspun's rule all over again. ... > But I wanted to read Hamish's thoughts. Heh, no chance! My tinfoil beanie successfully blocks your devilish CIA X-Ray Secret Mind Reading Abilities, so I'm afraid you'll just have to stick to standard plaintext communication protocols. Damned inefficient, I know, but I can't risk you finding out where the treasure is buried. ;) > That would be helpful for programmers because it takes some time > to find your way through the maze of Python template languages. I am, of course, happy to wait till the rest finally declare that "It's a fair cop, guv!" and gracefully concede defeat. (Like that's ever gonna happen, hey?;) > I prefer Cheetah. Teensy request: I think it'd help our readers if you could also show your Python code for hooking up to these templates and feeding them data; allow them to compare like-against-like. That'd be cool. ... Hamish's example in Cheetah: > > > > $title > > >
      > #for $link in $links >
    • > $link.text >
    • > #end for >
    > > I like Cheetah less than TAL. TAL, like HTMLTemplate, treats the template's HTML as a first-class citizen; Cheetah is much closer to the original macro processors from which all PHP/ASP/Cheetah/etc. style systems are basically descended and treat everything non-macro pretty much as dumb, meaningless character streams. Like I think I've said elsewhere, I've already designed, written, shipped and canned this sort of system myself before moving to DOM-derived designs, so I've firsthand experience from both sides of the fence and am quite certain that while there's some situations where the former is better, these are really just corner cases and the center field would be completely owned by HTMLTemplate-style systems if it hadn't been for those pesky PHP kids doing a BASIC upon us first. (Ah well; fair fight, early worm, and all that. Can't blame 'em for being successful; besides, it's never _too_ late to Change...:) ... > Advantages: > > - No magic No magic to HTMLTemplate either. It simply uses a more sophisticated model to describe and construct renderable templates. I'd suggest a good comparison is Apple's excellent Interface Builder, which allows desktop applications' Views to be constructed without writing or generating a single line of program code. In Cocoa GUI construction, everything is done by manipulating object instances directly, assembling them into a live, fully-functional object model and adding a smidgin of binding information to connect them to the application's Controller layer. [1] > - placeholders occupy the places of their replacements > - logic is visible in the template > -> you see what's going on > - logic is visible in the rendered html page > -> you see where the replacements will go These aren't outright advantages; merely differences in goals. Plus other advantages, like the ability to mockup your HTML templates to look like finished pages - very helpful for designers and clients in visualising their designs - are conspicuous by their absence. (Note that TAL and some other code-in-markup systems also share this ability, so it's not an advantage unique to DOM-derived systems; although they're certainly an excellent natural fit for it. Conversely, Cheetah's at a decided disadvantage here, since making Cheetah templates look anything like the pages they'll eventually produce is going to be rather hard with all that macro-style stuff strewn throughout.) PHP-style systems' lack of abstraction makes them particularly appealing to folk with little or no abstract design skills; i.e. non-programmers (and crap programmers, if you're being brutally honest;). This is certainly a valuable feature for those users, but I think this is oversold as an advantage while its disadvantages - particularly the ease with which is can yield the most amazing spaghetti code when put to use in non-trivial tasks - are simultaneously undersold to everybody else. Your average Python user, for example, shouldn't have any conceptual problems dealing with the stronger abstractions of DOM-derived systems like HTMLTemplate; and really, anyone that can understand and write basic DHTML should quickly find themselves at home. By comparison, while HTMLTemplate presents newcomers with a slightly greater conceptual first hurdle to pass, once over it there isn't much else left to learn. Meanwhile, the system itself scales extremely well: while trivial code examples like the introductory tutorial on my site can always be rewritten to look smaller and simpler in an embedded language (which I'd never dispute, btw), I think you'll really start noticing the difference as you move to larger, more complex "real-world" templating tasks. For example, it'd be most interesting to see a code comparison between Cheetah/TAL/PSP/EmPy/PTL and HTMLTemplate for something like the scripting terminology renderer in my appscript package. (Though at several hundred lines of HTML and code I won't mind if nobody takes me up on this; it'd take a good few hours' work with no actual reward at the end of it.:) ... Incidentally, one of the projects on my "Fun" list is to write a simple template macro preprocessor that can read a simple TAL-like template and generate HTMLTemplate-based View and Controller layers from it. This could make HTMLTemplate a great sell for developers writing "Aunt Millie" shrinkwrapped software (e.g. stuff like Fogcreek's CityDesk): non-programmers and "lite" users could use a simple embedded macro expansion system to produce simple HTML pages/customise their own; advanced users could dive straight in at the Python API level. The advantage of this approach is that users who start off using the macro system can seamlessly transition to the more powerful underlying programmatic system; they can even take their previous work with them, simply throwing away the original macro-based templates after outputting the code-generated versions to file for future modification and use. So this is definitely something I've thought about; the only difference is I'd answer it with a loosely coupled, multi-layered, componentised solution, not a big monolithic system that needs a chainsaw to reshape into any form not explicitly provided for by its designers. ... > - Cheetah templates everything, not only markup HTMLTemplate's motto here would be: "Don't bite off more than you really need to chew." As I think I've said elsewhere, most of its development history has involved throwing _away_ functionality whose presence did not belong in HTMLTemplate or whose cost could not be sufficiently justified to merit inclusion. In this case, responsibility for non-HTML templating has been turned over to texttemplate, which has been deliberately designed as a general-purpose templating engine rather than optimised specifically for working with HTML. I could just as easily turn this argument around by saying that Cheetah spreads itself too thinly, and adds unnecessary baggage for users who only want to do HTML templating. ... Anyway, I think you really need to approach HTMLTemplate on its own terms. It was never intended to be yet-another-PHP-style-macro-preprocessor-turned-into-full-blown-language templating system. It's actually an example of convergent evolution: while in the large it aims to solve the same problems as Cheetah et-al, it does so from completely different first principles and influences and with different detailed goals: total designer/programmer separation; desktop application architecture practices; DOM/Apple Event Manager object model; minimalist name-based object-code bindings. Now, the macro processor-style approach certainly works, and has an advantage in working equally well with any template type, while HTMLTemplate is limited to SGML-based markup (you'll need to use texttemplate[2] for templating other types of text). But ultimately it achieves its aims more through brute force than real elegance. It generally has to expend quite a bit of effort to reach its goals, and a lot of hard work that is, unfortunately, entirely self-imposed. A quick comparison of the Cheetah and HTMLTemplate APIs and codebases will easily demonstrate: - Cheetah's API consists of a complete built-in custom scripting language in addition to its Python-based "housekeeping" API, while the codebase spans twenty-odd modules and a C extension containing several thousand lines of code. - HTMLTemplate's API consists of four public classes [3] with under a dozen properties and methods between them, and the implementation is precisely 333 lines long. HTMLTemplate's entire API can fit comfortably within Cheetah's housekeeping API, with room left over. Cheetah's setup scripts alone run to a couple hundred LOC; HTMLTemplate is mostly implemented in that. I think if you're going to measure the two, you seriously have to consider these aspects as well, because they have major implications for things like user learning curves, developer maintenance, and, ultimately, reaching that magical v1.0 release that says "This System is Officially Complete." Cheetah is a helluva impressive achievement in itself; I can't imagine how many man-hours, how much blood sweat and tears have gone into getting it to where it is today. Though I'm willing to bet it's no more than I've put into getting HTMLTemplate to where it is today. The only difference is, looking at HTMLTemplate you can't actually see the many hundreds of hours and thousands of lines of code that it took me to get there, because I spent several hundred more hours getting rid of almost all of those thousands of lines of code. Like being a professional conjurer: you spend many long years making amazingly sophisticated and skillful sleight of hand appear to all the punters as if it took absolutely _no_ effort at all. Under those circumstances, y'just can't win...;) ... Funnily enough, if I'm worried about anything, it's that HTMLTemplates comparatively tiny size and simple API will cause casual viewers to assume it must be a crude, shallow, underpowered system only fit for trivial templating tasks. Because, you know, Real Templating is a Serious Business, and requires Seriously Large Templating Technologies like PHP, Cheetah, Velocity, etc, etc. After all, all that heavy-duty engineering must exist for a damn good reason, mustn't it? I mean, folk surely wouldn't go to all the trouble of writing it if it _weren't_? The single most important lesson I've learnt from developing HTMLTemplate's predecessors is that although learning how to factor and refactor program code well is a valuable skill, learning how to factor and refactor program _design_ is a hundred times _more_ valuable than that[4]. Because ultimately it doesn't matter that much how talented a coder you are: if the problem is split along just the right plane, even an average programmer like myself can, at the end of the day, outstrip one with ten times the coding skills who misses the natural grain and smacks it sideways instead. But anyway, I should shut-up on this angle before I start sounding like some insufferable Smalltalk/Lisp/Unix philosophy weenie. ;) ... Anyway, hope this mental splurge has been of some use to you (and anyone else that's managed this far). Cheers, has -- [1] There are some differences, of course: an IB GUI is assembled via drag-n-drop whereas HTMLTemplate uses compiler directives that indicate the type, name and relative location of each object to create; and IB pickles the resulting View object models for later rehydration and use, while HTMLTemplate users will generally compile their Views immediately before use.[1] [1a] Incidentally, the original HTMLTemplate did employ pickling, but that's because it was written in AppleScript, where it takes several seconds to compile a template (mostly because I had to resort to code generation to get around its lack of deep language features like introspection and dynamic slot addition; fortunately, its built-in object serialisation abilities makes pickling a breeze - a Smalltalk influence, I think). Eliminating the need for compiled template pickling was a major aim of the Python port, and quite successful, I think: HTMLTemplate/Python compiles templates in a few milliseconds/tens of milliseconds. [2] Note that the current texttemplate release, 0.1.0, has an older more complex API that I've since reworked for HTMLTemplate and am in the process of reworking for texttemplate; so I don't really recommend using the 0.1.0 version as its API _will_ be changing soon. [3] I fudge the exact number in the documentation; there's several subclasses I don't bother to distinguish between as the user has no need to know about these (one of the compromises I had to make in porting a nice simple prototype-based OO design to a less flexible class-based language). [4] That's 10x difference in API complexity times 10x difference in code length, if you're wondering...;) From a at a.invalid Tue Jun 8 00:10:42 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 08 Jun 2004 04:10:42 GMT Subject: left-quote ( ` ) on International keyboards [Prothon] In-Reply-To: References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: <6%axc.6$0N1.3@read3.inet.fi> Mark Hahn wrote: > Is $ easier to type on foreign keyboards? Well.. It's AltGr+4 on the Finnish keyboard, so not too hard. Easier than {[]}\, since they are AltGr+7890+ and you can really do them with one hand, whereas @?$ can be done with two hands. -- Timo "WT" Virkkala From brian at sweetapp.com Fri Jun 25 12:32:29 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 25 Jun 2004 18:32:29 +0200 Subject: ANN: Vancouver Python Workshop - Preliminary talk list available In-Reply-To: <40D86489.5060604@sweetapp.com> References: <40CF1521.5040901@sweetapp.com> <40D5D59A.4060004@sweetapp.com> <40D86489.5060604@sweetapp.com> Message-ID: <40DC539D.2060206@sweetapp.com> A preliminary list of talks has been compiled for the upcoming Vancouver Python Workshop. The list can be found at the end of this e-mail. Conference registration is only open until Wednessday (June 30th) so you should register as soon as possible. For general conference information, see: http://www.vanpyz.org/conference About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Tentative Talk List =================== This list is subject to change and does not included tutorials for beginning Python programmers. It also does not reflect the scheduling of the talks in any way. "Python Question and Answer Session" - Guido van Rossum "A strategic commercial perspective on ... Python? Really?" - David Ascher "Taking control of Windows" - Andy McKay "Python Quirks, Gotchas and Warts" - Paul Prescod "Komodo's Code Intelligence System" - Trent Mick "Using Zope/Plone with Relational Databases" - Joel Burton "Just add water: a newbie's guide to customizing Plone's look and feel" - Andrew Coates "Using Python and Zope to write a movie restoration system" - Ian Cav?n "Extending Python With Pyrex" - Fraser Hanson "Constraint Programming in Python" - Toby Donaldson "Python Optimization" - Brian Quinlan "Twisted Picture: Building a client-server app with WxPython and Twisted" - Carlos Choy "Blocks & Views" - Scott David Daniels "Groupthink: the approaches to collaboration in Plone" - David Morriss "Open Source GIS with Python" - Mishtu Banerjee "Keep It Simple with PythonCard" - Kevin Altis "Stagehand - A Python BPEL4WS Implementation" - Andrew Francis "The Prothon Language" - Mark Hahn "Pygame: Implementing the big ideas from little developers" - Dethe Elza "Using Plone to devolve Web site management and maintenance" - Dominic Hiles "Using PyObjC to Avoid Writing Code" - Jim Tittsler "Using Plone to publish the Mouse Atlas of Gene Expression" - Kevin Teague "Object-Oriented Basics" - Jim O'Leary "New Models for Processing Text and XML with Python" - Sam Wilmott Cheers, Brian From tdelaney at avaya.com Wed Jun 2 23:25:35 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 3 Jun 2004 13:25:35 +1000 Subject: Triple quoted repr Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE018EFF90@au3010avexu1.global.avaya.com> Edward C. Jones wrote: > On 2003-09-04, Rasmus Fogh said: > > > I need a way of writing strings or arbitrary Python code that will > > > > a) allow the strings to be read again unchanged (like repr) > > b) write multiline strings as multiline strings instead of escaping > > the \n's. > > > > A repr function that output triple-quoted strings with explicit > > (non-escaped) linebreaks would be perfect. > > > > Failing that, what is the simplest way to get close to the goal? > > There were no responses. Anyone have an answer? Perhaps something like: s = repr("'''multi\n'line'\nstring'''") s = "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''", "\\'\\'\\'"),) which changes \n to a linefeed, \r to a carriage return, and ''' to an escaped form (in case you have a triple-quoted string with the same quote character). Tim Delaney From fumanchu at amor.org Thu Jun 10 22:37:08 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 10 Jun 2004 19:37:08 -0700 Subject: Deeply-nested class layout suggestions wanted Message-ID: Kirk Strauser wrote: > ...I plan to subclass the heck out of each of these > classes, with overloading appropriate to the type of data source being > represented. For example, a DataSource that retrieves images > from a POP3 mailbox might be defined like: > > POP3Retriever.py: > [snip] > > Such a class will be further subclassed into modules like > POP3TiffFile, POP3ZipArchive, etc., the goal being to keep all > functionality as high in the inheritence hierarchy as possible, > so that the "leaf" modules define nothing more than the > bare minimum possible to distinguish each other. I'd > like to carry this to the point of not defining any classes > that are the same between siblings (the DataSource class > is identical between all of the different POP3Retriever > subclasses, for example). > > [1] We receive files from our customers via many means - fax, > email, ftp, you name it. I'm developing delivery method > agnostic tools to manipulate those files and flatly refuse > to write n tools to handle n methods. First thought: seeing two example classes named "POP3TiffFile" and "POP3ZipArchive" makes me wonder if this isn't a better candidate for delegation than subclassing. That is, a "POP3Retriever" would *possess* a "ZipArchive" handler rather than *be* a ZipArchive handler. Another instance of the same POP3Retriever class could possess a TiffFileHandler rather than *be* a TiffFileHandler. """app/handlers.py""" class FileFormatHandler(object): def handle(self, ...): ... class TiffFileHandler(FileFormatHandler): def handle(self, ...): ... class ZipArchiveHandler(FileFormatHandler): def handle(self, ...): ... -------------------------- """app/retrievers.py""" from app import handlers class FileRetriever(object): ... class POP3Retriever(FileRetriever): def __init__(self, handler=handlers.ZipArchiveHandler): self.handler = handler If by "keep all functionality as high in the inheritance hierarchy as possible", you imply "keep the module heirarchy flat", then delegation is a good technique. But I'd be interested to hear why you did not choose it (yet ;). Robert Brewer MIS Amor Ministries fumanchu at amor.org From fishboy at spamspamspam.com Sun Jun 6 00:06:24 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 04:06:24 GMT Subject: A little help had anyone used the email-dir.py Email Module References: Message-ID: <5m55c014l2i7ajcpf8i7n9jhu4f6e39n02@4ax.com> On Fri, 04 Jun 2004 10:19:19 +0100, Chuck Amadi wrote: >A little help has anyone used the email-dir.py Email Module ,I have downloaded >the example and would like some pointers to get it going . > >For example Have I got to add any parameters to python script or Do I just use >the command line. > > > >Cheers > >Chuck > Chuck, You sure are persistant. I'm going through comp.lang.python and this is the fourth message from you I've found. Anywoot, try executing the script directly like I said in another post. I think maybe the arguments are not getting parsed correctly because you start with python ... Wait a minute, I just realized that you are not specifying the file name needs to be: email-unpack.py -d /home/chuck/surveyResults nameofemailfile see if that does it ><{{{*> From mark at prothon.org Thu Jun 24 20:06:33 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 24 Jun 2004 17:06:33 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: Christos TZOTZIOY Georgiou wrote: >> Or, he might just want you to repeat it a third time. ;-) > > I am actually reading through Usenet... the newsserver link is fast, > but the arrival order of posts is not guaranteed, so I don't read > messages in the same order as people using the mail list. Often I > post a reply to a single message, only to find in the next > synchronisation that others did reply even earlier than me saying > more or less the same things. Other times I don't bother, saying > "somebody else will reply to this trivial question", and next day I > find out that everybody else thought the same as I did. That's > Usenet (sigh). I'm sorry if I was rude. It is always when I make a stupid remark on a public forum that I am asked to repeat it :-) No one ever asks me to repeat a witty gem. (Of course maybe that never occurs). From danb_83 at yahoo.com Sat Jun 12 17:56:07 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Jun 2004 14:56:07 -0700 Subject: kid wants to know more about color on the screen References: Message-ID: "Doug Mitchell" wrote in message news:... > Dear Group, > > My son who is in grade 7 has *just* started going through the book "Python > for the Absolute Beginner" by Michael Dawson. He and I have no programming > experience. He is beginning this on an old win 95 computer with Python 2.2 I > think. > > He is getting a bit frustrated with color coding. ... > Later on he says that strings within quotes will be green as expected and > then all of a sudden on the next line it will stay black :(. And when he > does a run script there will be a syntax error as Python wont recognize this > 'black' string but then on another occasion the 'black' will run ok :(. It sounds like you're using a syntax highlighting text editor, that is, it displays code in different colors depending on whether it's a keyword, a comment, a string literal, etc. This highlighting helps make it easy to see syntax errors (code that's in the wrong color is a syntax error), but it's not part of the *.py file itself, and therefore doesn't affect the output of the program. However, it is possible to print colored text in Python. Under Linux, you can print "ANSI escape sequences" (Look it up on Google) to your terminal. These are strings starting with the control character '\x1B' that, when printed, change the color of the text, or move the cursor, or even change the frequency of the beep you hear when you print '\a' (you can use this to make Python play simple music). I don't know how to do it on Windows, but there might be something for it in the msvcrt module. From http Fri Jun 11 16:38:38 2004 From: http (Paul Rubin) Date: 11 Jun 2004 13:38:38 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: <7xekolx229.fsf@ruckus.brouhaha.com> David Bolen writes: > It lets you write code like: > > void some_function(void) { > Lock_object lock(some_parms); > > - do something needing the lock - > } There's a PEP for something like that in Python: http://www.python.org/peps/pep-0310.html I think that's greatly preferable to dictating that the GC system act a certain way and free resources as soon as they go out of scope. That's just not the correct semantics for GC. GC should simply create the illusion for the application that all objects stay around forever. From rschroev_nospam_ml at fastmail.fm Sat Jun 19 09:29:10 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 19 Jun 2004 13:29:10 GMT Subject: Queue module and Python Documentation Rant In-Reply-To: References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > Roel Schroeven wrote: > >>Well, not everybody: I don't like the PHP documentation at all. Part of >>the problem is precisely the user comments: > > > You don't have to read them :-) They are clearly distinguished from the > documentation itself. Yes, of course, but sometimes one or a few of them contain essential information (that really ought to be in the documentation itself), and there's no way to knowing except reading them all. But it doesn't matter that much, since I'm not doing any PHP development anymore, and most people who do seem to like the docs. Just wanted to let the world know about the minority opinion :) -- "Codito ergo sum" Roel Schroeven From peter at engcorp.com Mon Jun 21 20:57:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 20:57:13 -0400 Subject: Cannot create a new file In-Reply-To: <40d77b19$1_3@aeinews.> References: <40d77b19$1_3@aeinews.> Message-ID: Eric Belanger wrote: > Ive created a little script which, at the end of it, deals with copying > two files. All the script works fine except when its at the copy > line(s). Nothing gets copied, it crashes at the first open() line. > > Before using open() I made it the lazy way first and wrote system("cp > "+file1+" "+file2), but gaves me that message: > > IOError: [Errno 2] No such file or directory: > '/home/bilange/.hnb-backup/1087861694' Could you please include the full traceback, cut and pasted from the console, so that we can see the parts just before what you show above? Also it would probably be a good idea to include a code snippet showing the previous ten-or-so commands just before the failing line. -Peter From NOmanlio_perilloSPAM at libero.it Fri Jun 18 12:32:32 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Fri, 18 Jun 2004 16:32:32 GMT Subject: [ANN] isrealfile function Message-ID: Hi. Maybe this function can be useful for someone: import os def isrealfile(file): """ Test if file is on the os filesystem """ if not hasattr(file, 'fileno'): return False try: tmp = os.dup(file.fileno()) except: return False else: os.close(tmp); return True I have implemented this function for testing if a Python script is being executed by Python.exe or Pythonw.exe. In the latter case, in fact, Microsoft implementation of stdout/stderr is broken. [sitecustumize.py] import sys if not isrealfile(sys.__stdout__): sys.stdout = NullStream() if not isrealfile(sys.__stderr__): sys.stderr = NullStream() Where NullStream is a file like class that writes nothing. P.S. I have only tested this function on Windows XP Pro. Regards Manlio Perillo From squirrel at wpi.edu Wed Jun 23 20:40:23 2004 From: squirrel at wpi.edu (Chris King) Date: Wed, 23 Jun 2004 20:40:23 -0400 Subject: Writing binary to stdout In-Reply-To: <2jubemF14b1jjU1@uni-berlin.de> References: <2jrglkF153jroU1@uni-berlin.de> <2jsm1iF7ott5U4@uni-berlin.de> <2jubemF14b1jjU1@uni-berlin.de> Message-ID: <10dk8nbr1m51k04@corp.supernews.com> Paul Watson wrote: > Even when I try to use low-level I/O it does CRLF interpretation. What am I > doing wrong? Are you using Cygwin? It will automatically CRLFify anything it thinks should be (I'm not sure what the exact critera are); this has bit me before, too. There's an option to disable it in Cygwin setup. This is being passed on to the script because the stdout redirections are done in Cygwin, not in Python. From nhodgson at bigpond.net.au Fri Jun 25 02:14:12 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 25 Jun 2004 06:14:12 GMT Subject: Script to condense the review page References: Message-ID: Skip Montanaro: > I help moderate a couple mailing lists on python.org. The biggest challenge > for me is vetting messages which were held for review. The information > density in the Mailman review page is pretty low, typically showing only two > or three messages per screen. On Windows using Mozilla, I had to comment out the os.unlink(htmlfile) as the file is gone before the browser can open it. Maybe sleep for 5 seconds before unlinking? I would like to have a web page that merged all four MailMan lists I manage together with duplicated messages only appearing once so they can be removed quickly. Neil From lyuan at ucdavis.edu Sat Jun 5 20:49:41 2004 From: lyuan at ucdavis.edu (lyuan) Date: Sat, 05 Jun 2004 17:49:41 -0700 Subject: write a bitmap using python In-Reply-To: References: Message-ID: Hi, Paul, Thanks for your help. The code is indeed clear and illustrative. I wonder under what license is your code distributed? Do you mind if I include part of your code into my code? I'm not writing anything commercial, but instead a scientific data analysis program. thanks Lihua Paul McGuire wrote: > "lyuan" wrote in message > news:c9ruf0$n4t$1 at woodrow.ucdavis.edu... > >>Hi, >>How can I write a bitmap using python? I have some integer data and >>want to generate a bitmap graph for visualization. Any suggestion will >>be appreciated. >>Sorry if this is an FAQ, BTW, where can I find the FAQ of this list? >> >>thanks >>Lihua > > > I chased this down last fall when I needed to visualize some data much as > you describe. > > http://www.geocities.com/ptmcg/python/index.html#bmp > > Follow the 'module' link to retrieve the bmp.py source. > > -- Paul > > From ptmcg at austin.rr._bogus_.com Mon Jun 7 11:41:53 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 07 Jun 2004 15:41:53 GMT Subject: My Experiences Subclassing String References: <8089854e.0406070423.5d2d1d71@posting.google.com> Message-ID: <510xc.52456$mQ4.51566@fe2.texas.rr.com> "Fuzzyman" wrote in message news:8089854e.0406070423.5d2d1d71 at posting.google.com... > I recently went through a bit of a headache trying to subclass > string.... This is because the string is immutable and uses the > mysterious __new__ method rather than __init__ to 'create' a string. > To those who are new to subclassign the built in types, my experiences > might prove helpful. Hopefully not too many innacuracies :-) > The bit I couldn't get (and I didn't have access to a python manual at > the time) - if the __new__ method is responsible for returning the new > instance of the string, surely it wouldn't have a reference to self; > since the 'self' wouldn't be created until after __new__ has been > called...... > > Actually thats wrong - so, a simple string type might look something > like this : > > class newstring(str): > def __new__(self, value): > return str.__new__(self, value) > def __init__(self, value): > pass > > See how the __new__ method returns the instance and the __init__ is > just a dummy. > If we want to add the extra attribute we can do this : > > > class newstring(str): > def __new__(self, value, othervalue): > return str.__new__(self, value) > def __init__(self, value, othervalue): > self.othervalue = othervalue > > The order of creation is that the __new__ method is called which > returns the object *then* __init__ is called. Although the __new__ > method receives the 'othervalue' it is ignored - and __init__ uses it. Fuzzy - I recently went down this rabbit hole while trying to optimize Literal handling in pyparsing. You are close in your description, but there is one basic concept that I think still needs to be sorted out for you. Think of __new__ as a class-level factory method, not an instance method. That first argument that you passed to your example as 'self' is not the self instance, it is the class being new'ed. By luck, even though you called it 'self', you passed it to str.__new__ where the class argument is supposed to go, so everything still worked. The canonical/do-nothing __new__ method looks like this: class A(object): def __new__(cls,*args): return object.__new__(cls) There's nothing stopping you from looking at the args tuple to see if you want to do more than this, but in truth that's what __init__ is for. Here's a sample of using __new__ to return a different class of object, depending on the initialization arguments: class SpecialA(object): pass class A(object): def __new__(cls,*args): print cls,":",args if len(args)>0 and args[0]==2: return object.__new__(SpecialA) return object.__new__(cls) obj = A() print type(obj) obj = A(1) print type(obj) obj = A(1,"test") print type(obj) obj = A(2,"test") print type(obj) gives the following output: : () : (1,) : (1, 'test') : (2, 'test') HTH, -- Paul From fumanchu at amor.org Sun Jun 6 03:54:33 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 6 Jun 2004 00:54:33 -0700 Subject: Dynamically adding methods to objects? Message-ID: damian birchler wrote: > I'm wondering if it is possible to automatically dynamically add > methods to a class instance. For example, if there is a class Foo with > one method named > add_function and an instance of Foo f - > > class Foo: > add_function(self, name, args): > # ... > # ... > > f = Foo() > > -, could one add arbitrary methods to f calling its method > add_function? > > I know how to do it manually, I just define a function and assigne it > to f - > > def bar(): > pass > > f.bar = bar -, > but what if this should be done at runtime. How can I get the string > passed to f.add_function as name to be the name of a new function in > the function's definiton? Yes, it is possible. Have a look at new.instancemethod: http://docs.python.org/lib/module-new.html Then hop over to the Python Cookbook for implementations: http://aspn.activestate.com/ASPN/Python/Cookbook/ HTH! FuManChu From walter at livinglogic.de Fri Jun 4 13:26:23 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Fri, 04 Jun 2004 19:26:23 +0200 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: <41A1CBC76FDECC42B67946519C6677A9A20EB2@pippin.int.etrials.com> References: <41A1CBC76FDECC42B67946519C6677A9A20EB2@pippin.int.etrials.com> Message-ID: <40C0B0BF.6080306@livinglogic.de> Ian Sparks wrote: > Walter D?rwald wrote : > >>XIST follows a different philosophy: All templates are pure XML (in >>fact most of our templates consist of a root element only (something >>like )). The rest is done in pure Python code. The designer >>develops the XML elements for the layout. > > So this is JSP taglibs for python? ... and PHP taglibs and PSP taglibs (not yet, but simple to implement) and EZT templates (ViewCVS) and ... XIST is not so much about how to get your business logic into the web pages, but how to simplify creating the repetitive parts of the web pages. > Taglibs seem like a good idea, > code-up your own tags and sprinkle them throughout your HTML. > But taken to the logical conclusion you get to monolithic tags > like your example. You have tags on all levels of a webpage, from a simple one that e.g. formats positive numbers green and negative ones red to complete web pages. >>Our main designer had no previous programming experience and was using >>Adobe GoLive before joining our company. Now he's programming all his >>HTML templates in Python without any problems. > > I can see how this would play out. You hire a web-designer and > explain to them your custom tags and what they do. They start > using them in GoLive (or whatever their tool of choice is) but > the custom tags don't render in their tool. But if the web page consists of a large table, and you want to replace the table tag with an XIST plaintable (with adds border="0" cellspacing="0" cellpadding="0" automatically) you suddenly loose the formatting of the complete page. > As the tag libraries > build up in complexity the HTML migrates from the templates into > the python taglib code and inevitably the designer will follow > the HTML there. I dont' think it's feasible to combine XIST and HTML editors. > Eventually the taglib becomes so customized that there is no HTML left, > only custom tags. Eventually the designer abandons the "HTML template" > completely and it is left as a stub like (which > looks a bit vestigal to me, the code equivalent of tonsils). Of course you can instantiate your page element directly instead of putting it in an XML file. Then generating the final web page template looks like this: print newsPage().conv().asBytes(encoding="utf-8") > I'm not criticising XIST (it looks very powerful). I'm genuinely > interested in what happens when you mutate HTML into a custom XML markup > via taglibs : How far does it go? As far as you want. You can have a file that looks like HTML and uses only a few simple tag, or go all the way up to . > Is there some safe middle ground? > Can you share the resulting markup language with 3rd parties > or has it simply become too customized to your uses? If you design frameworks for specific application areas, it should certainly be possible to share them with 3rd parties. > For instance, > what would be the learning curve to bring in a new HTML designer? Compared to "hack together a HTML file in frontpage and ship it to the programmer", you have a learn a bit: Real HTML/CSS and Python. > I've seen some advice on JSP taglibs to the effect of > "keep them small and specific and don't create monolithic tags", > what would your advice be for using XIST with python? I guess this depends on the application area: You can use XIST for HTML scraping, importing and exporting XML content, standalone web servers on CDROMs, for generating static pages (or PDFs via XSL-FO) and for generating templates for other systems like JSP and PHP. Bye, Walter D?rwald From davidf at sjsoft.com Tue Jun 29 03:59:23 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 29 Jun 2004 09:59:23 +0200 Subject: wxPython syntax In-Reply-To: References: Message-ID: OKB (not okblacke) wrote: > David Fraser wrote: > > >>MenuDeclaration = """ ... """ # put the above string in here... >>MenuResource = wxResourceParser.Parse(MenuDeclaration) >> >>class FileMenu(MenuResource): >> def OnAbout(self, event): >> # put the code here >> def OnExit(self, event): >> # put the code here > > > This is a cool idea. I like the looks of it. One worry I have, > though, is that with the code outside the hierarchical definition > there'll still be confusion about the organization. What if you have a > menu bar as well as some other widgets, or submenus? Also, what about > things like listboxes, where you want the list elements to be determined > programmatically? Various interrelationships might exist between the > GUI's appearance and its content, which could be difficult to express if > the layout were being specified with some static text. I'm not sure how > best to handle this, but I think it's something to think about. > The idea of this approach is that you use the resource string to define the simple stuff and then do the rest in code. For example, define a list box but no elements, than add them in the initializer. Because the Resource is used as a base class for the class you are declaring, you can call its initializer from the derived classes initializer, and then make any changes that are desired (including adding custom widgets or even doing fancy things with sizers). One of the main things that would need to be addressed is how sizers and layout could be defined using this approach David From fallen at leveltwo.com Wed Jun 9 12:48:36 2004 From: fallen at leveltwo.com (Fred Allen) Date: Wed, 9 Jun 2004 09:48:36 -0700 Subject: Perlish dictionary behavior Message-ID: Dear Mr. Brewer: Thank you for your rapid and eminently helpful reply. I remain, Gratefully, Fred Allen -----Original Message----- From: Robert Brewer [mailto:fumanchu at amor.org] Sent: Tuesday, June 08, 2004 7:34 PM To: Fred Allen; python-list at python.org Subject: RE: Perlish dictionary behavior Fred Allen wrote: > I fruitlessly tried your "thing counter", as you can see below. > > >>> class AllThingsStartAtZero(dict): > ... def getitem (self, key): > ... return dict.get(self, key, 0) > ... As Chris pointed out, it should be __getitem__ (two leading underscores and two trailing). If you read the original on Google (say, from the link in Dr. Dobb's? ;), they cut out underscores somewhere along the line. FuManChu From peter at engcorp.com Mon Jun 7 18:21:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jun 2004 18:21:21 -0400 Subject: win32all - determine wrkstn vs. server In-Reply-To: References: Message-ID: ChrisH wrote: > Does anyone know of a way to determine whether the current computer > running a python script is a workstation or server? What does it mean to you that something is a workstation or a server? These terms are not precise ones. Some people run servers as workstations, and vice versa, for example. On some versions of Windows, the primary difference was in the number of simultaneous incoming connections that were allowed, but only for MS network services, not TCP/IP ones. -Peter From bart_nessux at hotmail.com Mon Jun 14 15:38:58 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Mon, 14 Jun 2004 15:38:58 -0400 Subject: thread help Message-ID: Howdy, Below is a script that I'm using to try and count the number of HTTP servers within a company's private network. There are 65,536 possible hosts that may have HTTP servers on them. Any way, I wrote this script at first w/o threads. It works, but it takes days to run as it probes one IP at a time... so I thought I'd try to make it threaded so it could test several dozen IPs at once. I'm no expert on threading, far from it. Could someone show me how I can make this work correctly? I want to probe 64 unique IP address for HTTP servers simultaneously, not the same IP addy 64 times (as I'm doing now). Any tips would be much appreciated. Bart import urllib2, socket, threading, time class trivialthread(threading.Thread): def run(self): socket.setdefaulttimeout(1) hosts = [] networks = [] # Add the network 192.168.0 possibility. networks.append("192.168.0.") n = 0 while n < 255: n = n + 1 # Generate and add networks 192.168.1-255 to the list of networks. networks.append("192.168.%s." %(n)) for network in networks: h = 0 # Add the n.n.n.0 host possibility hosts.append(network+str(h)) while h < 255: h = h + 1 # Add hosts 1 - 255 to each network. hosts.append(network+str(h)) websites = file('websites.txt', 'w') for ip in hosts: try: f = urllib2.urlopen("http://%s" %ip) f.read() f.close() print>> websites, ip except urllib2.URLError: print ip except socket.timeout: print ip, "Timed Out..................." except socket.sslerror: print ip, "SSL Error..................." websites.close() if __name__ == '__main__': threads = [] for x in range(64): thread = trivialthread() threads.append(thread) for thread in threads: thread.start() while threading.activeCount() > 0: print str(threading.activeCount()), "threads running incl. main" time.sleep(1) From bkc at Murkworks.com Wed Jun 23 09:52:46 2004 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 23 Jun 2004 09:52:46 -0400 Subject: python-list to news gateway down? Message-ID: I have not seen any new posts in gmane.comp.python.general since 6/18/2004. However when I post to gmane, that post seems to make it out to the python list. Does anyone know if its a gmane problem, or a general news to python-list problem? -- Novell DeveloperNet Sysop #5 _ From jjl at pobox.com Tue Jun 29 16:26:02 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Jun 2004 21:26:02 +0100 Subject: How important is Python 1.5 compatibility? References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: <87isdaf6w5.fsf@pobox.com> Erik Max Francis writes: > How important do people think Python 1.5 compatibility is? For some of > my projects I've strived to keep it compatible with 1.5 (at least for > the portions of the applications that actually would work with 1.5; for > instance Unicode support obviously requires Python 2.x). It seemed to > me that this used to be fairly important, when, say, 2.1 was new, mostly > because of other large Python applications that required 1.5, or lazy > ISPs who still used older version. [...] Last time I checked (a month or so ago), the sourceforge web servers were still running 1.5.2. The SF *shell* servers were more up-to-date, but not the web servers. I take an "I've started so I'll finish" attitude to 1.5.2-compatibility with my open-source stuff. With code where I started out supporting 1.5.2 (um... badly, at least before I had decent tests), I feel I may as well leave it that way. (despite the fact that I'd be surprised to learn that anybody actually runs my code on 1.5.2) With new open-source library code, in the absence of a need for some major feature introduced later, I'd probably pick 2.2 now, because of the big changes from 2.1 to 2.2. I can see why you might choose 2.0, 2.1 or 2.3 instead, though. All depends on the audience you hope to reach, of course. John From Holger.Joukl at LBBW.de Tue Jun 15 04:24:38 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Tue, 15 Jun 2004 10:24:38 +0200 Subject: [Zope] zope 2.7 + debian + py2.3.3 + zlib Message-ID: > I want to install zope 2.7.0. > But it needs py2.3.3. > Ok, I compile it in Debian linux, and I try to configure zope 2.7. > But it is say to me: the zlib module is cannot be found. > > 1. Where I found this module ? When you build python, some standard directories are searched for libz.so. I think these are /usr/local/lib and /usr/lib. Where does libz.so live on your system? If it is in another directory, you will either - have to modify setup.py (see the detect_modules method) or - give some smart command line option to configure (which I do not know) or - set some smart environment variable (which one I do not know either: LDSHARED? LD_LIBRARY_PATH?). You must have libz.so and the appropriate headers on your system, of course. G H. Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From bram at nospam.sara.nl Wed Jun 23 08:01:51 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 23 Jun 2004 14:01:51 +0200 Subject: Parsing C Preprocessor files Message-ID: <20040623140151.6b8863f2@pistache.sara.nl> Hi there, What could I use to parse CPP macros in Python? I tried the Parnassus Vaults, and python lib docs, but could not find a suitable module. Thanks, Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "Software is math. Math is not patentable." OR "Software is literature. Literature is not patentable." -- slashdot comment ------------------------------------------------------------------------------ From mynews44 at yahoo.com Tue Jun 15 07:59:15 2004 From: mynews44 at yahoo.com (google account) Date: 15 Jun 2004 04:59:15 -0700 Subject: Newbie question: what is causing my socket error? References: Message-ID: mynews44 at yahoo.com (google account) wrote in message news:... > > The code in the library at line 254 is > > addr = socket.gethostbyname(socket.gethostname()) > > which would kinda support my theory about name resolution, but not > help me resolve the error. Turns out I was being pretty brickheaded... It wasn't complaining about not being able to resolve the mail server. It was complaining about not being able to resolve the host name of the box it was sitting on. It is actually mentioned in the sockets documentation somewhere that this is a requirement. On my linuxbox, I put an entry for the hostname in the /etc/hosts file, and then it worked like a bought one. Thanks for looking! Sorry to trouble you. Hope this post saves someone some time someday. ^_^ cha! From jjl at pobox.com Sun Jun 13 20:02:41 2004 From: jjl at pobox.com (John J. Lee) Date: 14 Jun 2004 01:02:41 +0100 Subject: urllib IOError Exception References: Message-ID: <87y8mr2ehq.fsf@pobox.com> Bart Nessux writes: > JanC wrote: > > Bart Nessux schreef: > > > >> try: > >> f = urllib2.urlopen("http://%s" %host) > >> except urllib2.URLError: > >> print host, "has no http server on port 80" > >> > >>Anyway to speed this up??? The timeout per host is several minutes. > > socket.setdefaulttimeout(timeout) > > > > > > Thanks, that worked... I find it odd that I have to import the socket > module to set a timeout while using the urllib2 module... why isn't > there a function in urllib2 that can handle this? Because nobody wrote one. Go ahead and add upload a patch :-) John From FBatista at uniFON.com.ar Thu Jun 24 16:41:39 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 24 Jun 2004 17:41:39 -0300 Subject: String help Message-ID: [Rigga] #- I am new to python and am working on a script that parses a #- file and loads #- the results in to variables for processing. I am having #- problems when it #- comes to data in the file that wraps over two lines i.e. #- #- las - #- lomas #- #- What i want to be able to do is to some how strip all the #- spaces from it #- so while it is contained as a variable so it equal 'las - lomas' >>> s = """las - lomas""" >>> s 'las -\n lomas' >>> s = s.replace('\n','') >>> ' - '.join([x.strip() for x in s.split('-')]) 'las - lomas' . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ville at spammers.com Sat Jun 19 17:10:20 2004 From: ville at spammers.com (Ville Vainio) Date: 20 Jun 2004 00:10:20 +0300 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: >>>>> "Leif" == Leif K-Brooks writes: Leif> I'm planning to start on a fairly large web application, Leif> most likely using mod_python. I recently wrote a fairly Leif> small (but real-world useful) web app with it, and all of Leif> those req.write()s made for really ugly code. Would a Leif> templating engine solve that? Does anyone have any Leif> suggestions about which one to use? A recent mod-python supports php-like "python-code-within-normal-text" development. Is that what you want? More details on: http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html -- Ville Vainio http://tinyurl.com/2prnb From adalke at mindspring.com Tue Jun 1 21:13:04 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 02 Jun 2004 01:13:04 GMT Subject: Autoflush in python cgi References: Message-ID: Gianluca Trombetta: > How can i do the autoflush effect in a python cgi? Start Python with the "-u" option. Also, try a web search for "python autoflush" and you'll find expanded answers, like using a wrapper around sys.stdout to do a flush after every write http://www.faqts.com/knowledge_base/view.phtml/aid/4419 as well as some philosophy on why Python differs from Perl on this regard. http://groups.google.com/groups?q=autoflush+python&hl=en&lr=&ie=UTF-8&selm=0 00701be54bc%2438bf5280%24a39e2299%40tim&rnum=2 Andrew dalke at dalkescientific.com From me at privacy.net Mon Jun 21 11:02:39 2004 From: me at privacy.net (Duncan Booth) Date: 21 Jun 2004 15:02:39 GMT Subject: Creating subclassess (newbie) References: <20040621153854.14f10a9f@debian> Message-ID: Adam wrote in news:20040621153854.14f10a9f at debian: > What is the best way of creating (coding) subclasses? > Alternatively, is there any good documentation on the web > for doing this? > Have you tried reading the Python tutorial? http://docs.python.org/tut if you can't find it on your own machine. Try reading chapter 9: 'classes' with special attention to 9.5 'inheritance'. If you want coding examples you could look at Python's standard library. There are plenty of examples of subclassing. For example, try CGIHTTPServer and its associated documentation, htmllib or HTMLParser are other places to look. http://docs.python.org/lib/htmlparser-example.html shows an example of subclassing the HTMLParser class to parse html. From connellybarnes at yahoo.com Thu Jun 17 03:11:42 2004 From: connellybarnes at yahoo.com (C. Barnes) Date: Thu, 17 Jun 2004 00:11:42 -0700 (PDT) Subject: Automatic thread safety for classes Message-ID: <20040617071142.54162.qmail@web14526.mail.yahoo.com> Another useful code snippet... This allows you to take a non-threadsafe class, and automatically generate a threadsafe class. When a method is called for your class, it automatically locks the object, then calls the method, then unlocks the object. You will have to perform any further locking/unlocking manually. # ------------------------------------------------- # threadclass: Get a threadsafe copy of a class. # ------------------------------------------------- import types, threading def threadclass(C): """Returns a 'threadsafe' copy of class C. All public methods are modified to lock the object when called.""" class D(C): def __init__(self): self.lock = threading.RLock() C.__init__(self) def ubthreadfunction(f): def g(self, *args, **kwargs): self.lock.acquire() ans = f(self, *args, **kwargs) self.lock.release() return ans return g for a in dir(D): f = getattr(D, a) if isinstance(f, types.UnboundMethodType) and a[:2] != '__': setattr(D, a, ubthreadfunction(f)) return D Example: class Counter: def __init__(self): self.val = 0 def increment(self): self.val += 1 SafeCounter = threadclass(Counter) Now SafeCounter is a threadsafe class. Try it out! Enjoy, Connelly Barnes __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From robin at SPAMREMOVEjessikat.fsnet.co.uk Mon Jun 7 04:00:26 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Mon, 07 Jun 2004 09:00:26 +0100 Subject: Brain Dead Singleton In-Reply-To: References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> <40C1B470.1000407@jessikat.fsnet.co.uk> Message-ID: <40C4209A.6090403@jessikat.fsnet.co.uk> Peter Hansen wrote: ...... > > An easy fix involved restoring sys.modules to a pristine state > > before each document was generated. > > I'd argue perhaps that "easy fix" should have read "hack", and > that this doesn't fit my condition of "most sane situations". > I think I would agree that this is a hack. Probably the correct fix would have been to packagize each document folder and the containing folder and then change all the imports to be absolute, but that would have meant changing far more lines of code and introducing packages which are not really packages. > Would you say that this "fix" was really an elegant solution, > or just a quick hack? I don't think deleting things from > sys.modules has defined, guaranteed behaviour, so I'm uncertain > whether anyone should rely on it working. I still think > Colin's approach is a generally okay one. > > -Peter If sys.modules isn't intended to be a modifiable cache, perhaps we shouldn't be given access to it. The docs for 2.3 say "modules This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object." So the Gods call call this a trick :) -- Robin Becker From BELLEMAIL-SA at exponent.com Wed Jun 23 23:56:16 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 20:56:16 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F94@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = pwrpossem at aol.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 280 Scanning time = 06/23/2004 20:56:16 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment your_website.pif matched file blocking settings. ScanMail took the action: Deleted. The attachment www.python.org.python-list.session-000025C8.com matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From tzot at sil-tec.gr Fri Jun 4 05:04:01 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 04 Jun 2004 12:04:01 +0300 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: <3ge0c0hpfbq9a53unlvcvfc01fg2fn0816@4ax.com> On 2 Jun 2004 19:26:12 -0700, rumours say that jasondrew at comcast.net (Jason Drew) might have written: >Christos "TZOTZIOY" Georgiou wrote in message news:... >> On Tue, 1 Jun 2004 13:30:10 +0100, rumours say that "Richard Brodie" >> might have written: >> >There is also a lot of keyboard locality: adjacent letters, nothing from the >> >bottom row, etc. >> Yes, that is the most obvious hint: it's the author's cat walking on the >> keyboard and wailing after the PSU killed the ori >I noticed the keyboard locality too, but then suspected that Python >might have the sophistication to decode this, when *my* cat walked >across my keyboard and gave me the magic key: > >### >magickey = 'nxxoanntrckpafqcaqaetxfnarwfb' [snip of nice code to 'decrypt' the original text :) ] >Amazingly, it worked. Then it struck me, that I don't have a cat. Of course. You have a parrot (deceased): >>> help(magickey) no Python documentation for 'a long squawk by a parrot pining for the fjords' -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From hank at nicht-prosysplus-schpamme.com Fri Jun 25 08:53:11 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Fri, 25 Jun 2004 08:53:11 -0400 Subject: (OT) wxPython & resizers, html text (code included) References: Message-ID: <10do81itirgnr4b@corp.supernews.com> Check out Dabo (www.dabodev.com); they are creating an IDE for wxPython that uses direct placement. It's still young, but does work. -- "flupke" wrote in message news:lpDBc.880$HB3.174961778 at hestia.telenet-ops.be... > Hi, > > i'm trying to convert my java console app to a python gui. > Now, the only problem i seem to have at the moment are the resizers > for the layout. It seems that for the purpose of what i'm trying to do, > specifying the coordinates is easier that fighting with the layout resizers. > > 1) I have a screen split in 2. Left side is a textcontrol where logging will > end up. All text will be appended to the textcontrol. Ideally this should > allow html tags but the wxHtmlWindow doesn't seem to support just adding > text. Only workaround that i can think off is to maintain a list of message > myself > and then i could set those every time something changes but i don't really > like this as on every change, the whole textcontrol will be refilled. > The reason for html is to easily adjust text from one colour to another and > for > instance some basic formatting like bold, italic etc. > Any ideas? > > 2) (view with for instance with courier) > ----------------------------------------------- > | TextControl | ________ | > | ||________| Combobox | > | | | > | | ________ | > | ||________| | > | | | > | | ________ | > | ||________| Textcontrol | > | | | > ----------------------------------------------- > > Basically i have a number of button left-aligned in the right part of the > split window and > they are placed vertically with a small gap in between (border). This is > working but then > i would want to add a combobox next to button 1 and saya textcontrol to > button 2. > A gridresizer would work if i would be able to specify what row and column > the component > would have to be in but there doesn't seem to be such a method. > Only sollution i can think of is adding the coordinates of where i want to > component to come. > Is there another sollution as i read that it's best not to add components by > specifying an x > and y value. > > Thanks > > ============== Working snippet below ======================= > > > from wxPython.wx import * > import sys, os > > ID_ABOUT=100 > ID_EXIT=101 > > ID_BUTTON_CONNECT=200 > ID_BUTTON_CHECK=201 > ID_BUTTON_CONNECTIONS=202 > ID_BUTTON_SEND=203 > ID_BUTTON_HELP=204 > ID_BUTTON_EXIT=205 > > class MainWindow(wxFrame): > def __init__(self, parent, id, title): > wxFrame.__init__(self,parent,id,title, style=wxDEFAULT_FRAME_STYLE| > wxNO_FULL_REPAINT_ON_RESIZE) > > self.split_window = wxSplitterWindow(self, -1) > self.button_pane = wxPanel(self.split_window, -1, > style=wxTAB_TRAVERSAL|wxNO_FULL_REPAINT_ON_RESIZE) > > self.logging_screen = wxTextCtrl(self.split_window, -1, "", > style=wxTE_MULTILINE|wxHSCROLL) > #self.html_window = new wxHtmlWindow( self ) > > self.connect = wxButton(self.button_pane, ID_BUTTON_CONNECT, > "connect") > self.check = wxButton(self.button_pane, ID_BUTTON_CHECK, "check") > self.connections = wxButton(self.button_pane, ID_BUTTON_CONNECTIONS, > "connections") > self.send = wxButton(self.button_pane, ID_BUTTON_SEND, "send") > self.help = wxButton(self.button_pane, ID_BUTTON_HELP, "help") > self.exit = wxButton(self.button_pane, ID_BUTTON_EXIT, "exit") > > #make the combobox for the connections > sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', > #'this is a long item that needs a scrollbar...', > 'six', 'seven', 'eight'] > > self.cb = wxComboBox( > self.button_pane, 500, "default value", (90, 50), > (95, -1), sampleList, wxCB_DROPDOWN #|wxTE_PROCESS_ENTER > ) > > # Menu Bar > self.frame_1_menubar = wxMenuBar() > self.SetMenuBar(self.frame_1_menubar) > self.File = wxMenu() > self.File.Append( ID_ABOUT, "&About", "About CheckServer Client" ) > self.File.AppendSeparator() > self.File.Append( ID_EXIT, "E&xit", "Leave the application" ) > self.frame_1_menubar.Append(self.File, "F&ile") > EVT_MENU(self, ID_ABOUT, self.OnAbout) > EVT_MENU(self, ID_EXIT, self.OnExit) > > # Menu Bar end > > self.statusbar = self.CreateStatusBar(1, wxST_SIZEGRIP) > > self.__set_properties() > self.__do_layout() > self.Show(true) > > # end wxGlade > > def __set_properties(self): > # begin wxGlade: MyFrame.__set_properties > self.SetTitle("CheckServer Client") > > _icon = wxEmptyIcon() > _icon.CopyFromBitmap(wxBitmap("D:\\temp\\1anipt1c.gif", > wxBITMAP_TYPE_ANY)) > self.SetIcon(_icon) > self.SetSize((723, 533)) > self.SetFocus() > > self.logging_screen.SetBackgroundColour(wxColour(247, 255, 159)) > self.logging_screen.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, > 0, "Century Gothic")) > self.logging_screen.SetToolTipString("Here you'll see the result of > the commands you issue to the server") > self.logging_screen.SetDefaultStyle(wxTextAttr(wxColour(255,0,0))) > self.logging_screen.AppendText("Red text\n"); > self.logging_screen.AppendText("Test\n"); > > > self.logging_screen.Enable(0) > > self.connect.SetSize((110, 28)) > self.connect.SetBackgroundColour(wxColour(143, 188, 143)) > self.connect.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, > "Arial Black")) > self.connect.SetToolTipString("Connect to a server") > self.connect.SetFocus() > > self.check.SetSize((110, 28)) > self.check.SetBackgroundColour(wxColour(143, 188, 143)) > self.check.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, > "Arial Black")) > self.check.SetToolTipString("Check server directories") > self.check.Enable(0) > > self.connections.SetSize((110, 28)) > self.connections.SetBackgroundColour(wxColour(143, 188, 143)) > self.connections.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, > "Arial Black")) > self.connections.SetToolTipString("What connections are active") > self.connections.Enable(0) > > self.send.SetSize((110, 28)) > self.send.SetBackgroundColour(wxColour(143, 188, 143)) > self.send.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial > Black")) > self.send.SetToolTipString("Send a file from the server to local > pc") > self.send.Enable(0) > > self.help.SetSize((110, 28)) > self.help.SetBackgroundColour(wxColour(143, 188, 143)) > self.help.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial > Black")) > self.help.SetToolTipString("Display help options (command line)") > > self.exit.SetSize((110, 28)) > self.exit.SetBackgroundColour(wxColour(143, 188, 143)) > self.exit.SetFont(wxFont(10, wxMODERN, wxNORMAL, wxNORMAL, 0, "Arial > Black")) > self.exit.SetToolTipString("Exit the application") > > self.button_pane.SetFocus() > self.button_pane.SetBackgroundColour(wxBLUE) > self.statusbar.SetStatusWidths([-1]) > self.split_window.SetMinimumPaneSize(20) > > # statusbar fields > statusbar_fields = ["CheckServer"] > for i in range(len(statusbar_fields)): > self.statusbar.SetStatusText(statusbar_fields[i], i) > > # end wxGlade > > def __do_layout(self): > # begin wxGlade: MyFrame.__do_layout > split_window_sizer = wxBoxSizer(wxVERTICAL) > > button_pane_sizer = wxBoxSizer(wxVERTICAL) > button_pane_sizer.Add(self.connect, 0, wxALL, 2) > button_pane_sizer.Add(self.check, 0, wxALL, 2) > button_pane_sizer.Add(self.connections, 0, wxALL, 2) > button_pane_sizer.Add(self.send, 0, wxALL, 2) > button_pane_sizer.Add(self.help, 0, wxALL, 2) > button_pane_sizer.Add(self.exit, 0, wxALL, 2) > button_pane_sizer.Add(self.cb,0, wxALL, 2) > self.button_pane.SetAutoLayout(1) > self.button_pane.SetSizer(button_pane_sizer) > button_pane_sizer.Fit(self.button_pane) > button_pane_sizer.SetSizeHints(self.button_pane) > > > self.split_window.SplitVertically(self.logging_screen, > self.button_pane) > split_window_sizer.Add(self.split_window, 1, wxEXPAND, 0) > self.SetAutoLayout(1) > self.SetSizer(split_window_sizer) > self.Layout() > self.Centre() > # end wxGlade > > def OnAbout(self,e): > d= wxMessageDialog( self, " A sample editor \n" > " in wxPython","About Sample Editor", wxOK) > # Create a message dialog box > d.ShowModal() # Shows it > d.Destroy() # finally destroy it when finished. > > def OnExit(self,e): > self.Close(true) # Close the frame. > > # end of class MyFrame > > > class App(wxApp): > def OnInit(self): > wxInitAllImageHandlers() > main_window = MainWindow(None, -1, "CheckServer Client") > self.SetTopWindow(main_window) > return true > > # end of class App > > app = App(0) > app.MainLoop() > > From claird at lairds.com Wed Jun 16 09:49:34 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 16 Jun 2004 13:49:34 -0000 Subject: Looking for a different version of sort References: <8a4484e4.0406151819.6c0538e7@posting.google.com> Message-ID: <10d0jvelvgalue5@corp.supernews.com> In article <8a4484e4.0406151819.6c0538e7 at posting.google.com>, Brian McGonigle wrote: >I'm a Perl programmer learning Python (up to chapter 7 in Learning >Python, so go easy on me :-) and I find that I look to do things in >Python the way I would do them in Perl. In Perl functions and methods . . . Incidentally, is that the first or second edition you're reading? -- Cameron Laird Business: http://www.Phaseit.net From moughanj at tcd.ie Thu Jun 10 22:36:39 2004 From: moughanj at tcd.ie (James Moughan) Date: 10 Jun 2004 19:36:39 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> Message-ID: <16752bcc.0406101836.37101578@posting.google.com> Jim Newton wrote in message news:<2irotfFqob91U1 at uni-berlin.de>... > >>Secondly, Lisp's syntax doesn't parse well into the way people > >>think, > > > > > > not sure i understand what you mean by "not the way people think", > but i think i disagree with you. lisp seems to be very similar > to the way people think, it is just that programmers have learned > over the years to think in a algol type way. > > For example, if you have a bag of balls, and you want to find out > if one of them is red. The algol type way would be > > for ball in bag-of-balls > is ball red? > yes ==> set flag true > no ==> keep going > Is flag true? > yes ==> there is a red ball > no ==> there is no red ball > > > but that seems like a very different way than people think. > the lisp way to answer the question is > > is there a ball in the bag that matches condition? > condition being: is the ball red? > > It seems like a much more natural way to think... at least to me. > -jim Undeniably, Lisp has some useful routines. Especially for LISt Processing. :)However, let's rewrite this how I might put it in Python; def has_elem(lis, cond): for x in lis: if cond(x): return True return False which, to me, says; check each element of the list, if it fulfils the condition, be true. If none fulfilled the condition, be false. Logical enough. If I were checking through a deck of cards to see if there were any Jokers then that's what I'd do. Now, how to do this in Lisp. There are several functions for applying a function to the elements of a list to select them, though AFAIK none specifically for our purpose. I may very well be wrong there o'course. One way is: (define has-element (cond list) (equal () (member-if #'cond list)))) Well, it's definitely short. It doesn't exactly translate well, though; search the list for a sub-list that starts with an element which evaluates to true under cond. Evaluate to the equality of that list with the null list. Hmmm. That's not a great example, although it's probably how I'd write it :) so let's do a real function: (defun has-element (pred lis) (if (equal lis ()) NIL (if (funcall pred (car lis)) T (has-element pred (cdr lis))))) Rough translation; if the list is the null list, return NIL (false). Otherwise, if applying pred to the first element of the list is true, be T (true), otherwise, evaluate to the value of this function applied to pred and the list excluding the first element. This isn't really too complex. However, it's not how most people *think* about a job like searching a list; mentally, searching is a single block task, not a recursive function. There are some other obvious issues with syntax. The brain wasn't meant to pick up on structure in arbitrary numbers of parenthesis, and I wouldn't even try to write Lisp without a highlighting editor. car and cdr might as well be in greek. (yes, I know I can redefine them; first thing I did). We have to have a rather arbitrary #' funcall and syntax to stop a function evaluating long enough to shift it to where it's useful. None of these are anything like fatal flaws. When I'm programming in Python, though, concepts seem to just flow naturally onto the screen. I don't think that's entirely 'what I know', either, because it began happening within a day or two, and my style in Python is quite different to in most other languages. Hmm, long answer to a short question. I hope you see what I mean, though. Lisp is a powerful language, but pragmatically, Python lets me just get on with what I'm doing. From tundra at tundraware.com Wed Jun 23 17:30:07 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jun 2004 17:30:07 EDT Subject: Tix In-Reply-To: References: Message-ID: Eugene Van den Bulke wrote: > Hi everyone, > > I have read a fair bit about python GUI and was wondering why no one > seemed to be mentioning Tix. Is it because it is considered as being > implicitly part of Tkinter? > > Thanks, > > EuG?Ne http://docs.python.org/lib/module-Tix.html -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From squirrel at WPI.EDU Mon Jun 28 11:51:49 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 11:51:49 -0400 Subject: what editor do you use? In-Reply-To: <40e0241e_2@newsfeed.slurp.net> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <40e0241e_2@newsfeed.slurp.net> Message-ID: On Mon, 28 Jun 2004, Steven Rumbalski wrote: > Michael Anckaert wrote: > > > A friend of mine uses emacs and we held a 'speedcontest', we had > > to edit a file with our editors and write some code. Me and vim were > > about 50% faster than him and emacs. > > But I don't want to start any vim vs. emacs flamewar :-) > > > I suspect you would be 50% faster even if you both used notepad. This > comparison is meaningless without a baseline comparison in an unfamiliar > editor. Perhaps you are simply a faster typist. Perhaps code flows more > quickly from your brain. Perhaps you were more familiar with the file to > be edited and the problem domain. We cannot know the reason that you > performed this particular test more quickly. A better comparison would be to perform weird editing tasks, since all editors let you type code at about the same speed. Example: One of my friends was trying to cut and paste columnar values in EMACS. The task took him about five minutes. I showed him JOE's rectangle selection mode. He was then able to use that feature to accomplish the same task with (literally) a couple of keystrokes. Of course, there are tasks which will be more efficient in EMACS due to its scriptability. It all boils down to a question of which editor provides more practical features. From indigo at bitglue.com Wed Jun 2 12:17:19 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 2 Jun 2004 12:17:19 -0400 Subject: How to demonstrate bigO cost of algorithms? In-Reply-To: References: Message-ID: <20040602161719.GA8461@unununium.org> The problem is that BigO cost describes how the computation time scales with the size of the set, but nothing about how long that really is. For example, let us implement a trivial algorithm that increments each number in a list: def f(list): for key in xrange( len(list) ): list[key] += 1 this is O(n), because as the size of the set increases, the computation time increases linearly. Now say we change the implementation to this: def f(list): for key in xrange( len(list) ): list[key] += 1 i = 2**32 while i: print 'wasting time' i -= 1 This functionally equivalent algorithm takes much longer to run, but its complexity is still O(n). Because O(n) only tells us how the computation time scales, to get the real time, multiply n by the time it takes to run the algorithm on a set of size one. In your case of qsort which is O(log(n)), that is not a base2 log, it's just a log, and the base doesn't really matter. Changing the base of the log only multiplies the result by some constant. By simple algebra, we know that log2(x) = log10(x) / log10(2). From this we can see that changing the base of the log in your calculation multiplies the result by a constant. What this constant is depends on the implementation of the algorithm, and to translate BigO notation into real times you will have to find it by performing a regression on your data. That said, BigO notation only gives the complexity in theory, and not always in practice. Other factors will cause the real run time to deviate from the BigO model, so you will likely need a large set of data to clearly see the relation. On Wed, Jun 02, 2004 at 03:40:12PM +0000, Rusty Shackleford wrote: > Hi - > > I'm studying algorithms and I want to write a python program that > calculates the actual runtimes. > > I want to increment up some global variable called n in my program so > that I can see the relationship between the size of the problem and the > number of steps. > > Here's my clumsy attempt to implement this: > > def qsort(ll): > try: > global n > n += len(ll) > print "adding %d to %d." % (len(ll), n) > print "incrementing up n to %d." % n > except: > pass > if len(ll) == 0: > return [] > p = ll[0] > left = [x for x in ll if x < p] > mid = [x for x in ll if x == p] > right = [x for x in ll if x > p] > return qsort(left) + mid + qsort(right) > > I'm not getting the results I hoped for. I expected that after the > program is finished, I would get results near > > len(ll) * math.log(len(ll), 2) > > since the big O for quicksort is nlogn for all but the worst case. > > I'd like to write similar functions for mergesort, bubblesort, and all > the other basic algorithms covered in data structures classes. > > All help is welcome. From grey at despair.dmiyu.org Mon Jun 14 18:15:12 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 14 Jun 2004 22:15:12 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: On 2004-06-14, Carl Banks wrote: > Ryan Paul wrote: >> ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| >> Dir[$prefix+fn].collect {|x| >> x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| >> `cat #{sesc x}.* > #{sesc x}`} } > Oh boy. I believe this untested Python code does what you want, also > one line, also wrapped in the name of "clarity." > for f in dict([(__import__('re').sub(r"\.\d+[\d.-]*$","",x),None) > for fn in ("*.rar.*","*.r[0-9][0-9].*") > for x in __import__('glob').glob(prefix+fn)]): > __import__('os').system("cat %s.* > %s" % (sesc(f),sesc(f))) > This would take about 7 lines in well-written Python, not 15. > bad-code-can-be-written-in-any-language-ly yr's, Ok, see, here's the thing. I look at the Ruby code and can kind of follow it. I look at the Python code and can kind of follow it. but in neither case have I, in glancing here and there today, been able to decipher exactly what is going on. Care to show the 5 line long form to see if I get that? No explination, just curious to see if I can get it reading real code instead of hacked up line noise. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From BELLEMAIL-SA at exponent.com Wed Jun 23 22:55:23 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 19:55:23 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F86@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = tim.peters at gmail.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 268 Scanning time = 06/23/2004 19:55:23 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment Details.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From benn at cenix-bioscience.com Mon Jun 21 08:16:47 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 21 Jun 2004 14:16:47 +0200 Subject: ConfigParser Keys Message-ID: <40D6D1AF.3070800@cenix-bioscience.com> Hello, To my chagrin, I've just discovered that SafeConfigParser, by default, returns all the keys in the key/value pairing in lowercase (what earthly possible reason it would do this I do not know!). Does anyone know of a way of stopping it doing this? Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From ab_som at vsnl.net Tue Jun 15 12:35:36 2004 From: ab_som at vsnl.net (Abhijit Soman) Date: Tue, 15 Jun 2004 22:05:36 +0530 Subject: Curses module on windows In-Reply-To: <95aa1afa.0406150743.720e5261@posting.google.com> References: <2j82q8FujmukU1@uni-berlin.de> <95aa1afa.0406150743.720e5261@posting.google.com> Message-ID: <2j8lv7Fuo2bjU1@uni-berlin.de> I found a port of curses module for windows at flangy.com/dev/python/curses/ regards, Abhijit Michele Simionato wrote: > Abhijit Soman wrote in message news:<2j82q8FujmukU1 at uni-berlin.de>... > >>Where can i find curses module for windows? I have pdcurses library on >>windows. But python binary doesnot include curses module. >> >>Thanks, >>Abhijit > > > I guess you need something like CygWin to get curses running on Windows > (not sure, please correct me if I am wrong). > > > Michele Simionato -- Man Invented Alcohol, God Invented Grass. Who do you trust? From wayne at mishre.com Tue Jun 1 19:11:35 2004 From: wayne at mishre.com (Wayne Pierce) Date: 1 Jun 2004 16:11:35 -0700 Subject: Problem with smtplib: 550 'Administrative prohibition' Message-ID: <2a897f11.0406011511.7a7f360e@posting.google.com> I have a script that checks a POP3 mailbox and sends the emails to different people based upon some settings. For some reason my script cannot send any emails, the error I am getting is: reply: '550 Administrative prohibition\r\n' reply: retcode (550); Msg: Administrative prohibition data: (550, 'Administrative prohibition') send: 'rset\r\n' reply: '250 Reset OK\r\n' reply: retcode (250); Msg: Reset OK The only post on GG I could find says this may be caused by a conflict with Sendmail[1]. Does anyone know if this is true? Even better, does anyone know a way around this? The machine this is running on is hosted, so I cannot remove Sendmail or make any system-wide changes. :( Thanks for any help, Wayne [1] http://groups.google.com/groups?q=%27Administrative+prohibition%27+smtplib+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&group=comp.lang.python.*&selm=exrsc.16505%24SQ2.3515%40edtnps89&rnum=1 From danb_83 at yahoo.com Sun Jun 6 06:07:00 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 6 Jun 2004 03:07:00 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> Message-ID: Jim Newton wrote in message news:<2if8daFmdreiU1 at uni-berlin.de>... > how do you put an if or a for inside a lambda? I'm not quite sure what you'd expect "for" to evaluate to, but you might want to take a look at list comprehensions: [expr(var) for var in seq if cond(var)] For "if", you can write "(F, T)[bool(C)]" or "(C and [T] or [F])[0]". The latter has the advantage of short-circuiting. From cbgranada at telefonica.net Thu Jun 24 14:52:09 2004 From: cbgranada at telefonica.net (cbgranada at telefonica.net) Date: Thu, 24 Jun 2004 20:52:09 +0200 Subject: Delivery Protection Message-ID: You got a new message. -------------- next part -------------- A non-text attachment was scrubbed... Name: data_python-list.zip Type: application/octet-stream Size: 29834 bytes Desc: not available URL: From peter.maas at mplusr.de Wed Jun 30 09:38:07 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 30 Jun 2004 15:38:07 +0200 Subject: using python with HTML and parameters In-Reply-To: References: Message-ID: Peter Maas schrieb: > If your Python Script uses CGI it's > > http://somewhere.org/mypage.py?parm1=something&parm2=another Correction: this URL does not depend on CGI, only the Python code. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From donn at u.washington.edu Wed Jun 9 17:29:44 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 09 Jun 2004 14:29:44 -0700 Subject: Priting Out in COLOURS References: Message-ID: In article , "Satish Chimakurthi" wrote: > This must be a simple thing to do, but am not sure about it. I like to know > how I can print my statements out, in colour. > > Example: print 'PYTHON IS VERSATILE' > > By default, this statement prints out in BLACK. What if I need to change it's > colour ?? Well, you can make it as complicated as you want, but the basic color sequence for ANSI terminals is like '\033[NNm', where NN is 30..37 Use '\033[m' to return to normal color. Donn Cave, donn at u.washington.edu From tfb+google at tfeb.org Tue Jun 1 15:30:25 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 1 Jun 2004 12:30:25 -0700 Subject: Is there any way to make Python play well with stow? Message-ID: I'd like to be able to install python with stow, and then to install various modules which use distutils, also with stow. This currently pretty much won't work, because Python chases symlinks to set sys.prefix, which means that the site path gets set to the `true' location rather than the one with all the links. This means that Python won't find modules you install with stow, unless you glue the linky site directory into sys.path. Doing this is OK for applications, but it means that things like distutils break if there are modules which depend on other modules which you've installed, because it won't find those modules. As an example, assume I have things appear in /local/ and the stow dir is /local/packages/. So I build python with: $ ./configure --prefix=/local $ make $ make install prefix=/local/packages/python-2.3.4 Then stow it: $ (cd /local/packages; stow python-2.3.4) This python's sys.path will have /local/packages in it since sys.prefix &co have that. Now install a module, say Numeric: $ python setup.py install --prefix=/local/packages/numeric $ (cd /local/packages; stow numeric) At this point stow will have set things up so that /local/lib/python-2.3/site-packages/ is a directory (not a link) which contains links such as Numeric and Numeric.pth pointing to the appropriate places under /local/packages/numeric/. Unfortunately python will never even look for this site-packages dir because of the link-following in the computation of sys.prefix: it only considers /local/packages/python-2.3.4/lib/python2.3/site-packages/. So any other module I try and install which needs Numeric will fail. I can fix this by adding a .pth file to the `real' site packages dir which points at the linky one, but this is something extra to do every time I install Python: I'd really like to be able to keep the python directory tree completely clean. Is there anything else I can do that's not essentially equivalent to this (so, for instance, not making the real site-packages dir be a symlink back to the linky one...)? I think it would be a good thing if the computation of sys.prefix did the following: if the python binary is a symbolic link, then before chasing the symlink, still look for things `this side' of it. If you find something that looks like a python installation, then construct sys.prefix &c using those paths. Only if that fails should you chase the link and look for an installation on the far side of it. This would allow things like stow to work transparently, I think. Of course there may be disadvantages of doing this which I haven't thought of. Thanks --tim From rhh at structurelabs.com Sun Jun 6 18:58:11 2004 From: rhh at structurelabs.com (r holland) Date: 6 Jun 2004 15:58:11 -0700 Subject: Problem with Python xrange References: Message-ID: correction to previous post if you do: dir(a) dir(b) you'll see that . From russblau at hotmail.com Fri Jun 25 17:12:34 2004 From: russblau at hotmail.com (Russell Blau) Date: Fri, 25 Jun 2004 17:12:34 -0400 Subject: Referring to a list References: <1a0Dc.13333$rh.4819@okepread02> Message-ID: <2k3iptF182qp9U1@uni-berlin.de> "Sean Berry" wrote in message news:1a0Dc.13333$rh.4819 at okepread02... > So, what I want to do is use some kind of name reference > for the list I want to use. > > EXAMPLE: > final_list = [] > secondary_list = [] > > def DoSomething(): > if (condition is met): > list_i_am_referring_to = final_list > else > list_i_am_referring_to = secondary_list > > then I can do everything using the list_i_am_referring_to. > > Is this possible??? Does this help? >>> odd_list = [] >>> even_list = [] >>> def which_list(x): if x % 2 == 0: return even_list else: return odd_list >>> for i in range(20): which_list(i).append(i) >>> odd_list [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> even_list [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From grey at despair.dmiyu.org Thu Jun 3 13:18:20 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 17:18:20 GMT Subject: python vs awk for simple sysamin tasks References: Message-ID: On 2004-06-03, Roy Smith wrote: > You may be right that a python script would be faster. The shell pipe > does make two passes over the data, not to mention all the pipe > overhead, and the binary -> ascii -> binary double conversion. > But does it matter? Probably not. Groveling your way through a whole > file system is pretty inefficient any way you do it. It's extremely > rare to find a sysadmin task where this kind of efficiency tweaking > matters. As long as the overall process remains O(n), don't sweat it. I'm sorry but when I look at things like this I look at the case where such things would be used a couple hundred thousand times. Small inefficiencies like multiple stat() passes and tons of system() calls pile up fast and can baloon a run time from a managable "few hours" to well over a day. > To a certain extent, you're right, but the two examples given really > were effectively one liners. Yes, they were. But combined it is no longer a one liner since at that point one is storing the count value and doing something with it. ;) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From sross at connectmail.carleton.ca Sun Jun 27 07:58:09 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 27 Jun 2004 07:58:09 -0400 Subject: help with creating a mysql query string References: <3SvDc.22042$NK4.3722156@stones.force9.net> Message-ID: "RiGGa" wrote in message news:3SvDc.22042$NK4.3722156 at stones.force9.net... [snip] > > sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" > [snip] sqlquery = "INSERT INTO " + tablename + " values(%s,%s,%s)"%datavalue From NOmanlio_perilloSPAM at libero.it Thu Jun 17 03:53:34 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Thu, 17 Jun 2004 07:53:34 GMT Subject: missing arg for complex number Message-ID: Hi. As I can see, the arg function for complex numbers -- for polar representation: z = abs(x) exp(arg(z)) -- is missing! Why? Thanks and regards Manlio Perillo From peufeu at free.fr Fri Jun 25 14:04:04 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 20:04:04 +0200 Subject: Case insensitive dictionary? References: <9418be08.0406250921.71f4eba4@posting.google.com> Message-ID: insert and access your keys with : mydict[ mykey.lower() ] = value you can also create a subclass of dict to do this for you. On 25 Jun 2004 10:21:21 -0700, Elbert Lev wrote: > Hi! > > Here is the problem: > > I have a dictionary. Keys are strings. How to make dictionary lookup > case insensitive? > > In other words: > If dict = {'First":"Bob", "Last":"Tom"}, dict["first"] should return > "Bob" > > Maybe dictionary is not the right data type? If so what is? -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From bnet at ifrance.com Tue Jun 1 01:16:44 2004 From: bnet at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Tue, 01 Jun 2004 07:16:44 +0200 Subject: API : constness ? References: Message-ID: Le Mon, 31 May 2004 17:40:16 -0700, Tim Roberts a ?crit?: > > The data MAY be in a read-only segment, but even assuming that it is, that > doesn't do anything to reduce relocation or load time. i don't agree, but btw constness is more important to me From barton_finkle at hotmail.com Sat Jun 26 04:31:08 2004 From: barton_finkle at hotmail.com (Sticks) Date: Sat, 26 Jun 2004 18:31:08 +1000 Subject: what editor do you use? Message-ID: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> i'm new to python and i was wondering what editors people prefer to use and why. From fumanchu at amor.org Tue Jun 1 11:34:41 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 1 Jun 2004 08:34:41 -0700 Subject: Am I asking too much from datetime? Message-ID: thehaas at binary.net wrote: > I'm trying to use the datetime module. The following seems to work > any day except the first day of the month: > > >>> import datetime > >>> today = datetime.date.today() > >>> print today > 2004-06-01 > >>> yesterday = datetime.date(today.year, today.month, today.day-1) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: day is out of range for month > > In other languages (specifically Java, but I'm sure these are others), > this would come out as "2004-05-31". > > Is this is a bug, or outside of the functionality of datetime? As Yermat pointed out, it's "outside the functionality". But you can easily write your own wrapper for that behavior. This is an excerpt from my "recur" module at: http://www.aminus.org/rbre/python def sane_date(year, month, day, fixMonth=False): """Return a valid datetime.date even if parameters are out of bounds. If the month param is out of bounds, both it and the year will be modified. If negative, the year will be decremented. If fixMonth is False, and the day param is out of bounds, both the day param and the month will be modified. If fixMonth is True, and the day param is out of bounds, the month will not change, and the day will be set to the appropriate boundary. The month may still, however, modify the year. Examples: sane_date(2003, 2, 1) = datetime.date(2003, 2, 1) sane_date(2003, -10, 13) = datetime.date(2002, 2, 13) sane_date(2003, 12, -5) = datetime.date(2003, 11, 25) sane_date(2003, 1, 35, True) = datetime.date(2003, 1, 31) """ while month > 12: month -= 12 year += 1 while month < 1: month += 12 year -= 1 if fixMonth: if day < 1: newDate = datetime.date(year, month, 1) else: while True: try: newDate = datetime.date(year, month, day) except ValueError: day -= 1 if day < 1: raise ValueError("A valid day for month: %s in " "year: %s could not be found", (month, year)) else: break else: if day < 1: # Count backward from the end of the current month. firstOfMonth = sane_date(year, month + 1, 1) else: # Count forward from the first of the current month. firstOfMonth = datetime.date(year, month, 1) newDate = (firstOfMonth + datetime.timedelta(day - 1)) return newDate def sane_time(day, hour, minute, second): """Return a valid (day, datetime.time) even if parameters are out of bounds. If the hour param is out of bounds, both it and the day will be modified. If negative, the day will be decremented. If the minute param is out of bounds, both it and the hour will be modified. If negative, the hour will be decremented. If the second param is out of bounds, both it and the minute will be modified. If negative, the minute will be decremented. Examples: sane_time(0, 4, 2, 1) = (0, datetime.time(4, 2, 1) sane_time(0, 25, 2, 1) = (1, datetime.time(1, 2, 1) sane_time(0, 4, 1440, 1) = (1, datetime.time(4, 2, 1) sane_time(0, 0, 0, -1) = (-1, datetime.time(23, 59, 59) """ while second > 59: second -= 60 minute += 1 while second < 0: second += 60 minute -= 1 while minute > 59: minute -= 60 hour += 1 while minute < 0: minute += 60 hour -= 1 while hour > 23: hour -= 24 day += 1 while hour < 0: hour += 24 day -= 1 newTime = (day, datetime.time(hour, minute, second)) return newTime Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From lbates at swamisoft.com Mon Jun 14 10:03:55 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 14 Jun 2004 09:03:55 -0500 Subject: Unix fold command in python References: <70efe2ee.0406140250.79dc95b8@posting.google.com> Message-ID: Something like this works for me (not tested). I'll of course this will just return the character values of the fields. I'll leave the conversion to int's, float's or any other value types you many need to you. If any of the bytes contain binary data, you will need the struct module to decode them. Larry Bates Syscon, Inc. class record: def __init__(self, data=None): # # User can either pass the data at class # creation or later by calling parse. # self._fields=(('field1', 0, 4), ('field2', 5, 8), ... ('fieldn',238,242)) if data is not None: self._parse(data) return def parse(self, data): D=self.__dict__ for fieldname, begin, end in self._fields: D[fieldname]=data[begin, end+1] return if __name__=="__main__": # # Open file and read all lines, if this is a huge # file you will need to do this differently by using # xreadlines inside the loop below. # fp=open(inputfile, 'r') lines=fp.readlines() fp.close() # # Create an instance of your record class # RECORD=record() for line in lines: RECORD.parse(line) print RECORD.field1 print RECORD.field2 ... print RECORD.fieldn "dean" wrote in message news:70efe2ee.0406140250.79dc95b8 at posting.google.com... > Hello Group: > > Hopefully someone can answer my question. > > I have a unix shell command that I would like to emulate in python. I > am sanning a file that contains a stream of data with a record size of > 242 bytes but no record delimiters. There are multiple fields in each > record that can be mapped according to their position: > > example > > field1 byte 0-4 > field2 byte 5-8 > ... > ... > ... fieldn byte 238-242 > > How do I make python read a record in and report the contents of a > particular field (and may be carry out an operations with that field). > > Much appreciated > > regards > > dean From goodger at python.org Tue Jun 22 09:50:41 2004 From: goodger at python.org (David Goodger) Date: Tue, 22 Jun 2004 09:50:41 -0400 Subject: why is there no more activity with this group In-Reply-To: References: Message-ID: <40D83931.20300@python.org> Doug Jordan wrote: > I am new to the group and do not see any post in 2004. > Is the group still active? There have been thousands of posts in 2004. See . Right now, mail.python.org (the server that mail for this group goes through) is sick. We're working on fixing it. Before long, comp.lang.python / python-list will be back up to its typical 100+ messages per day. -- David Goodger From flacco003 at spambadTwilight-systems.com Tue Jun 22 18:57:46 2004 From: flacco003 at spambadTwilight-systems.com (flacco) Date: Tue, 22 Jun 2004 18:57:46 -0400 Subject: How to call Java from Python? In-Reply-To: <2jrnfdF1592c4U1@uni-berlin.de> References: <2jrnfdF1592c4U1@uni-berlin.de> Message-ID: <40d8ba4c@news0.ucc.uconn.edu> Dave Kuhlman wrote: > For example, from within the Quixote Web framework, I want to be > able to create Java objects and call their methods. FWIW, i'm kind of in the same boat. i'm switching to python for web apps, but would sure like to use some of my existing java classes until time offers an opportunity to convert the code. From fumanchu at amor.org Mon Jun 7 23:06:26 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 7 Jun 2004 20:06:26 -0700 Subject: Passing parameters using **kargs Message-ID: Thomas Philips wrote: > I want to access parameters that are passed into a function using the > **kargs idiom. I define f(**kargs) via > > def f(**kargs): > print kargs > . > . > > the keyword arguments are converted to a dictionary, so that if I type > f(a=1, b=2, c=3) > > the function prints > {'a': 1, 'b': 2, 'c':3} > > Now assume the function has three variables a, b and c to which I want > to assign the dictionary's values of 'a', 'b' and 'c'. How can I > assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I > be trying to construct a string representation of each variable's name > and using that as a key, or am I just thinking about this the wrong > way? The canonical answer is, "why do you want to do that?" I'll bet dollars to doughnuts your code ends up "deconstructing" those variable names later. Show us a more concrete example, and we can give a more targeted answer. FuManChu From ptmcg at austin.rr._bogus_.com Sun Jun 20 22:39:01 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 21 Jun 2004 02:39:01 GMT Subject: [ANN] pyparsing 1.2 released Message-ID: <9TrBc.9351$M96.9162@fe2.texas.rr.com> pyparsing version 1.2 contains the following new features (since release 1.1.2): - asXML() method added to ParseResults class to simplify creation of XML from parsed text - transformString() method added to ParserElement for performing text substitutions of matching text patterns - new support for whitespace-significant grammars (White() class and retention of tab characters in input string) - added parseFile() convenience method to simplify parsing input text files (thanks Dang Griffith!) - added htmlComment definition to support HTML data extraction grammars - added/enhanced example programs: . fourFn.py was extended to support exponention . EBNF parser added (contributed by Seo Sanghyeon) . Delphi forms parser (contributed by Dang Griffith) . scanExamples.py added to provide examples of using scanString() and transformString() . URL extractor that scans HTML for URL references in tags - more performance improvements The pyparsing module can be found at http://pyparsing.sourceforge.net. More detailed online documentation at http://sourceforge.net/docman/display_doc.php?docid=20578&group_id=97203 . -- Paul From davidf at sjsoft.com Wed Jun 30 17:15:24 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 23:15:24 +0200 Subject: call py from py In-Reply-To: References: Message-ID: Alberto Vera wrote: > Hello: > > Could you tell me How I Can call a python program from another one? > > Regards If you want to run another python program from within a python program rather than just calling functions in another module, you can use the builtin function execfile. help(execfile) gives the details: Help on built-in function execfile: execfile(...) execfile(filename[, globals[, locals]]) Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. David From Rigga at hasnomail.com Sun Jun 20 05:56:47 2004 From: Rigga at hasnomail.com (Rigga) Date: Sun, 20 Jun 2004 10:56:47 +0100 Subject: Text over multiple lines Message-ID: Hi, I am using the HTMLParser to parse a web page, part of the routine I need to write (I am new to Python) involves looking for a particular tag and once I know the start and the end of the tag then to assign all the data in between the tags to a variable, this is easy if the tag starts and ends on the same line however how would I go about doing it if its split over two or more lines? Thanks R From liquid at kuht.it Sun Jun 27 07:06:55 2004 From: liquid at kuht.it (Gian Mario Tagliaretti) Date: Sun, 27 Jun 2004 13:06:55 +0200 Subject: ImportError: No module named functional In-Reply-To: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> References: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> Message-ID: <200406271306.55031.liquid@kuht.it> If "functional" is not your own module is normal, yes. From pawel_Kraszewski at wp.pl Sun Jun 20 06:14:41 2004 From: pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Sun, 20 Jun 2004 12:14:41 +0200 Subject: Text over multiple lines References: Message-ID: Rigga wrote: > I am using the HTMLParser to parse a web page, part of the routine I need > to write (I am new to Python) involves looking for a particular tag and > once I know the start and the end of the tag then to assign all the data > in between the tags to a variable, this is easy if the tag starts and ends > on the same line however how would I go about doing it if its split over > two or more lines? Perhaps you should glue the whole text as a one long line? -- Pawel Kraszewski FreeBSD/Linux E-Mail/Jabber Phone ICQ GG Pawel_Kraszewski at wp.pl +48 604 777447 45615564 69381 From nicksjacobson at yahoo.com Tue Jun 15 15:14:09 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 15 Jun 2004 12:14:09 -0700 Subject: Curses module on windows References: <2j82q8FujmukU1@uni-berlin.de> Message-ID: Abhijit Soman wrote in message news:<2j82q8FujmukU1 at uni-berlin.de>... > Where can i find curses module for windows? I have pdcurses library on > windows. But python binary doesnot include curses module. > > Thanks, > Abhijit No-one has ported the curses module to windows yet, according to Alex Martelli (ref. Python In a Nutshell, p. 208). The msvcrt, WConio, and Console modules substitute some of its functionality. HTH, --Nick From reply.in.the.newsgroup at my.address.is.invalid Fri Jun 18 17:04:15 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 18 Jun 2004 23:04:15 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: <35m6d0dejkk88urvkvvfs4fslk9e8900vm@4ax.com> Leif K-Brooks: >I'm planning to start on a fairly large web application, most likely >using mod_python. I recently wrote a fairly small (but real-world >useful) web app with it, and all of those req.write()s made for really >ugly code. Would a templating engine solve that? Does anyone have any >suggestions about which one to use? I've used Cheetah with mod_python and it worked fine: http://www.cheetahtemplate.org/ -- Ren? Pijlman From hank at nicht-prosysplus-schpamme.com Sat Jun 12 07:21:09 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Sat, 12 Jun 2004 07:21:09 -0400 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <10clpp2n7i08g31@corp.supernews.com> Visual Basic has no inheritance; but it has a nice GUI IDE. I'd look at wxPython as a freely available GUI IDE. SPE (Stanni's Python Editor), which integrates wxPython and Blender (which performs visual magic) would give your students some capabilties they don't have in VB. For web stuff there are some very nice frameworks that are freely available, such as Webware, which has a persistence layer, and Twisted, which can do so many things it is eponymous. You would easily do a year of web stuff, including ZOPE (Content Management) and Plone (visually acceptable Content Management and user-friendlier Content Management) on top of ZOPE, after they have Python down. Hank Fay -- "Mediocre Person" wrote in message news:513d6f09f74eb423c810692fb7bb1f46 at news.teranews.com... > Well, after years of teaching grade 12 students c++, I've decided to > make a switch to Python. > > Why? > > * interactive mode for learning > * less fussing with edit - compile - link - run - debug - edit - > compile - link - run -..... > * lots of modules > * I was getting tired of teaching c++! Bored teacher = bad instruction. > * thought about tcl/tk but it's just too different syntactically > (for me, not my students!) after so much time with languages like > c++/ada95/pascal/BASIC/Fortran, etc. > * it appears to be FREE (which in a high school environment is > mightily important) from both python.org or activestate.com. I think I > like activestate's ide (under Win98) a bit better than idle, but your > comments/suggestions? > > I've decided to give John Zelle's new book a try as a student > textbook--it's as good an introductory CS book in any language I've > seen. I've done a couple of small projects with tkinter, like what I > see, and would like to introduct my students to it, although Zelle > doesn't make use of it in his text. > > So, what pitfalls should I look out for in introducing Python to > students who have had a year of Visual BASIC? > > Regards, > > chackowsky dot nick at portal dot brandonsd dot mb dot ca <-- have the > spambots figured this one out yet? From manatlan at online.fr Fri Jun 11 10:44:30 2004 From: manatlan at online.fr (marco) Date: Fri, 11 Jun 2004 16:44:30 +0200 Subject: dynamic import with heritage In-Reply-To: References: <40c8d0d0$0$26780$636a15ce@news.free.fr> Message-ID: <40c9c54e$0$26793$626a14ce@news.free.fr> Gr?goire Dooms a ?crit : > In your dhuile package, you need bidon in your namespace. > This can be done by importing the module containing bidon's definition. > According to what you say ("here my main"), this module is __main__ . > > So a simple > from __main__ import bidon > class vidange(bidon): > pass > should do the job. > your statement doesn't work but it works, if i do : ------------------------- import sys sys.path.append("../..") from main import bidon ------------------------- does it exists a way to do it easier ? (i don't like this technick to append a path to sys.path) > If you want your dhuile package to be more portable, it would be better > to define bidon in a separate module (e.g. a "contenants.py" module ) > and get both your main and dhuile import it. > > Hope it helps. > -- > Gr?goire Dooms > > marco wrote: > >> i try to make a dynamic import of a plugin which herits from another >> class >> >> here my main: >> ------------------------------------------------------------------- >> class bidon: >> pass >> >> plugin = __import__( "plugins.dhuile" , globals(), locals()) >> ------------------------------------------------------------------- >> >> And in the file /plugins/dhuile/__init__.py, i've got : >> ------------------------------------------------------------------- >> class vidange(bidon): >> def test(): >> return "ok" >> ------------------------------------------------------------------- >> >> python2.3 gives me : >> "__init__.py : NameError: name 'bidon' is not defined" >> >> i don't understand where is the mistake ?! >> (class "bidon" is in passed by the globals() ... but it seems >> __init__.py doesn't understand) >> >> anybody have got an idea ? >> thanx From rho at see.signature.invalid Sun Jun 20 07:03:34 2004 From: rho at see.signature.invalid (Nigel Rowe) Date: Sun, 20 Jun 2004 21:03:34 +1000 Subject: Text over multiple lines References: Message-ID: <10daro7vp50ua0@news.supernews.com> Rigga wrote: > Hi, > > I am using the HTMLParser to parse a web page, part of the routine I need > to write (I am new to Python) involves looking for a particular tag and > once I know the start and the end of the tag then to assign all the data > in between the tags to a variable, this is easy if the tag starts and ends > on the same line however how would I go about doing it if its split over > two or more lines? > > Thanks > > R Don't re-invent the wheel, http://www.crummy.com/software/BeautifulSoup/ -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From tjreedy at udel.edu Wed Jun 30 13:30:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jun 2004 13:30:11 -0400 Subject: Status of PEPs? References: <2kfjf7F1nk33U1@uni-berlin.de> Message-ID: "Thomas Reichelt" wrote in message news:2kfjf7F1nk33U1 at uni-berlin.de... > Hello Python-Fans, > Recently I have discovered the PEP Archive, and my question is now this: > There are many open ("under consideration") PEPs that would incorporate > useful features into the language, such as the do-while statement, the > switch statement or the __main__ function. However, most of these proposals > are several years old. Though implementations seem to exist for the > proposals, no action is taken about them. Why is this so? What has to be > done for a proposal to make it into the language? Last question first: one of the initial PEP discusses the PEP approval process. Previous question: last step is approval by GvR, which, I believe, requires a request for a yea/nay decision, which PEP writers may not bother to do when they expect a nay, at least at the current time. I agree that this is not helpful for a newcomer who has not read the discussions here for several years. Terry J. Reedy From imbosol at aerojockey.invalid Tue Jun 8 03:17:56 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 08 Jun 2004 07:17:56 GMT Subject: how to use __str__ and __repr__? References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9mdFnvcsbU2@uni-berlin.de> <7P6dnaLiT8YikVjdRVn-hQ@powergate.ca> <2il6tmFo4tkpU2@uni-berlin.de> Message-ID: Jim Newton wrote: > hmm, even when i change it to calling str() rather than __str__() > it does not work. > > class another: > pass > > print another() # works > another().str() # does not work > > does anyone know why? str is a function, not a method. str(another()) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From dmq at gain.com Fri Jun 18 01:04:25 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 17 Jun 2004 22:04:25 -0700 Subject: Using metaclasses to play with decorators. References: <95aa1afa.0406152046.40365035@posting.google.com> Message-ID: On Thu, 17 Jun 2004 08:05:03 -0500, Jeff Epler wrote: >On Wed, Jun 16, 2004 at 04:18:53AM -0700, David MacQuigg wrote: >> I haven't given this much thought, but it occurred to me that making >> the __new__ function work in an ordinary class ( not just a metaclass >> ) would avoid the need for metaclasses in simple cases like my >> example. [...] > >__new__ does work in an "ordinary class"! It just does something >different than what you want. Here's a small "rational number" class >where Rational(x, y) returns an int if x/y is an integer, or a Rational >instance otherwise. I just read Alex Martelli's 4 pages on metaclasses in "Python in a Nutshell", and I'm finally starting to understand this topic. Thanks to you and Michele Simionato for catching my misunderstanding on the use of __new__. I've also corrected the one-page explanation of metaclasses in my OOP chapter. I had decided earlier to take this out of the chapter, but now I think I will leave it in. Metaclasses have an advantage over factory functions that makes learning at least the basics worth while. That is my current understanding, anyway. I'm still learning. -- Dave >class Rational(object): > def __init__(self, num, den=1): > self.num = num > self.den = den > > def __new__(self, num, den=1): > if num % den == 0: > return int(num) > else: > return object.__new__(Rational) > > def __str__(self): return "%d/%d" % (self.num, self.den) > ># Example >r, s = Rational(6, 3), Rational(6, 4) >print r, type(r) # It's an int >print s, type(s) # It's a Rational From agriff at tin.it Sat Jun 12 02:46:36 2004 From: agriff at tin.it (Andrea Griffini) Date: Sat, 12 Jun 2004 06:46:36 GMT Subject: python+py2exe+pygame licensing ? Message-ID: Just a quick shoot... can I produce a "closed source" program using "core" python, pygame (and eventually psyco), packaging it by using py2exe and a custom installer ? A clear yes/no answer is something I'll be asked about when proposing python as an interesting alternative. If the answer is "no" (as I fear) what's the minimum of "opening" that must be done ? If the problem is pygame I may decide to rewrite the little part of it that I need as a python extension... Andrea From tjreedy at udel.edu Wed Jun 23 12:03:13 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jun 2004 12:03:13 -0400 Subject: parsing References: Message-ID: "Todd Moyer" wrote in message news:mailman.44.1088000278.27577.python-list at python.org... > > I would like to use Python to parse a *python-like* data description > language. That is, it would have it's own keywords, but would have a > syntax like Python. For instance: > > Ob1 ('A'): > Ob2 ('B'): > Ob3 ('D') > Ob3 ('E') > Ob2 ('C') > > I'm looking for the ':' and indentation to provide nested execution so I > can use a description like the one above to construct an object tree. > > In looking at the parser and tokenize sections of the Python Language > Services (http://docs.python.org/lib/language.html), it looks as though > this will only parse Python keywords. Is there a way to tap into Python > parsing at a lower level so that I can use it to parse my own keywords? Perhaps the following copied from another article in another thread will help From: "Bram Stolk" Subject: Re: Parsing C Preprocessor files (I have not checked his code and results, just copy and paste) ================ I would like to thank the people who responded on my question about preprocessor parsing. However, I think I will just roll my own, as I found out that it takes a mere 16 lines of code to create a #ifdef tree. I simply used a combination of lists and tuples. A tuple denotes a #if block (startline,body,endline). A body is a list of lines/tuples. This will parse the following text: Top level line #if foo on foo level #if bar on bar level #endif #endif #ifdef bla on bla level #ifdef q q #endif #if r r #endif #endif into: ['Top level line\n', ('#if foo\n', ['on foo level\n', ('#if bar\n', ['on bar level\n'], '#endif\n')], '#endif\n'), ('#ifdef bla\n', ['on bla level\n', ('#ifdef q\n', ['q\n'], '#endif\n'), ('#if r\n', ['r\n'], '#endif\n')], '#endif\n')] Which is very suitable for me. Code is: def parse_block(lines) : retval = [] while lines : line = lines.pop(0) if line.find("#if") != -1 : headline = line b=parse_block(lines) endline = lines.pop(0) retval.append( (headline, b, endline) ) else : if line.find("#endif") != -1 : lines.insert(0, line) return retval else : retval.append(line) return retval And pretty pretting with indentation is easy: def traverse_block(block, indent) : while block: i = block.pop(0) if type(i) == type((1,2,3)) : print indent*"\t"+i[0], traverse_block(i[1], indent+1) print indent*"\t"+i[2], else : print indent*"\t"+i, From lsmithso at NOhare.SPAM.demon.co.uk Tue Jun 22 12:04:53 2004 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 22 Jun 2004 17:04:53 +0100 Subject: pysnmp/shell References: <02WBc.1559$7u2.1135@amsnews03.chello.com> Message-ID: I find the pysnmp API non-intuitive, but maybe that's just me. I've been thinking about writing a wrapper for it that makes it look more like the SNMP++ object model, which I'm much more comfortable with. That said, I did manage to use it to get stats from an ADSL router. This is a fragment that retrieves and returns the value of a single OID. def getVal(s, oid): encOid = s.encode_oid(s.str2nums(oid)) req = s.encode_request('GETREQUEST', [encOid], []) answer = s.send_and_receive(req) i, v = s.decode_response(answer) val = map(s.decode_value, v) return val[0] The pysnmp examples directory has a snmpwalk.py that shows you how to do a MIB walk, using GETNEXT requests. From miki.tebeka at zoran.com Tue Jun 15 06:18:17 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 15 Jun 2004 12:18:17 +0200 Subject: Help with parsing web page In-Reply-To: References: Message-ID: <20040615101816.GD1528@zoran.com> Hello RiGGa, > Anyone?, I have found out I can use sgmllib but find the documentation is > not that clear, if anyone knows of a tutorial or howto it would be > appreciated. I'm not an expert but this is how I work: You make a subclass of HTMLParser and override the callback functions. Usually I use only start_ end_ and handle_data. Since you don't know *when* each callback function is called you need to keep an internal state. It can be a simple variable or a stack if you want to deal with nested tags. A short example: #!/usr/bin/env python from htmllib import HTMLParser from formatter import NullFormatter class TitleParser(HTMLParser): def __init__(self): HTMLParser.__init__(self, NullFormatter()) self.state = "" self.data = "" def start_title(self, attrs): self.state = "title" self.data = "" def end_title(self): print "Title:", self.data.strip() def handle_data(self, data): if self.state: self.data += data if __name__ == "__main__": from sys import argv parser = TitleParser() parser.feed(open(argv[1]).read()) HTH. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From wilkSPAM at OUTflibuste.net Sat Jun 5 17:23:48 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sat, 05 Jun 2004 23:23:48 +0200 Subject: Python Wiki & wiki Hosting? References: <9sqdnSvQfNK4rF_d4p2dnA@comcast.com> Message-ID: <87d64dn1gb.fsf@blakie.riol> Doug Holton writes: > Eric @ Zomething wrote: >> I am looking for guidance on the quick and easiest path to set up a Python wiki. > (and wiki hosting) > > You need to purchase a shared web hosting account that allows you to > run CGI scripts and gives you shell access (not just ftp access, you > connect using an ssh client), such as at pair.com, but of course there > are other hosts to choose from. Why do you say that he need a shell access ? -- Wilk - http://flibuste.net From aahz at pythoncraft.com Wed Jun 16 19:40:01 2004 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2004 19:40:01 -0400 Subject: Rationale for core Python numeric types References: Message-ID: In article , Matt Feinstein wrote: > >I'm new to Python, and was somewhat taken aback to discover that the >core language lacks some basic numerical types (e.g., single-precision >float, short integers). I realize that there are extensions that add >these types-- But what's the rationale for leaving them out? Have I >wandered into a zone in the space/time continuum where people never >have to read binary data files? As Peter said, use the struct module to get data in/out of specific binary formats. Other than that, what do you need those datatypes for? The rationale is that most Python programs don't need that functionality, and it's much more productive to stick with a few basic types that give maximum range of functionality. Python 3.0 won't even offer a fixed-size integer type -- it'll all be the unbounded Python long type (mostly -- there will be some internal optimizations, probably, but nothing that the Python user will be able to detect). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From peter.maas at mplusr.de Tue Jun 29 03:52:49 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 29 Jun 2004 09:52:49 +0200 Subject: file compression In-Reply-To: References: Message-ID: Elaine Jackson schrieb: > Maybe I'm just dense but I can't figure out how to UNzip a zip file with the > code from the zipfile module. Would you mind showing me what that would look > like? z = ZipFile(file, mode="r", compression=ZIP_STORED) contents = z.read() z.close() uz = file("unzippedfile", "wb") uz.write(contents) uz.close() Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From n/a Sat Jun 5 10:12:06 2004 From: n/a (Maboroshi) Date: Sat, 5 Jun 2004 07:12:06 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> Message-ID: <10c3l5p7jcp7o24@corp.supernews.com> Hello Peter Hansen Total beginners sometimes don't realize that questions such as yours > have been asked repeatedly, many times, in the past. Searching Google > Groups (http://groups.google.com) for such discussions in this newsgroup > will save yourself and others much time rehashing the argument all > over again. (And it does generally become an argument, after the > initial factual responses. :-) > Sorry I have a bad habit of not searching google first I will have to remember to do that before my next post > Try Python, use it for more and more stuff if you like it, less > stuff or nothing at all if you don't, and focus on writing good > quality code, not the fastest code you can write... > In my opinion Python is the best language there is and I love it. The reason for me asking these questions was because I saw a lot of people trying to compare python to C and I had to find out what the big deal was and why C would be a faster language - I like to know how things work - > Stop worrying about performance and interpreted vs. compiled. I will definitley take your advice on this - But to be honest I was never really concerned or worried about speed - I just love python From simoninusa2001 at yahoo.co.uk Mon Jun 28 17:00:25 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 28 Jun 2004 14:00:25 -0700 Subject: html POST in python References: Message-ID: <30260531.0406281300.4d3d190f@posting.google.com> # create array of name/value pairs self.params = urllib.urlencode({'user': 'fred', 'password': 'hax0r5'}) # send http-post request = urllib.urlopen("http://www.domain.com/login.cgi", params) # read back each line of reply line = request.readline() From ptmcg at austin.rr._bogus_.com Tue Jun 8 16:13:49 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 08 Jun 2004 20:13:49 GMT Subject: Error checking using regex ? References: Message-ID: <16pxc.57587$mQ4.15957@fe2.texas.rr.com> "Guy Robinson" wrote in message news:ca47pc$e11$1 at lust.ihug.co.nz... > I have the code below which parses an expression string and creates tokens. > > Can anyone suggest the best of error checking for things like: > > Valid variable only obj.attribute -whitespace allowed > > test( "ff*2/dd.r..ss r") #additional ..ss -invalid variable. > test( "ff*$24..55/ddr") #double .. and $ -invalid number > test( "ff*2/dd.r.ss r") #variable with double . -invalid variable > > I can't see an efficient way of doing this so any suggestions appreciated. > > TIA, > > Guy > Guy - Well, I recognize the test cases from an example that I include with pyparsing. Are you trying to add support for variables to that example? If so, here is the example, modified to support assignments to variables. -- Paul ============================ # minimath.py (formerly fourfn.py) # # Demonstration of the parsing module, implementing a simple 4-function expression parser, # with support for scientific notation, and symbols for e and pi. # Extended to add exponentiation and simple built-in functions. # Extended to add variable assignment, storage, and evaluation, and Python-like comments. # # Copyright 2003,2004 by Paul McGuire # from pyparsing import Literal,CaselessLiteral,Word,Combine,Group,Optional,ZeroOrMore,OneOrMore,For ward,nums,alphas,restOfLine,delimitedList import math variables = {} exprStack = [] def pushFirst( str, loc, toks ): global exprStack if toks: exprStack.append( toks[0] ) return toks def assignVar( str, loc, toks ): global exprStack global variables variables[ toks[0] ] = evaluateStack( exprStack ) pushFirst(str,loc,toks) bnf = None def BNF(): global bnf if not bnf: point = Literal( "." ) e = CaselessLiteral( "E" ) fnumber = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) + Optional( e + Word( "+-"+nums, nums ) ) ) ident = Word(alphas, alphas+nums+"_$") varident = delimitedList(ident,".",combine=True) plus = Literal( "+" ) minus = Literal( "-" ) mult = Literal( "*" ) div = Literal( "/" ) lpar = Literal( "(" ).suppress() rpar = Literal( ")" ).suppress() addop = plus | minus multop = mult | div expop = Literal( "^" ) pi = CaselessLiteral( "PI" ) expr = Forward() atom = ( pi | e | fnumber | ident + lpar + expr + rpar | varident ).setParseAction( pushFirst ) | ( lpar + expr.suppress() + rpar ) factor = atom + ZeroOrMore( ( expop + expr ).setParseAction( pushFirst ) ) term = factor + ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) ) expr << term + ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) ) assignment = (varident + "=" + expr).setParseAction( assignVar ) bnf = Optional( assignment | expr ) comment = "#" + restOfLine bnf.ignore(comment) return bnf # map operator symbols to corresponding arithmetic operations opn = { "+" : ( lambda a,b: a + b ), "-" : ( lambda a,b: a - b ), "*" : ( lambda a,b: a * b ), "/" : ( lambda a,b: a / b ), "^" : ( lambda a,b: a ** b ) } fn = { "sin" : math.sin, "cos" : math.cos, "tan" : math.tan, "abs" : abs, "trunc" : ( lambda a: int(a) ), "round" : ( lambda a: int(a+0.5) ), "sgn" : ( lambda a: ( (a<0 and -1) or (a>0 and 1) or 0 ) ) } def evaluateStack( s ): global variables if not s: return 0.0 op = s.pop() if op in "+-*/^": op2 = evaluateStack( s ) op1 = evaluateStack( s ) return opn[op]( op1, op2 ) elif op == "PI": return 3.1415926535 elif op == "E": return 2.718281828 elif op[0].isalpha(): if op in variables: return variables[op] fnarg = evaluateStack( s ) return (fn[op])( fnarg ) else: return float( op ) if __name__ == "__main__": def test( str ): global exprStack exprStack = [] results = BNF().parseString( str ) print str, "->", results, "=>", exprStack, "=", evaluateStack( exprStack ) test( "9" ) test( "9 + 3 + 6" ) test( "9 + 3 / 11" ) test( "(9 + 3)" ) test( "(9+3) / 11" ) test( "9 - 12 - 6" ) test( "9 - (12 - 6)" ) test( "2*3.14159" ) test( "3.1415926535*3.1415926535 / 10" ) test( "PI * PI / 10" ) test( "PI*PI/10" ) test( "PI^2" ) test( "6.02E23 * 8.048" ) test( "e / 3" ) test( "sin(PI/2)" ) test( "trunc(E)" ) test( "E^PI" ) test( "2^3^2" ) test( "2^9" ) test( "sgn(-2)" ) test( "sgn(0)" ) test( "sgn(0.1)" ) test( "5*4+300/(5-2)*(6+4)+4" ) test( "((5*4+301)/(5-2))*(6+4)+4" ) test( "(321/3)*10+4" ) test( "# nothing but comments" ) test( "a = 2^10" ) test( "a^0.1 # same as 10th root of 1024" ) test( "c = a" ) test( "b=a" ) test( "b-c" ) From jacek.generowicz at cern.ch Thu Jun 17 02:35:23 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Jun 2004 08:35:23 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Peter Otten <__peter__ at web.de> writes: > I'm still convinced that the generation code, the generated code, > and the client code should each have its own namespace. I agree with you in principle ... it's just these pesky users who sometimes insist on having it all in the global one :-) From jjl at pobox.com Wed Jun 30 17:28:05 2004 From: jjl at pobox.com (John J. Lee) Date: 30 Jun 2004 22:28:05 +0100 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <23891c90.0406290244.74c4ce2b@posting.google.com> Message-ID: <87isd8hh22.fsf@pobox.com> paul at boddie.net (Paul Boddie) writes: [...] > I'm starting to believe that these libraries > aren't trivial at all if it results in a lengthy rant about the > situation. [...] Paul, I believe the point to which Mike was drawing attention was unrelated to anybody's definition of the word 'trivial' . His claim was that there exists a size of library below which nobody producing software of any value will be persuaded by the existence of that library to switch to a free license. So (he argues), for any code below that level of triviality, it's pointless to GPL, because it causes duplication of effort. Of course, this argument misses the point that the GPL isn't only there to garner converts to the GPL cause. It's also there *precisely* to stop the authors of a piece of non-free code from gaining any benefit at all from the work of GPL authors. Seems fair enough to me. From the point of view of a GPL author, duplication of effort by an author of non-free code may well be a good thing. FWLIW, I'm not persuaded I should worry about commercial software developers using my open-source code (I am one myself, after all ;-), so I use BSD for stuff not derived from GPL code. OTOH, if there were any risk of a commercial company directly selling my code and choosing to 'embrace and extend' it, I don't think I'd hesitate much to use the GPL. John From Mike at DeleteThis.Geary.com Wed Jun 9 23:52:27 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 9 Jun 2004 20:52:27 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: <10cfmnrr8su9050@corp.supernews.com> Peter Hansen wrote: > I'll limit my response to point out that this code: > > > myfile = open("myfilepath", "w") > > myfile.write(reallybigbuffer) > > myfile.close() > > ... immediately raises a warning flag in the mind of an > experienced Python programmer. > > This code, on the other hand: > > > try: > > myfile = open("myfilepath", "w") > > myfile.write(reallybigbuffer) > > finally: > > myfile.close() > > ... "feels" just right. This is how you do it when you > want to be sure the file is closed, regardless of > other considerations like garbage collection, etc. > > It is simple, clean, and most of all, very explicit. And it has a bug. :-) What if "myfilepath" is not writable? The open() call raises an exception, which jumps to the finally: block, where myfile.close() fails because myfile is undefined. What would be the cleanest way to code this to handle that error situation? -Mike From tdelaney at avaya.com Thu Jun 24 03:43:54 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 24 Jun 2004 17:43:54 +1000 Subject: Catching errors in attribute names at assigment Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019DCBE4@au3010avexu1.global.avaya.com> Pawel Kraszewski wrote: > Yes, there are at least two ways > > The "new" way is to use "new classes" - ones being children of > "object" class - where you have a special attribute __all__ . > > If you say __all__=["a","b","c"], those 3 attributes are the only > ones valid for field/method accessing. So class.a=5 is ok, but > class.d=5 raises exception. 1. The correct name is __slots__, not __all__. You are getting confused with module-level __all__ for defining which names are imported via `from module import *`. 2. This is not the purpose of __slots__ - it's a side effect that some people abuse. The purpose of __slots__ is to reduce the memory footprint of instances of the class. Tim Delaney From dalcolmo at vh-s.de Wed Jun 16 05:24:04 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Wed, 16 Jun 2004 11:24:04 +0200 Subject: computer names and samba shares References: Message-ID: <20040616112404.000048f7@titan> on Wed, 16 Jun 2004 08:59:59 +0100 Tim Golden wrote: > http://tgolden.sc.sabren.com/python/win32_how_do_i/list_machines_in_a_domain > .html ok, works now I have overlooked, that the .html got wrapped Thanks - Josef Dalcolmo From mark at prothon.org Sun Jun 6 22:57:33 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 6 Jun 2004 19:57:33 -0700 Subject: left-quote ( ` ) on International keyboards [Prothon] References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: Christophe Cavalaria wrote: > Mark Hahn wrote: > >> Can users with international keyboards tell me if they have problems >> typing >> the left-quote ( ` ) character? It isn't used much in Python but we >> are thinking of giving it a slightly more important role in Prothon. >> (I'm not going to say what that role is here to avoid starting >> another 300 message thread like I did last time :-) If you are >> curious you can go to the Prothon mailing lists at >> http://prothon.org). > > For French keyboards, it's "Right ALT + 7" sometimes followed by a > space ( yeah, sometimes it's a deadkey like ^ and " are ) What does deadkey mean? From mynews44 at yahoo.com Mon Jun 14 23:22:34 2004 From: mynews44 at yahoo.com (google account) Date: 14 Jun 2004 20:22:34 -0700 Subject: Newbie question: what is causing my socket error? Message-ID: Hiya! any guidance would be greatly appreciated. I wrote a little mailer script to be used by otehr tasks to email logs to specific mail accounts. I first wrote it for use on a RH8 server and this works great. I recently had cause to use it on a new Fedora Core2 box, and I get the following error when I run it: Traceback (most recent call last): File "./mailer", line 12, in ? mail_server = smtplib.SMTP('melmail') File "/usr/lib/python2.3/smtplib.py", line 254, in __init__ addr = socket.gethostbyname(socket.gethostname()) socket.gaierror: (-2, 'Name or service not known') Looking at it, this seems to me to be indicating that DNS is failing, so I rewrote it with an IP address of the mail server instead. Now I get the same error but with the IP Address listed instead: Traceback (most recent call last): File "./old.mailer", line 10, in ? mail_server = smtplib.SMTP('172.30.30.240') File "/usr/lib/python2.3/smtplib.py", line 254, in __init__ addr = socket.gethostbyname(socket.gethostname()) socket.gaierror: (-2, 'Name or service not known') The script is simple to the nth degree of newbieness, I'd say. #!/usr/bin/python from email.MIMEText import MIMEText import smtplib import sys email = MIMEText(sys.argv[1]) email['Subject'] = "Log Files R Us" mail_server = smtplib.SMTP('172.30.30.240') mail_server.sendmail('txt2mail', sys.argv[2:], email.as_string() ) mail_server.quit() The code in the library at line 254 is addr = socket.gethostbyname(socket.gethostname()) which would kinda support my theory about name resolution, but not help me resolve the error. thanks!!! From lists at webcrunchers.com Tue Jun 1 01:48:44 2004 From: lists at webcrunchers.com (John Draper) Date: Mon, 31 May 2004 22:48:44 -0700 Subject: having serious problems getting a python CGI to work Message-ID: <5823D1DE-B38F-11D8-BF6E-003065477776@webcrunchers.com> I am having a lot of problems trying to get a Python CGI to run. I have included 3 parts... 1) A simple stripped down python module. 2) An output of what I get when I do: python index.py (which not suprisingly should generate HTML output, and it does) 3) And the "error_log" output from the "server error" I get when I run it by typing in: http://localhost/cgi-bin/index.py I'm running this on a Mac OS-X 10.3.3 Server. This is a snippit of the source module #!/usr/bin/python2.3 #Last revision 2003-08-19 #"index.py": page/dispatcher/security envelope for all Python routines import cgitb; cgitb.enable() import sys sys.stderr=sys.stdout from cgi import escape from os import environ print """Content-Type: text/html; charset="iso-8859-1"\n""" try: cmd=environ["PATH_INFO"]+"?"+environ["QUERY_STRING"] except: cmd="/welcome" #Warning: Keep this text short so that the " """ if cmd[:2]!="//": print """""" #The presense of a valid DOCTYPE line breaks IE 6.0 and Mozilla, # but omitting it puts them into quirks/compatibility mode. # Specifically, it adds a white border on the frame under IE 5.1 (Mac). #print """""" print """ My Test Page """ #FRAMESET has no border attribute, however it helps IE and Opera. print """ <body>This requires frames to use</body> This is what I would type to first test the CGI module. And as expected I get the xml code back, as you see below. sh-2.05b# python index.py Content-Type: text/html; charset="iso-8859-1" My Test Page <body>This requires frames to use</body> This is the output of the apache "error_log" file I get. error] (2)No such file or directory: exec of /Library/WebServer/CGI-Executables/index.py failed [Mon May 31 22:05:09 2004] [error] [client 192.168.1.250] Premature end of script headers: /Library/WebServer/CGI-Executables/index.py ------- NOTE: I Set the chmod flags to 755 - made sure execute privelages are set. Running as "root". Question: What does a "Premature end of script headers" mean. This message is very confusing. What would normally cause this? Why would I get: "No such file or directory" exec of .... failed? I DID set the "x" bits on the file. What ELSE could I be doing wrong? John From miki.tebeka at zoran.com Thu Jun 17 06:20:52 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 17 Jun 2004 12:20:52 +0200 Subject: OT: Chat server Message-ID: <20040617102051.GE2048@zoran.com> Hello All, I'm looking for a chat (IRC) server. Nothing fancy. It has to be free, standalone and with logging. Python based will be ideal. Any recommendations? Thanks. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From insert at spam.here Fri Jun 4 06:11:45 2004 From: insert at spam.here (Doug Holton) Date: Fri, 04 Jun 2004 05:11:45 -0500 Subject: Python reference In-Reply-To: References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: <47ednezqs95A113dRVn-gQ@comcast.com> Here's an easy wrapper for os.spawn that lessens the confusion: import os def run (program, *args): "Run external program, wait til it quits, and return the exit code" spawn = os.spawnvp #not available on windows though if os.name == "nt": spawn = os.spawnv return spawn(os.P_WAIT, program, (program,) + args) def start (program, *args): "Start an external program and return immediately, returning proc id" spawn = os.spawnvp #not available on windows though if os.name == "nt": spawn = os.spawnv return spawn(os.P_NOWAIT, program, (program,) + args) #example: errcode = run('cp','index.html','index2.html') if errcode == 0: #no error pid = start('cp','index2.html','index3.html') else: print "error finding or copying the index.html file" From diabolik at uku.co.uk Wed Jun 2 04:09:36 2004 From: diabolik at uku.co.uk (dean) Date: 2 Jun 2004 01:09:36 -0700 Subject: Converting Hex to decimal References: Message-ID: <70efe2ee.0406020009.1e1000d6@posting.google.com> Hello Group Thanks for your responses so far. I have not been clear it seems so here it goes: The file is binary. Using the standard hpux or linux hexdump (xxd or xd) this is the output that is obtained: 0000000: 5c1a 0100 0100 ff35 0399 7272 9903 0002 \......5..rr.... 0000010: 010e 0300 050a 0214 ffff ffff 5cd4 2e01 ............\... 0000020: fbb9 5900 b400 0000 0020 2000 b502 5423 ..Y...... ...T# 0000030: 3a71 2e11 00ff ffff ffff ffff ffff ffff :q.............. 0000040: ffff ffff ff00 ff07 0209 3519 4fff ffff ..........5.O... 0000050: ffff ffff ffff ffff ffff ffff ffff ffff ................ 0000060: ffff ffff ffff ffff ffff ffff ffff ffff ................ 0000070: ffff ffff ffff ffff ffff ffff ffff ffff ................ 0000080: ffff ffff ffff ff00 5435 3617 040a d207 ........T56..... 0000090: 3e05 3717 040a d207 0000 0000 2c01 6000 >.7.........,.`. 00000a0: 0141 01a8 0005 030b 0300 00ff ffff ffff .A.............. 00000b0: ffff ffff ffff ffff ffff ff00 0000 0000 ................ 00000c0: 0300 0000 5435 3617 040a d207 0b00 0000 ....T56......... 00000d0: 0000 0000 fcb9 5900 b400 0000 0020 2000 ......Y...... . 00000e0: b602 5423 3b71 2e11 00ff ffff ffff ffff ..T#;q.......... 00000f0: ffff ffff ffff ffff ff00 2094 3965 0702 .......... .9e.. 0000100: 0935 194f ffff ffff ffff ff07 0209 3519 .5.O..........5. 0000110: 4fff ffff ffff ffff ffff ffff ffff ffff O............... 0000120: ffff ffff ffff ffff ffff ffff ffff ffff ................ 0000130: ffff ffff ffff ffff ffff ff00 1536 3617 .............66. Each hex character is 8 bits. I would like to convert one byte at the time and pipe the converted data into a new file. Thanx in advance Regards Dean From grante at visi.com Thu Jun 3 16:41:05 2004 From: grante at visi.com (Grant Edwards) Date: 03 Jun 2004 20:41:05 GMT Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> Message-ID: On 2004-06-03, Reiner Block wrote: > ----------------------------------------------------------------------- > import os > os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') > ----------------------------------------------------------------------- > There is no further explaination why there are suddenly two times 'cp'! The > first says the first parameter is the mode like P_WAIT or P_NOWAITE. That's > clear. But the second should be the program to start and the third...? :-( > > It is not clear why the 2nd and 3rd parameter are the same. The 2nd parameter is the filename of the program to be executed. The 3rd parameter is the value of the first argument to be passed to that program. It is traditional on Unix systems to pass the program's name to it as its first parameter. Some programs will behave differently if different names are passed as that first parameter -- allowing a single executable file to take the place of several (usually slightly) different programs by simply changing its name. -- Grant Edwards grante Yow! RELATIVES!! at visi.com From deetsNOSPAM at web.de Tue Jun 8 16:57:39 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 08 Jun 2004 22:57:39 +0200 Subject: [OT] Pythonesque References: Message-ID: Jarek Zgoda wrote: > Yesterday evening new pythonesque emerged: Zofia Irena Zgoda (56cm, > 3.4kg). It was hard to get this new life here, but finally she is with > us. She is the cause of my absence at EuroPython this year. > > Wish me good luck in my new role of happiest man in the world. ;) > > Anyone who understands Polish can read (nearly instant) news at > http://zgoda.jogger.pl/. > congrats - its always good to hear that the army of pythoneers is joined by promising members at the earliest age possible :) -- Regards, Diez B. Roggisch From manatlan at online.fr Fri Jun 25 03:10:37 2004 From: manatlan at online.fr (marco) Date: Fri, 25 Jun 2004 09:10:37 +0200 Subject: a small-gui for python/win32 ? In-Reply-To: References: <40db01fb$0$17144$626a14ce@news.free.fr> Message-ID: <40dbcfee$0$29370$626a14ce@news.free.fr> Chris S. a ?crit : > marco wrote: > >> this week, i've seen a little GUI for python/win32 .. >> a little library which can use simple dialog (openfile, opendir, >> messagebox, progressbar ... and that's all) ... >> it worked only on win32 platform >> >> AND i've not bookmarked the url ;-( (shame on me) >> >> i've seen that in "daily python url" perhaps ??! >> i cant find it again ;-( >> >> perhaps someone could help me ? >> (don't tell me about tk, wx, qt, gtk ... ;-) > > > Doesn't Python come bundled with Tkinter? Isn't Tkinter cross-platform > compatible? What's wrong with Tk? > > For the record, Tk and Wx work on windows. Tk is about as simple a gui > library as you can get. i know, i know ... i am a wx addict (i hate the render of tk) i'm not looking for full gui cross platform just for a simple api wich call the real dialogbox of windows (selectfolder, selectFile(s), input a text, messagebox ...) From dkgunter at lbl.gov Wed Jun 30 23:53:54 2004 From: dkgunter at lbl.gov (Dan Gunter) Date: Wed, 30 Jun 2004 20:53:54 -0700 Subject: reflection In-Reply-To: <77rbr1-175.ln1@gatekeeper.kadnet.dk> References: <77rbr1-175.ln1@gatekeeper.kadnet.dk> Message-ID: <40E38AD2.6060803@lbl.gov> carlo v. dango wrote: > hello there > > I have searched the documentation in vein... :( Well, then, I guess it's time to try an artery :-) When I typed "python introspection" into Google, my first result was: http://www-106.ibm.com/developerworks/linux/library/l-pyint.html which seems to be a nice introduction to the topic. -Dan > > I would like to be able to > > a) see all classes in the runing system > > b) inspect all classse that can be found in pythonpath (to look for > classes not yet made instances of / loaded) > > > how to perform these simple tasks? > > sincerely > Carlo From eric at zomething.com Fri Jun 18 21:33:40 2004 From: eric at zomething.com (Eric @ Zomething) Date: Fri, 18 Jun 2004 17:33:40 -0800 Subject: Robot Message-ID: <20040618173340.1539319890.eric@zomething.com> export at hope.cz wrote: > Does anyone know about a script that can walk through webpages and > extract an information from these web sites according to given > keyword(s)? > Thanks for reply Python is a high level language well suited for this task, however the task is not terribly simply and likely you will have to write your own program to do what you want. Several aspects of this are (1) spidering - accumulating the URL's you want to visit as you load pages (2) web page fetching - which is easy: import urllib captured_page = urllib.urlopen("http://somewebpage.com").read() and (3) figuring how to identify what you want to extract from each page. This can be non-trivial. The web is not so semantic after all. Yet, at least. Good luck and feel free to share your solutions. Eric Pederson http://www.songzilla.blogspot.com :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: e-mail me at: do at something.com except, increment the "d" and "o" by one letter and spell something with a "z" :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: From mark at prothon.org Fri Jun 18 15:34:32 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 18 Jun 2004 12:34:32 -0700 Subject: mutable default parameter problem [Prothon] References: <8ef9bea6.0406180809.10053ba6@posting.google.com> Message-ID: Hung Jung Lu wrote: > In code refactoring, the equivalent is to replace conditional > statements by polymorphism. In terms of codeblocks, what I mean is > dynamic hook-on and hook-off of codeblocks. If the underlying language > is powerful enough, one should be able to achieve runtime > restructuring of code, without performance impact for subsequent > calls. What about this Prothon code: def f(): if 'static' not in f.attrs_: f.static = 0 f.static += 1 tmp = f.static def outer.f(): f.static += 1 return f.static f.static = tmp return f.static print f() # 1 print f() # 2 print f() # 3 I'm sure Python can do this better so please don't barrage me with replies saying so. I'm not going to brag this time :-) From imbosol at aerojockey.invalid Tue Jun 8 03:18:53 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 08 Jun 2004 07:18:53 GMT Subject: how to use __str__ and __repr__? References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9mdFnvcsbU2@uni-berlin.de> <7P6dnaLiT8YikVjdRVn-hQ@powergate.ca> <2il6tmFo4tkpU2@uni-berlin.de> Message-ID: Carl Banks wrote: > > > Jim Newton wrote: >> hmm, even when i change it to calling str() rather than __str__() >> it does not work. >> >> class another: >> pass >> >> print another() # works >> another().str() # does not work >> >> does anyone know why? > > str is a function, not a method. (Ok, it's actually a type object.) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From irmen at -nospam-remove-this-xs4all.nl Sat Jun 5 11:32:35 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 05 Jun 2004 17:32:35 +0200 Subject: Python Speed Question and Opinion In-Reply-To: <10c3l5p7jcp7o24@corp.supernews.com> References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> Message-ID: <40c1e793$0$563$e4fe514c@news.xs4all.nl> Maboroshi wrote: > In my opinion Python is the best language there is and I love it. The > reason for me asking these questions was because I saw a lot of people > trying to compare python to C and I had to find out what the big deal was > and why C would be a faster language - I like to know how things work - I have taken the liberty of taking a few of the comments made in this thread and writing them down here: http://www.razorvine.net/python/PythonSpeed I've added a few other things related to Python's performance, such as a short reference to Psyco. --Irmen de Jong. From mnh at cogitation.org Wed Jun 30 14:33:57 2004 From: mnh at cogitation.org (Mark Hertel) Date: Wed, 30 Jun 2004 18:33:57 +0000 (UTC) Subject: Getting User Display Information References: Message-ID: On Wed, 30 Jun 2004 12:10:45 -0400, Christopher T King wrote: >> I was wondering if it was possible to get the screen display size and >> other associated properties somehow either using python modules or if >> possible using Tk methods. > > Using Tkinter: > > from Tkinter import Tk > w=Tk() > print w.winfo_screenwidth(),w.winfo_screenheight() > w.destroy() > > There's a plethora of other information available as methods of the Tk > object (actually any Tkinter widget), including color depth, cursor > position, window manager type, etc. > > Note that this is actually creating a Tk window; calling its destroy() > method right after you've finished with it prevents it from appearing on > screen. Don't do this if you actually are creating a GUI with Tk. Is there anyway to get the size of the available screen. I have things like the status bar across the bottom of the screen (redhat) and I would like to size my application so that it doesn't overlap it. --Mark From greg at cosc.canterbury.ac.nz Mon Jun 14 22:00:11 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 15 Jun 2004 14:00:11 +1200 Subject: PyGUI broken link fixed (Re: ANN: PyGUI 1.3 released) In-Reply-To: References: Message-ID: <2j73heFu2t43U1@uni-berlin.de> If anyone was looking for the sample code (blobedit.py), I've fixed the broken link in the web docs that was suppposed to be pointing to it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From eldiener at earthlink.net Sun Jun 13 22:28:54 2004 From: eldiener at earthlink.net (Edward Diener) Date: Mon, 14 Jun 2004 02:28:54 GMT Subject: Generic database dictionary access References: <40cd04c7$1_3@omega.dimensional.com> Message-ID: Michael Fuhr wrote: > "Edward Diener" writes: > >> Has there been any movement in the 5 year time span since the 2.0 API >> was published to add richer generic functionality for relational >> databases as regards data dictionary access ? I fully realize that >> each major RDBMS has its own methods for programatically querying >> its data dictionary, and I suspect that there is no common SQL >> specification for doing so, but I would think that richer >> functionality along these lines might be welcome to Python database >> programmers other than myself. > > SQL defines INFORMATION_SCHEMA as a standard way to query metadata, > although not all databases implement it. Google for more info. Yes, I see it but it seems as if even some of the large databases don't support it ( unless I am mistaken, Oracle for instance ). Nonetheless it would be great if the Python database API were able to use it to create richer data dictionary information than what it provides. In particular constraints and unque key/foreign key links in tables if this could be discovered generically through the INFORMATION_SCHEMA standard methods. From me at privacy.net Tue Jun 1 05:57:28 2004 From: me at privacy.net (Duncan Booth) Date: 1 Jun 2004 09:57:28 GMT Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> <0dqkb09bc54jlo8m9aqcosei5p7olccvec@4ax.com> Message-ID: David MacQuigg wrote in news:0dqkb09bc54jlo8m9aqcosei5p7olccvec at 4ax.com: > I may be missing your intent. If so, maybe you could show a more > complete example. Ok, let me try to clarify again. I am suggesting that we write factory methods using classmethod to give code like: Rectangle.fromCenterAndSize(10, 10, 3, 4) Ellipse.fromCenterAndSize(10, 10, 3, 4) OffsetRectangle.fromCenterAndSize(10, 10, 3, 4) TextLabel.fromCenterAndSize(10, 10, 3, 4) and as I understand it, you would prefer to use static methods and write: Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) Shape.fromCenterAndSize(Ellipse, 10, 10, 3, 4) Shape.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) Shape.fromCenterAndSize(TextLabel, 10, 10, 3, 4) In the hope that I'm right so far, I'll try to list some of the ways that I believe my code is a better way to implement this sort of scheme. First off, my classes all implement an interface which I'll call 'shape factory'. Interfaces in Python aren't declared explicitly, but that doesn't stop me claiming that I have one. Any class which implements shape factory can be instanciated in a consistent manner. Secondly, the implementation is hidden. I might tell you here that Rectangle and Ellipse have a common base class, OffsetRectangle subclasses Rectangle, and TextLabel doesn't share the same base class as the others (perhaps it doesn't have any other methods in common), but this would just be irrelevant information and any other relationship between the classes would work just so long as each continued to implement the shape factory interface. I'm sure we both know the difference between a base class and an interface, but, just to check we are communicating, I'm going to spell out what I think is the important distinction: An interface lets multiple classes share functionality or services that they offer. A base class lets multiple classes share common implementations of code. A base class need not supply any public interface; indeed a base class might expose a public interface which derived classes do not expose. I think this is important, as you rarely want to write code where the common implementation is the important thing; usually its the common set of services that are important. Even in languages such as C++ and Java it is better to write code that accepts objects which implement an interface rather than code which requires objects to have a specific base class. The final point I want to make about my code, and I admit it is less important, is that the factory methods can be passed around just like any other method. I could have a dict mapping object name to factory method and create any of the objects in my system simply by calling the saved method. Back to your way of doing things: Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) Shape.fromCenterAndSize(Ellipse, 10, 10, 3, 4) Shape.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) Shape.fromCenterAndSize(TextLabel, 10, 10, 3, 4) I may have some problems communicating my intent here. How do I know which classes it is valid to pass to Shape.fromCenterAndSize? My classes no longer have any common interface. Oops. Did I mention that TextLabel is an unrelated class and doesn't have the same methods as Shape? Shape.fromCenterAndSize calls the resize method, but my TextLabel class has a setFont method instead, so that code is going to throw an AttributeError. Fortunately, that is easily fixed: Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) Shape.fromCenterAndSize(Ellipse, 10, 10, 3, 4) Shape.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) TextLabel.fromCenterAndSize(TextLabel, 10, 10, 3, 4) Sadly, it looks as though the implementation, which I presume we would like to hide, is beginning to be significant. The code may now execute with throwing an exception, but I just spotted a worse problem. The OffsetRectangle object has its own implementation of fromCenterAndSize, so while you can construct it through the Shape class you get the wrong values stored. You can fix that in the same way as before, but there is still a deadly trap for the unwary: anyone who accidentally calls the factory method in Shape will silently get the wrong results: Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) Shape.fromCenterAndSize(Ellipse, 10, 10, 3, 4) OffsetRectangle.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) TextLabel.fromCenterAndSize(TextLabel, 10, 10, 3, 4) Now my problem is the inconsistency of the code, the underlying implementation has become all important. Why should I be calling the method on Shape for two of the classes, and on the classes themselves for the other two? How am I going to remember which is which? Fortunately there is nothing stopping us from using the derived class for the call: Rectangle.fromCenterAndSize(Rectangle, 10, 10, 3, 4) Ellipse.fromCenterAndSize(Ellipse, 10, 10, 3, 4) OffsetRectangle.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) TextLabel.fromCenterAndSize(TextLabel, 10, 10, 3, 4) Now we have a consistent interface again. The only problem with this is that we have duplication in the call. That is easily fixed though by switching to class methods and you get back to my code. One more point. You said in an earlier post: > I would change the classmethods to staticmethods, however, and avoid > the need to teach classmethods. If you are going to teach your students how to create objects in Python you will need to explain the __new__ method. __new__ is automatically a class method, so there is no way you can avoid teaching class methods. You can however avoid teaching static methods. From db3l at fitlinxx.com Fri Jun 11 17:34:19 2004 From: db3l at fitlinxx.com (David Bolen) Date: 11 Jun 2004 17:34:19 -0400 Subject: How do you write test suites for GUI components? References: <86isdynp6c.fsf@sysfault.org> Message-ID: j_mckitrick at bigfoot.com (j_mckitrick) writes: > I guess mine will be much simpler, then. :-) > > I have pygtk guis tha are the interface to my application. If test > suites are so important, how can they be applied to modules that just > run dialogs or windows? When testing a GUI, IMHO what you are testing is that actions taken against that GUI turn into appropriate operations on your underlying application data model, as well as that the appropriate portion of your data model is going to be reflected in the presentation of the GUI. So, do those dialogs or windows interact with your business logic? That is, when a user manipulates controls on those dialogs or windows, what sort of actions are taken on the data managed by the application. That's what you want to test is occurring properly. Or, do those dialogs or windows display data that is obtained from your business logic? That's what you want to test will be displayed properly. By separating out the act of translating actions on a GUI control into business logic actions, versus the management of any data that underlies a GUI control (the text for a static text box, or the label on a button), versus the drawing of the control itself and interaction with external events like mouse presses, you can go a long way towards testing a lot of how the GUI operates. Combine that with tests to ensure that your business layer operates properly (sans GUI), and you've got some reasonable coverage. -- David From bvande at po-box.mcgill.ca Wed Jun 9 19:07:25 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 09 Jun 2004 19:07:25 -0400 Subject: Is a 'bugfix' version of jed's pymode.sl editor config file available anywhere? In-Reply-To: References: Message-ID: <40C7982D.5090901@po-box.mcgill.ca> Kenneth McDonald said unto the world upon 08/06/2004 20:48: > I just started using the jed editor, and am really happy with it-- > like emacs, but much, much friendlier. However, my python mode > file (the one that came with the 0.99.16 precompiled version of > jed that I got) isn't handling string highlighting properly-- > it doesn't understand that '''This 'string' isn't really a string''' > is a single triple quoted string, and instead treats the interior > ' marks as string delimiters as well as (correctly) treating the > ''' as single string delimiters. I took a quick look in pymode.sl > and it didn't look hard to fix, for someone familiar with slang's > DFA implmentation and its RE syntax--which I'm not :-( ). So > I thought I would try here first. > > Thanks for any suggestions, > Ken Hi Ken, I'm pretty much a python newbie and I don't know jed. But I've noticed that every editor with a Python mode that I have tried (other than IDLE and possibly LEO) has this problem. One of the links on has a discussion of various workarounds that you might find of use. It is, as the address implies, focused on emacs and Python, but I have found the advice generally applicable to the Python modes of other editors. Hope that helps, Brian vdB From nospam at here.com Sun Jun 6 10:24:50 2004 From: nospam at here.com (Richard Townsend) Date: Sun, 6 Jun 2004 15:24:50 +0100 Subject: Embedded window in wxPython app Message-ID: I've been experimenting with passing a window handle from a wxPython app to a Tkinter app. The Tkinter app should embed a Toplevel window containing a Canvas widget in the wxPython app's Frame (see example below). Both apps run, but the Tkinter app's output doesn't appear. Can anyone see why this isn't working? Using wxPython-2.5.1/Python 2.3.3/Win98 and Win2000. regards Richard ---------------------------- #!/usr/bin/env python # generated by wxGlade 0.3.3 on Thu Jun 03 14:36:32 2004 import wx import os class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("frame_1") # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout self.Layout() # end wxGlade def StartSlave(self): # Get the window id window_id = str(self.GetHandle()) print 'In wx_app window_id =', window_id script = 'tk_slave.py' cmd = r"C:\python23\python.exe" args = [script, script, window_id] os.spawnv(os.P_NOWAIT, cmd, args) #self.Refresh() # end of class MyFrame class MyApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") self.SetTopWindow(frame_1) frame_1.Show(1) frame_1.StartSlave() return 1 # end of class MyApp if __name__ == "__main__": app = MyApp(0) app.MainLoop() ---------------------------- #!/usr/bin/env python # Module: tk_slave.py import sys import Tkinter class EmbeddedTk: """Create Embedded Tk app inside a wxPython app """ def __init__(self, window_id): print 'Received window id =', window_id self.window_id = window_id self.root = Tkinter.Tk() self.root.withdraw() toplevel = Tkinter.Toplevel(use=self.window_id) #toplevel = Tkinter.Toplevel(self.root) self.c = Tkinter.Canvas(toplevel, width=250, height=250, bg='white', bd=0) self.c.pack() self.c.create_rectangle(20,20,230,230) self.root.mainloop() if __name__ == '__main__': if len(sys.argv) != 2: sys.exit('Usage: python tk_slave.py window_id\n') window_id = sys.argv[1] EmbeddedTk(window_id) From CousinStanley at HotMail.Com Tue Jun 29 13:01:17 2004 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Tue, 29 Jun 2004 10:01:17 -0700 Subject: Simple Practice Programs References: <2004062816162375249%brianmartin@gmailcom> <8MKdnWKtOvt9c33dRVn-hQ@powergate.ca> Message-ID: <1c6vkmf768aj9.1pa80n9xm4jnz$.dlg@40tude.net> On Tue, 29 Jun 2004 00:23:59 -0400, Peter Hansen wrote: > .... > (*) More specifically, it was a Star Trek game written in > BASIC on a CBM 8032, with little asterisks and hash symbols > that fired little slashes and hyphens at each other across a > 10x10 sector of periods.... great fun at the time. An MBasic Star Trek version along with MBasic that looks very similar to one I played occasionally under IBM VM/CMS back in the middle 1970s .... http://www.issue.org.uk/ .... startrek.zip I found this only yesterday when someone in another NG mentioned it and thought it might make a good candidate for conversion to Python .... -- Cousin Stanley Human Being Phoenix, Arizona From mrchameleon at hotmail.com Wed Jun 2 14:15:06 2004 From: mrchameleon at hotmail.com (Chris Reay) Date: 2 Jun 2004 11:15:06 -0700 Subject: strange socket behaviour References: <82jrb0t5ss1dtf9qki44qphd13t0vpnl02@4ax.com> Message-ID: <7652139e.0406021015.207c7632@posting.google.com> fishboy wrote in message news:<82jrb0t5ss1dtf9qki44qphd13t0vpnl02 at 4ax.com>... > On Wed, 2 Jun 2004 10:37:21 +0800, "Joe Wong" > wrote: > snip > > No, your code is ok. It's just that closing the local end of the > socket is undefined in select(). Which is why Windows does one thing > and Linux the other. > > Closing the remote end causes the socket to show up as readable with > zero data. > Precisely. I've been through this myself. My solution on the FreeBSD server side is (pardon the bad pseudocode): rd, wr, err = select(myClientSocksList, [], myClientSocksList, myTimeOut) for eachSock in rd: try: dataIn = eachSock.recv(MaxBufSz) except socket.error: # Server closes session. self.closeSession(eachSock, "Socket error - recv") else: if len(dataIn) > 0: # Process, process. else: # Server closes session. self.closeSession(eachSock, "Recvd 0 bytes") # Check the err list etc, etc. From axel at axel.truedestiny.net Tue Jun 22 08:59:28 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Tue, 22 Jun 2004 12:59:28 GMT Subject: pysnmp/shell Message-ID: Hi All, Python is so great. I've been creating a small set of objects to get some stats from our adsl routers. So far it works great and fast. However, in the shell script I created over a year ago to gather stats I do: mib_lp=`$snmpwalk $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntIf Index 2>/dev/null | $grep " = $lan_iface" | $head -1 | $sed -E 's/^ip.ipAddrTabl e.ipAddrEntry.ipAdEntIfIndex.(.+) = .*/\1/g'` if [ "$mib_lp" != "" ]; then lan_ip=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntA ddr.$mib_lp 2>/dev/null | $sed -E 's/.+IpAddress: //g'` lan_netmask=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipA dEntNetMask.$mib_lp 2>/dev/null| $sed -E 's/.+IpAddress: //g'` else lan_ip="ERROR" lan_netmask="ERROR" fi To retrieve the lan settings for the router. I don't know the (lan)ip address of it but do know the interface number, that's why I check for that and then use a part of the mib to get to the netmask. This seems to be quite difficult with pysnmp (took me half an hour to write Router.SNMPQuery(self, noid) ;-)), so before I get started I wanted to ask if somebody might have better idea for this. Thanks! Kind regards, Axel Scheepers From DennisR at dair.com Wed Jun 30 19:56:06 2004 From: DennisR at dair.com (Dennis Reinhardt) Date: Wed, 30 Jun 2004 23:56:06 GMT Subject: distributing executable embedding Python References: Message-ID: See http://www.spamai.com/hello.php for a discussion and example of how to build this on Windows. -- Dennis Reinhardt DennisR at dair.com http://www.spamai.com?ng_py From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jun 9 09:33:57 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 09 Jun 2004 15:33:57 +0200 Subject: hotshot profiler: how to distinguish between cpu time and wait (idle) time? Message-ID: <40c711c5$0$37789$e4fe514c@news.xs4all.nl> Hi, when using the hotshot profiler, I can see no difference in the measurement of a function that is busy eating CPU cycles, and a function that is blocking/waiting on IO (or sleeping)... For instance I have this output: 3 function calls in 26.931 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 13.465 13.465 13.465 13.465 testprof.py:5(cpu) 1 13.464 13.464 13.464 13.464 testprof.py:9(sleep) 1 0.002 0.002 26.931 26.931 testprof.py:12(main) 0 0.000 0.000 profile:0(profiler) My test program (see below) consists of two functions called sequentially: a cpu() function eating 13+ seconds of CPU cycles when calculating sha-hashes, and a sleep() function that only has time.sleep(13) in it. What would be really useful, is that the profiler would show that sleep() is actually not doing *anything*, while cpu() is doing all the hard work. I.E.: measure CPU-time, not user-time. How do I do this? Is this possible? (I'm using Python 2.3.4) Thanks!! --Irmen de Jong. --------------- test program ------------------ import hotshot, hotshot.stats import time import sha def cpu(): for i in range(1000000): a=sha.sha("abcdefghijklmnopqrstuvwxyz").hexdigest() def sleep(): time.sleep(13) def main(): print "cpu..." cpu() print "sleep..." sleep() print "done" prof = hotshot.Profile("/tmp/test.prof") result = prof.runcall(main) prof.close() print "PROFILE DONE, result=",result,type(result) stats = hotshot.stats.load("/tmp/test.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) From Holger.Joukl at LBBW.de Mon Jun 14 03:46:29 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Mon, 14 Jun 2004 09:46:29 +0200 Subject: Bug in strptime in Python 2.3.3 Message-ID: >I still think there is something missing in the way %w is handled >(note: it is lower case for weekday) > >I'd like to know what is missing in _strptime.py for %w handling >between pre-python 2.3 and post 2.3? Andy, If you want to get closer to pre-python 2.3 behaviour you could modify the patch code I posted. E.g. instead of this 527 if weeknr_set: # correct julian to be the given weekday (which defaults to 0) julian += weekday - datetime_result.weekday() if julian < 1: # ignore negative values, stay in the current year julian = 1 you might want to do s.th. like 527 if weeknr_set: # correct julian to be the given weekday (which defaults to 0) julian += weekday - datetime_result.weekday() + (weekday != 6) * 7 ##if julian < 1: # ignore negative values, stay in the current year ## julian = 1 This is still different with regard to %U values of 0 (days in the previous year), but it seems closer to previous python versions. Then again this might differ depending on the C libraries on the machine (?). You might also want to add a weeknr_set = False in the "elif group_key == 'j'"-section to have a given julian day override any week number arguments. Regards Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From indigo at bitglue.com Mon Jun 7 08:03:19 2004 From: indigo at bitglue.com (Phil Frost) Date: Mon, 7 Jun 2004 08:03:19 -0400 Subject: Balanced tree type coming in next Python? In-Reply-To: References: Message-ID: <20040607120319.GA28859@unununium.org> I'm not aware of any such feature to be added, but an AVL tree module is available now: http://www.nightmare.com/squirl/python-ext/avl/ On Mon, Jun 07, 2004 at 04:45:13AM +0000, Kenneth McDonald wrote: > I can't see anything about this in the notes on the upcoming > 2.4 on python.org, but for some reason I thought I remembered > seeing that a balanced tree sequence type would be included > in Python in the near future. Is this correct? > > Thanks, > Ken From davidf at sjsoft.com Tue Jun 1 04:55:58 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Jun 2004 10:55:58 +0200 Subject: mod python confusion In-Reply-To: References: Message-ID: Ben Sizer wrote: > David Fraser wrote: > >>Kylotan wrote: >> >>>I read somewhere today that >>>mod_python made Python as simple to use for web apps as PHP etc, > > but if > >>>this is any indication of the amount of code you need to simply > > redirect > >>>execution to separate places based on the URI, then I'd have to > > disagree > >>>with that! >>> >> >>Actually redirecting execution to separate places based on the URI is > > >>fairly easy in mod_python, I suspect you may want to use something > > like > >>publisher > > > mod_python.publisher is poorly documented (the 'explanation' in section > 6.1.2.1 of the manual is perhaps the most confusing attempt to explain > something in clear language that I've ever seen) and seems pretty > idiosyncratic, expecting you to return the page rather than write it > out piece by piece. In the absence of decent documentation I've tried > to experiment with it but couldn't find a consistent way of getting it > to call my pages, and often ended up with 404 errors in situations > where the tutorial led me to believe it would call a function. Is there > a more clear guide on how to use this? Not sure, I don't use it myself, but if you're wanting more help you could try the mod_python users list. may have been a bad suggestion though. > By the way, thanks for the 3.1.3 file. That seems to have installed > fine now. > Good, glad to hear it :-) David From simonroses at granisla.com Tue Jun 8 09:59:52 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Tue, 8 Jun 2004 15:59:52 +0200 Subject: any simple and multiplatform database? References: <001901c44d59$a27bffc0$0200a8c0@lucifer> <16581.49846.271286.610876@montanaro.dyndns.org> Message-ID: <00a901c44d60$dfcbc890$0200a8c0@lucifer> Thx I have already looked at sqllite, but I think metakit (http://www.equi4.com/metakit/python.html) is better for me, at least. Any experience with metakit ? Sincerely, SRF ----- Original Message ----- From: "Skip Montanaro" To: "Simon Roses Femerling" Cc: Sent: Tuesday, June 08, 2004 3:44 PM Subject: Re: any simple and multiplatform database? > > Simon> Is there any simple and multiplatform database for python ? > > I believe a fair number of people are fond of SQLite: > > http://www.hwaci.com/sw/sqlite/ > > Skip From r_m_jones_email at yahoo.com Tue Jun 15 13:32:14 2004 From: r_m_jones_email at yahoo.com (RMJ) Date: Tue, 15 Jun 2004 10:32:14 -0700 Subject: Enthought Python + Cygwin Message-ID: After installing Enthought's python and typing 'python' from within cygwin the program hangs with no output. I do not remember this being the case with earlier versions of Enthought python. Is this version not compatible with cygwin? Or, is there some configuration file that needs changing? It does run successfully with 'python somecode.py' -but without printing out intermediate results. Thanks! -Roger Jones From dave.opstad at agfamonotype.com Wed Jun 2 13:31:33 2004 From: dave.opstad at agfamonotype.com (Dave Opstad) Date: Wed, 02 Jun 2004 10:31:33 -0700 Subject: Iteration weirdness Message-ID: I'm running into a strange behavior under Python 2.3.3: ------------------------------------------ >>> d = {-1: 'cv', -2: 'se', -3: 'se'} >>> d {-1: 'cv', -2: 'se', -3: 'se'} >>> len(d) 3 >>> [d[-1], d[-2], d[-3]] ['cv', 'se', 'se'] >>> [d[-1-i] for i in len(d)] Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence ------------------------------------------ Can someone enlighten me as to why the list comprehension gives an error, but the simple list construction case works fine? Thanks for any help! Dave Opstad From alloydflanagan at comcast.net Mon Jun 7 17:19:18 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 7 Jun 2004 14:19:18 -0700 Subject: Python Wiki & wiki Hosting? References: <20040605115256.1749992717.eric@zomething.com> Message-ID: "Eric S. Johansson" wrote in message news:... > Eric @ Zomething wrote: > >>> When I was CTO of a small startup, we used twiki to hold all of the development documentation. >>It worked reasonably well until the pages became quite large. Eventually, we all noticed that we >>didn't update our pages as we should because it was too much like work. Editing a markup language >> inside of a browser text area was lame. While I like your suggestion for better editing, I've got to point out that I think your real problem was that the pages "became quite large". It would be much more "wiki-correct" to make a larger number of small pages, with many links between them. Easier to use _and_ maintain. From diabolik at uku.co.uk Mon Jun 14 06:52:41 2004 From: diabolik at uku.co.uk (dean) Date: 14 Jun 2004 03:52:41 -0700 Subject: Unix fold command in python Message-ID: <70efe2ee.0406140252.2c7b0989@posting.google.com> Hello Group: Hopefully someone can answer my question. I have a unix shell command that I would like to emulate in python. The command is FOLD. I am scanning a file that contains a stream of data with a record size of 242 bytes but no record delimiters. There are multiple fields in each record that can be mapped according to their position: example field1 byte 0-4 field2 byte 5-8 ... ... ... fieldn byte 238-242 How do I make python read a record in and report the contents of a particular field (and may be carry out an operations with that field). Much appreciated regards dean From peter at engcorp.com Wed Jun 9 22:55:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 22:55:08 -0400 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Michael P. Soulier wrote: I'll limit my response to point out that this code: > myfile = open("myfilepath", "w") > myfile.write(reallybigbuffer) > myfile.close() ... immediately raises a warning flag in the mind of an experienced Python programmer. This code, on the other hand: > try: > myfile = open("myfilepath", "w") > myfile.write(reallybigbuffer) > finally: > myfile.close() ... "feels" just right. This is how you do it when you want to be sure the file is closed, regardless of other considerations like garbage collection, etc. It is simple, clean, and most of all, very explicit. -Peter From dkturner at telkomsa.net Mon Jun 21 04:08:54 2004 From: dkturner at telkomsa.net (David Turner) Date: 21 Jun 2004 01:08:54 -0700 Subject: does python have useless destructors? References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > >> Not really. Problem is that there's nothing to prevent people from > >> passing File.fh outside the loop -- and that's standard Python coding > >> technique! For that matter, there's nothing preventing a File() > >> instance from being passed around. The fact that you've created an > >> idiom that you want to behave like a similar C idiom has nothing to do > >> with the way Python actually works. > > > >You can do exactly the same thing in the C++ version, and regularly > >do. What's your point? > > And how does your destructor work when you do that? Just fine, thank you. It does exactly what I expect it to - runs when the last reference disappears. What did you expect? Regards David Turner From nicolas at lehuen.com Thu Jun 3 03:42:21 2004 From: nicolas at lehuen.com (Nicolas Lehuen) Date: 3 Jun 2004 00:42:21 -0700 Subject: jython 2 cpython bridge References: <8dssc.179150$f_5.163363@lakeread01> <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> Message-ID: Steve Menard wrote in message news:... > Irmen de Jong wrote: > > Randall Smith wrote: > > > >> I would like to use a type 4 JDBC driver in my Python program. I > >> believe I can use in with Jython. Do you know of some way to > >> communicate between the Jython and Python processes so that the > >> CPython program can use the Jython JDBC database connection? > > > > > > Create some form of IPC between the two, for instance using xmlrpc. > > > > --Irmen > > > > PS: I would have suggested to use Pyro, but: > > - Java/Jython doesn't have the select() system call that Pyro needs for > > a server, > > - There are bugs in Jython that make it crash when compiling Pyro's > > source. > > > Alternately, you can look at JPype ( http://jpype.sourceforge.net ). > > It is still a very early release, but I would welcome any feeback. And > version 0.1 should allow you to use JDBC without problem. > > It currently only works on Windows, but if there is interest, I could > make a linux release pretty quickly. > > That's awesome ! This is still a little bit rough on the edges, but it already works well enough to have an idea of what it could bring to Python. This is what I mean by 'rough on the edge' : launching a Python program using JPype from a .py file is OK, but using the prompt is weird : >>> from jpype import * >>> startJVM(r"C:\j2sdk1.4.2_03\jre\bin\client\jvm.dll", "-ea") >>> 1+1 File "", line 1 1+1 ^ SyntaxError: invalid syntax >>> help() File "", line 1 help() ^ SyntaxError: invalid syntax Anyway, this is extremely promising. Soon, we'll be able to seamlessly use Java object thanks to JPype, as we do with COM objects using win32all or ctypes. Python is THE real integration/composition platform ! Thanks for your work, Steve. Regards, Nicolas From michael at foord.net Wed Jun 9 10:16:35 2004 From: michael at foord.net (Fuzzyman) Date: 9 Jun 2004 07:16:35 -0700 Subject: Empty directories with zipfile Message-ID: <8089854e.0406090616.28a4c494@posting.google.com> I have created a set of classes that will profile a file structure and record all changes as a simple markup and single zipfile of all new/modified files. I can't get the zipfile module to archive an empty directory - you need to give it a filename. I know the zip format will support it as winzip will allow it... I looked at the zipfile module source - and I'm sure it's not impenetrable but I don't wish to learn the intricasies of the zip format just yet :-) Anyone got any ideas - beyond extending the markup to record *all* empty directories created as well...... ?? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From light at soton.ac.uk Thu Jun 17 11:07:41 2004 From: light at soton.ac.uk (Mark Light) Date: Thu, 17 Jun 2004 15:07:41 +0000 (UTC) Subject: calculate a colour gradient Message-ID: Hi, I have a tk.scale bar for which I want the background to change from blue to red as I slide along it. The mechanics of this I can do, but the colour gradient I have is very crude - basically the amount of R in RGB just increases whilst the G and B are fixed values. Whilst this is not really a python question does anybody have any suggestions about calculating the RGB values for a smooth colour gradient? Mark. From fishboy at spamspamspam.com Sat Jun 5 23:03:51 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 03:03:51 GMT Subject: problems with mmap under windows nt References: Message-ID: On Tue, 01 Jun 2004 08:34:25 GMT, Manlio Perillo wrote: >Hi. >If I map a file (for WRITING) of 0 lenght, mmap raises an exception: > >WindowsError: [Errno 1006] The volume correspondent to the file has >been altered from the extern. The opened file is no longer valid > > >This is a problem only on windows? > > >Thanks and regards Manlio Perillo Some code would be nice, but I'm feeling psychic tonight. Abracadabra! Two guesses 1. Windows mmap uses length 0 to mean the max size is the same as the current size of the file. Now if the file doesnt already exist, you could see how it might get confused. 2. The fileno needs to point at a file opened for *update* The Great Fishmac has spoken! ><{{{*> From donn at drizzle.com Sun Jun 13 14:04:28 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 13 Jun 2004 18:04:28 -0000 Subject: does python have useless destructors? References: <40CC19D5.6040401@v.loewis.de> Message-ID: <1087149868.12886@yasure> Quoth Carl Banks : ... | These are silly examples, of course, but with more intricate stuff (or | with code by other people who are always less disciplined than you) | this can become a real problem. Face it, people, it's ludicrous to | rely on the garbage collector to finalize stuff for us. `Face it?' We're not the ones talking about preposterous hypothetical cases and hand-waving claims about intricate code written by people who don't know what they're doing. There's boatloads of Python code with constructs like the text = open(file, 'r').read() usage proposed in this thread, and it's truly no problem. If you want to make that into a laborious exercise in defensive programming, that's your problem. It is a fact that there are some issues that have to be understood for more general use of finalization, but that's part of understanding Python's storage model. That model is in the end no simpler or more intuitive than any other language - really worse than most - but it's functional. At the cost of occasionally baffling the newcomer, it lets us write modular code that doesn't impose on the caller to manage objects. I don't need to know whether my function is the sole user of an object and it falls to me to free it when I'm done, because the system takes care of that. I get it, I use it, I forget about it. I realized what a huge architectural difference that makes when I tried to translate a non-trivial program to C. If the choice is either to abandon that advantage for resources other than (small chunks of) memory, or learn how to deal with the tricky corner cases, I'll take the latter. Donn Cave, donn at drizzle.com From bram at nospam.sara.nl Wed Jun 23 10:04:46 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 23 Jun 2004 16:04:46 +0200 Subject: Parsing C Preprocessor files References: <20040623140151.6b8863f2@pistache.sara.nl> Message-ID: <20040623160446.4500287c@pistache.sara.nl> On Wed, 23 Jun 2004 13:58:04 GMT "Paul McGuire" wrote: > (I'm sure pyparsing is listed in Vaults of Parnassus. Why did you think it > would not be applicable?) Because I searched for "parser", "macro", "preprocessor", "cpp", and none of those searches comes up with "pyparsing". I should have searched for "parsing" I guess. Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "Software is math. Math is not patentable." OR "Software is literature. Literature is not patentable." -- slashdot comment ------------------------------------------------------------------------------ From fishboy at SPAMredSPAMpeanutSPAM.com Sat Jun 19 04:39:35 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Sat, 19 Jun 2004 08:39:35 GMT Subject: Help with parsing web page References: Message-ID: <84acz0c508.fsf@redpeanut.com> RiGGa writes: [...] > > How do I get the current position (offset) which I am at in the file? > > I have tried getpos() and variations thereof and keep getting syntax > errors... > > Thanks > > R http://www.python.org/doc/current/lib/bltin-file-objects.html From martin at v.loewis.de Tue Jun 15 00:18:33 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 15 Jun 2004 06:18:33 +0200 Subject: does python have useless destructors? In-Reply-To: <695vp1-aok.ln1@home.rogerbinns.com> References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <40CC1ABC.4010400@v.loewis.de> <40CC9AA2.5080409@v.loewis.de> <695vp1-aok.ln1@home.rogerbinns.com> Message-ID: <40ce789a$0$157$9b622d9e@news.freenet.de> Roger Binns wrote: > Actually I did. Can you please repeat your proposed solution? I must have missed it. All I can find is I would do the same thing that shutdown does. Run the destructors, but don't delete the underlying memory. Set all the fields to None (just as shutdown points modules at None). Finally in a second round actually free the memory. (apparently alternative approach of throwing an exception omitted) This specifies that you want to do the same thing as shutdown, but later you say that you don't want to do the same thing as shutdown does: I meant that during shutdown the modules are forcibly garbage collected, and to a certain extent Python treats their names like weak references This is not true: In Python, modules are not forcibly garbage collected at shutdown. Instead, they are emptied, and explicitly removed from sys.modules. You also specify "Run the destructors, but don't delete the underlying memory". This is, unfortunately, not a complete specification. It does not specify what to do, and when to do it. While it says that we should run destructors, it does not say which objects to run the destructors for. You clearly don't mean: "After each statement, run the destructors on all objects". But I cannot guess what it is that you mean. Regards, Martin From guy at NOSPAM.r-e-d.co.nz Tue Jun 8 07:26:48 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Tue, 08 Jun 2004 23:26:48 +1200 Subject: Error checking using regex ? Message-ID: I have the code below which parses an expression string and creates tokens. Can anyone suggest the best of error checking for things like: Valid variable only obj.attribute -whitespace allowed test( "ff*2/dd.r..ss r") #additional ..ss -invalid variable. test( "ff*$24..55/ddr") #double .. and $ -invalid number test( "ff*2/dd.r.ss r") #variable with double . -invalid variable I can't see an efficient way of doing this so any suggestions appreciated. TIA, Guy code: import re import time re_par = '[\(\)]' re_num = '[0-9]*\.?[0-9]+\E?[0-9]*' re_opr = '[\*\/\+\-\^]' re_cns = 'PI' re_trg = 'SIN|COS|TAN|ASIN|ACOS|ATAN|SGN' re_var = '[a-z_0-9\s]*\.?[a-z_0-9\s]*' recom = re.compile( '(?P%s|%s|%s|%s|%s|%s)' %(re_par,re_num,re_opr,re_cns,re_trg,re_var) ,re.VERBOSE|re.IGNORECASE) def test(str): output = [] try: r = recom.split(str) for rr in r: rr = rr.strip() #test for blank string if rr =='': pass else: output.append(rr) print output except: print 'error of some kind' class stopwatch: def __init__(self): pass def start(self): self.t = time.time() return 'starting timer' def stop(self): rstr = 'stopped at %f seconds' %(time.time() -self.t) self.t = 0 return rstr e = stopwatch() print e.start() test( "9" ) test( "9 + 3 + 6" ) test( "9 + 3 / 11" ) test( "( 9 + 3)" ) test( "(9+3) / 11" ) test( "9 - 12 - 6" ) test( "-9 - (12 - 6)" ) test( "2*3.14159" ) test( "3.1415926535*3.1415926535 / 10" ) test( "PI * PI / 10" ) test( "PI*PI/10" ) test( "PI^2" ) test( "6.02E23 * 8.048" ) test( "sin(PI/2)" ) test( "2^3^2" ) test( "2^9" ) test( "sgn(-2)" ) test( "sgn(0)" ) test( "sgn(0.1)" ) test( "ff*2" ) test( "ff*g g/2" ) test( "ff*2/dd.r r") test( "5*4+300/(5-2)*(6+4)+4" ) test( "((5*4+300)/(5-2))*(6+4)+4" ) test( "(320/3)*10+4" ) #now test error expressions test( "ff*2/dd.r..ss r") #additional ..ss and whitespace -invalid variable test( "ff*$24..55/ddr") #double .. -invalid number test( "ff*2/dd.r.ss r") #variable with double . -invalid variable #test( "ff*((w.w+3)-2") #no closing parentheses-to be tested when evaluating expression print e.stop() From jepler at unpythonic.net Sat Jun 26 16:29:51 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 26 Jun 2004 15:29:51 -0500 Subject: i have a big dictionary...:) In-Reply-To: <1088275878.20902.7.camel@dubb> References: <1088275878.20902.7.camel@dubb> Message-ID: <20040626202951.GB31288@unpythonic.net> If the database doesn't change, over a run, you can store in memory the keys plus file offsets instead of values. My on-disk file is of the format "key:value" separated by newlines. I You may be splitting on whitespace instead. class SimpleDiskDict: def __init__(self, f, cachesize = 100): self.cachesize = cachesize self.cache = {} self.key2offset = {} self.f = open(f, "rb") pos = 0 for line in self.f: key = line.split(":")[0] self.key2offset[key] = pos pos = pos + len(line) def __getitem__(self, item): if self.cache.has_key(item): return self.cache[item] o = self.key2offset[item] self.f.seek(o) value = self.f.readline().split(":", 1)[1].strip() if len(self.cache) > self.cachesize: self.cache.popitem() self.cache[item] = value return value def keys(self): return self.key2offset.keys() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From simonroses at granisla.com Tue Jun 8 09:08:02 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Tue, 8 Jun 2004 15:08:02 +0200 Subject: any simple and multiplatform database? Message-ID: <001901c44d59$a27bffc0$0200a8c0@lucifer> Hello all :) Is there any simple and multiplatform database for python ? It must be a local database (like mdb. files) I was thinking of using mdb (MS Access) but in linux is a bit more hard to use it because you must install several tools (mxODBC, etc..) Sincerely, SRF -------------- next part -------------- An HTML attachment was scrubbed... URL: From BELLEMAIL-SA at exponent.com Thu Jun 10 10:20:36 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 10 Jun 2004 07:20:36 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28D6A@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = noreply at python.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 122 Scanning time = 06/10/2004 07:20:35 Engine/Pattern = 7.000-1004/903 Action taken on message: The attachment MoreInfo.zip contained WORM_BAGLE.GEN-1 virus. ScanMail took the action: Deleted. The attachment AttachedFile.zip contained WORM_BAGLE.GEN-1 virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From tim.one at comcast.net Mon Jun 7 10:12:44 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 7 Jun 2004 10:12:44 -0400 Subject: how to get memory info from python? In-Reply-To: <6ee58e07.0406070442.6e8d32fe@posting.google.com> Message-ID: [Lothar Scholz] > But obmalloc.c has a high performance penalty That's a peculiar claim. All comparative timings I've seen showed it beating the platform malloc, starting with Vladimir Marangozov's original studies (Vladimir originally wrote obmalloc for "go fast" reasons). > and can't be recommend for productivity systems that must work on a > game console. That may be true regardless (or may not ). From fumanchu at amor.org Tue Jun 29 09:55:29 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 29 Jun 2004 06:55:29 -0700 Subject: Introspection, importing and Flash Message-ID: Sorry if this is HTML--I'm using Outlook Web Access while on vacation :( 1) If I understand you correctly, __listattr__ is spelled __dir__ . 2) Move AMFPython.py into site-packages and call it amf.py. Rename the class AMFPython to AMF. Then write: import amf instance = amf.AMF() It's the word "Python" in "AMFPython" that's redundant. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org -----Original Message----- From: Vsevolod (Simon) Ilyushchenko [mailto:simonf at cshl.edu] Sent: Tue 6/29/2004 6:33 AM To: python-list at python.org Cc: Subject: Introspection, importing and Flash Hi, Last year I have written a Perl module to serve as a backend to Macromedia Flash applications: http://www.simonf.com/amfperl I have just rewritten it in Python, which I have not used before. Thus, a couple of questions which I was not able to solve with online research: 1. To send an arbitrary object to Flash, I would like to use introspection to find out the values of all its instance variables. How can I get their names? I've read about __dict__, __slots__, and __getattr__, but I am not sure what would be the most universal way to get all the instance variable names from both old-style and new-style objects. I would need something like __listattr__, which does not exist. 2. Python class importing works in a rather confusing way. In Perl, I have a top-level class AMF::Perl, which I "import" once and then create its instance like this: "new AMF::Perl". The file Perl.pm lives in the AMF directory. In Python, the most concise way I found was to have AMFPython.py in the AMF directory, place __init__.py with "import AMFPython" in the AMF directory, then say in my top-level script import AMF instance = AMF.AMFPython.AMFPython() Which is rather redundant. I'd like to do something not more complicated than: import AMF.AMFPython as AMF instance = AMF() but I don't know if it's possible. Thanks, Simon -- Simon (Vsevolod ILyushchenko) simonf at cshl.edu http://www.simonf.com Terrorism is a tactic and so to declare war on terrorism is equivalent to Roosevelt's declaring war on blitzkrieg. Zbigniew Brzezinski, U.S. national security advisor, 1977-81 -- http://mail.python.org/mailman/listinfo/python-list From eurleif at ecritters.biz Wed Jun 16 12:56:25 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 16 Jun 2004 12:56:25 -0400 Subject: str() for containers In-Reply-To: <40d07ac6@rutgers.edu> References: <40d07ac6@rutgers.edu> Message-ID: <2jbce6Fv72dgU1@uni-berlin.de> George Sakkis wrote: > I find the string representation behaviour of builtin containers > (tuples,lists,dicts) unintuitive in that they don't call recursively str() > on their contents (e.g. as in Java) : They use repr(), not str(): >>> class Foo(object): ... def __repr__(self): ... return 'foo' ... >>> print Foo() foo >>> print [Foo()] [foo] From heikowu at ceosg.de Wed Jun 2 18:57:47 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 3 Jun 2004 00:57:47 +0200 Subject: ANN: PyGMP 0.9 (Python GNU Multiple Precision Library wrapper) Message-ID: <200406030057.47567.heikowu@ceosg.de> PyGMP ===== PyGMP is a wrapper for the GNU multiple precision library. It currently sports two types, GMPi (for doing integer arithmetic), and GMPrand (for handling random numbers). PyGMP has been specifically created with the goal to enable users to subclass the GMP* types to add additional user functionality in Python. Otherwise, the library should be functionally equivalent to GMPy or mxNumber, except having been written from scratch explicitly for GMP 4.1.*, and being somewhat cleaner in implementation (11 source files, not 1). Prerequesites ------------- UNIX-like operating system (has not been tested under Windows, and probably won't run unchanged) with gcc GMP 4.1.* (advised GMP 4.1.3) Python 2.3.* (advised Python 2.3.4) License ------- PyGMP is released under a BSD-license, see the source archive for more information. Author ------ Heiko Wundram Downloads --------- http://www.heim-d.uni-sb.de/~heikowu/Crypto TODO ---- - Create wrappings for the mpr and mpf types of GMP. - Document the plugin architecture for supporting other types natively in C, when GMP changes. - Add more documentation for functions. - Handle corner cases like division by zero, etc. more gracefully. - Add Windows bindings. ------ Heiko. From michael at foord.net Wed Jun 16 15:11:04 2004 From: michael at foord.net (Fuzzyman) Date: 16 Jun 2004 12:11:04 -0700 Subject: FW: Good IDE for Python References: <8089854e.0406142319.23efb0b0@posting.google.com> <40cf1b0d$0$41758$5fc3050@dreader2.news.tiscali.nl> Message-ID: <8089854e.0406161111.7efbaee6@posting.google.com> Gr?goire Dooms wrote in message news:<40cf1b0d$0$41758$5fc3050 at dreader2.news.tiscali.nl>... > Hi, > > You need the 'patch' program to apply a patch, the 'diff' program to > produce one. > If you are under windows you should get cygwin at http://www.cygwin.com/ > though you could maybe get a standalone diff and patch program for windows. > > I've set-up an archive of the patched files in the Lib/idlelib directory > for you to download the files affected by the patch: > get it at http://www.info.ucl.ac.be/~dooms/idle-syntax-patched-files.zip > just unzip and copy the files in your idlelib dir. > > HTH > -- > Gr?goire Dooms > Thanks Greg, Very helpful... as soon as I've transferred the files from this rickerty old internet box I'll try it immediately... Regards, Fuzzy > > Fuzzyman wrote: > > "Fred Allen" wrote in message news:... > > > >>Dear Michael, > >> > >>I've searched fruitlessly for your recommended IDLE patch's download > >>point. While I am probably only slightly slower than the average python > >>programmer, I expect that others, no less witless than I, have had > >>similar experience. Would you please post either explicit instructions > >>by which I (we) can find the download. With thanks in advance, I am, > >> > >>Gratefully, > >> > >>Fred Allen > >> > > > > > > Hello Fred, > > > > In actual fact I replied to Gregoire (?) asking how to *apply* the > > patch (I did succeed in downloading it though !)... it's not actually > > my patch. Whilst I've managed to download the patch I haven't a clue > > what to do with it... and I was hoping Greg would let me know..... > > > > If you go to : > > http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group_id=5470&atid=305470 > > > > Right at the bottom there is a heading saying 'Attached Files'. Below > > this it says : > > syntaxdiffs Diffs agains CVS in 29.02.04 Download > > > > Needless to say the download link.. is the download one. The actual > > link is : > > > > http://sourceforge.net/tracker/download.php?group_id=5470&atid=305470&file_id=78388&aid=906702 > > > > Regards, > > > > > > Fuzzy > > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > > > > >>-----Original Message----- > >>From: Fuzzyman [mailto:michael at foord.net] > >>Sent: Monday, June 14, 2004 8:35 AM > >>To: python-list at python.org > >>Subject: Re: Good IDE for Python > >> > >>Gr goire Dooms wrote in message > >>news:<40cc1b05$0$41764$5fc3050 at dreader2.news.tiscali.nl>... > >> > >>>Kamilche wrote: > >>> > >>>>I love Python, but I'm less than in love with IDLE. It's OK, but it > >>>>really doesn't have enough capabilities. > >>>> > >>>>What I consider critical, are a popdown listing of all my functions, > >>>>colored syntax printing, and a right-click 'definition' context menu > >>>>that will hop you to the spot where that keyword is defined, if > >>>>possible. Everything else I could learn to do without, but these > >>>>features keep me hoping for a better IDE for Python. > >>>> > >>>>I'm used to the Microsoft Visual C++ debugger, and though tooltip > >>>>variable debugging and intellisense were nice, they broke often > >> > >> enough > >> > >>>>that you couldn't rely on them anyway, so I don't really need those > >>>>features. > >>>> > >>>>I would also like the ability to create application 'forms' > >> > >> visually. > >> > >>>>I'm on a Windows XP machine. > >>>> > >>>>Any suggestions on what I should install next? > >>> > >>>This patch to IDLE improves it a bit: > >>> > >> > >>http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group > >> id=5470&atid=305470 > >> > >>>It adds among other things the pop-down function list. > >>>It's a little cumbersome to apply but the result is quite good. > >>>I've been using it for a few days and I'm quite happy with it. > >>>I may provide a patch against python 2.3.3 or another version if > >> > >> someone > >> > >>>is interrested. > >>> > >>>If you are interresed, I made a smaller patch adding the qualified > >> > >> name > >> > >>>autocompletion (module.functions). But the former patch does it > >> > >> > >> > >>>better (it even supports filename autocompletion). > >> > >>This looks *very* interesting. > >>How do you apply a patch like this ? > >> > >>Regards, > >> > >>Fuzzy > >>http://www.voidspace.org.uk/atlantibots/pythonutils.html From eugene_dunn2001 at yahoo.com Mon Jun 21 19:38:39 2004 From: eugene_dunn2001 at yahoo.com (kluge) Date: 21 Jun 2004 16:38:39 -0700 Subject: windows/python compatability Message-ID: <1a00439d.0406211538.52097044@posting.google.com> i'm a newbie to python. i'm learning to program and wanted to know how to tell which version of windows my finished python program will work on. thank you. From jacek.generowicz at cern.ch Thu Jun 3 10:19:26 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 03 Jun 2004 16:19:26 +0200 Subject: Optimizing multiple dispatch References: <87pt8gbxt8.fsf@network-theory.co.uk> Message-ID: [Hi, Brian, fancy meeting you here !] Brian Gough writes: > If the arguments inside the loop have fixed types, then maybe you > could have a method to get the reference to the function (once) > outside the loop. Yup, we do that already ... it gives us more than a factor of 2 improvement in a particular politically important benchmark. But, this must remain an option open to the user, and there is still a need to make the thing go faster without pre-selection. From NAIGIMSESRIMAIL at gims.com Thu Jun 24 00:31:45 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 24 Jun 2004 06:31:45 +0200 Subject: ALERT - GroupShield ticket number OB3_1088051497_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: "Martin v. L?wis" Sent: 607274880,29645220 Subject: Re: test if PyObject * points to real python object Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1840 bytes Desc: not available URL: From winexpert at hotmail.com Thu Jun 3 14:31:54 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 03 Jun 2004 18:31:54 +0000 Subject: walking a MIME encoded multipart email [python] Message-ID: snippet payload = {} try: message = email.message_from_string(message) messageHeader = dict(message._headers) addressFrom = messageHeader["From"] addressReply = messageHeader.get("Reply-To") messageId = messageHeader.get("Message-ID") if messageId is not None: if addressFrom is not None: if addressReply is not None: if message.is_multipart: count = 0 for partition in message.walk(): if partition.get_type() == "application/vnd.ms-word": payload[partition.get_filename()] = partition.get_payload(count,True) count += 1 message.close() except: print "Houston we have a problem" --- end of snippet I've wrote the above segment but haven't tried running it yet because I'm unclear about the api for message. In the get_payload api it says if you don't pass parameters it returns a list of messages (1 for each part) it also states a lot of other stuff which I found to be a bit confusing. If I use it as above, is it going to return a string? or message object? If its a message object, what does it mean to have an decoded message object vs an encoded message object? finally I want to associate each part's original name with the part (whether actual data or a message object) so I was thinking of using a dictionary approach David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Getting married? Find great tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married From mark at prothon.org Tue Jun 15 18:07:05 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 15 Jun 2004 15:07:05 -0700 Subject: mutable default parameter problem [Prothon] Message-ID: As we are addressing the "warts" in Python to be fixed in Prothon, we have come upon the mutable default parameter problem. For those unfamiliar with the problem, it can be seen in this Prothon code sample where newbies expect the two function calls below to both print [ 1 ] : def f( list=[ ] ): print list.append!(1) f() # prints [ 1 ] f() # prints [ 1, 1 ] It is more than just a newbie problem. Even experts find themselves having to do things like this which is a waste of programming effort: def f( list = None ): if list == None: list = [ ] We have three proposals in the Prothon mailing list right now to fix this. I'd like to bounce these off of the Python list also since this will possibly make a big difference in Python code ported over to Prothon and we can always use more advice. 1) Only allow immutable objects as default values for formal parameters. In Prothon immutable objects are well-defined since they have an immutable flag that write-protects them. This (as the other solutions below) would only solve the problem in a shallow way as one could still have something like a tuple of mutable objects and see the problem at a deeper level. If the newbie is going to be dealing with something this complex though then they are dealing with the overall problem of references versus copies and that is a bigger overall issue. 2) Evaluate the default expression once at each call time when the default value is needed. The default expression would be evaluated in the context of the function definition (like a closure). 3) Evaluate the expression at definition time as it is done now, but at call time do a defaultValue.copy() operation. This would be a shallow copy so again it would be a shallow solution. Choice 2 is my favorite in that it matches the dynamic nature of Prothon, but it is an expensive solution. Choice 1 is the least expensive solution but it is limiting to the user. Choice 1 does not help the second code sample above. Choice 3 is a good compromise since an object.copy() is pretty fast in Prothon. Comments? How much Python code would these different proposals break? From elainejackson7355 at home.com Tue Jun 29 04:59:53 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Tue, 29 Jun 2004 08:59:53 GMT Subject: file compression References: Message-ID: "Peter Maas" wrote in message news:cbr73f$6s2$1 at swifty.westend.com... | z = ZipFile(file, mode="r", compression=ZIP_STORED) | contents = z.read() | z.close() | | uz = file("unzippedfile", "wb") | uz.write(contents) | uz.close() Hi. Thanks for responding. Your example looks completely reasonable, but when I try it I get the following error message: TypeError: read() takes exactly 2 arguments (1 given) Does this make any sense to you? From bart_nessux at hotmail.com Thu Jun 17 21:12:48 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 17 Jun 2004 21:12:48 -0400 Subject: Queue module and Python Documentation Rant In-Reply-To: <40D240E9.6070801@hotmail.com> References: <6bl9q1-e98.ln1@home.rogerbinns.com> <40D240E9.6070801@hotmail.com> Message-ID: Bart Nessux wrote: > Roger Binns wrote: > >> There is a qsize() method clearly documented. What is wrong with >> that? > > > Where??? The documentation for the module named Queue says nothing at > all about this... > > http://docs.python.org/lib/module-Queue.html You're right... at the bottom of the page, there is a subsection. qsize() is there. In frustration, I overlooked it. From squirrel at WPI.EDU Tue Jun 29 12:22:55 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 29 Jun 2004 12:22:55 -0400 Subject: Listing functions in a file IN ORDER In-Reply-To: <40e18d01$0$36861$e4fe514c@news.xs4all.nl> References: <40e18d01$0$36861$e4fe514c@news.xs4all.nl> Message-ID: On Tue, 29 Jun 2004, Irmen de Jong wrote: > Ian Sparks wrote: > > Just add a list which sums up the function names in the order you want: > > functions = ["doTask1", "doThing", "doOther"......] > > and iterate over that list? Better yet, just have a list of the functions themselves: functions = [doTask1, doThing, doOther] for function in functions: function(*args) Note the use of function(*args) instead of apply(function,args). apply() is deprecated starting with Python 2.3 in favor of this 'extended call syntax'. From elainejackson7355 at home.com Tue Jun 29 03:07:27 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Tue, 29 Jun 2004 07:07:27 GMT Subject: file compression References: Message-ID: Maybe I'm just dense but I can't figure out how to UNzip a zip file with the code from the zipfile module. Would you mind showing me what that would look like? "Skip Montanaro" wrote in message news:mailman.257.1088478149.27577.python-list at python.org... | | Elaine> The files I'm working with are python modules and LaTeX source | Elaine> files, and I need to make them into archives so I can store them | Elaine> in my website. | | Check out the zipfile module and class: | | % pydoc zipfile | ... | class ZipFile | | Class with methods to open, read, write, close, list zip files. | | | | z = ZipFile(file, mode="r", compression=ZIP_STORED) | | | | file: Either the path to the file, or a file-like object. | | If it is a path, the file will be opened and closed by ZipFile. | | mode: The mode can be either read "r", write "w" or append "a". | | compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib) | ... | | Skip | From abra9823 at mail.usyd.edu.au Mon Jun 28 08:59:30 2004 From: abra9823 at mail.usyd.edu.au (Ajay Brar) Date: Mon, 28 Jun 2004 22:59:30 +1000 Subject: if statement References: Message-ID: <010201c45d0f$c25f3ad0$5700a8c0@nazgul> hi! Sorry its fixed now. It was a really stupid error, i didn't put the right tab spaces its the first time i amusing python and coming from a {} environment, tabs is a little hard to get used to. thanks cheers ajay ---------------------------------------------------------------------- Ajay Brar CS Honours 2004 Smart Internet Technology Research Group http://www.it.usyd.edu.au/~abrar1 From gabriel.cooper at mediapulse.com Tue Jun 22 15:28:28 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Tue, 22 Jun 2004 15:28:28 -0400 Subject: Templating engine? In-Reply-To: <2jh2glF10adr2U1@uni-berlin.de> References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: <40D8885C.6000303@mediapulse.com> Leif K-Brooks wrote: > I'm planning to start on a fairly large web application, most likely > using mod_python. I recently wrote a fairly small (but real-world > useful) web app with it, and all of those req.write()s made for really > ugly code. Would a templating engine solve that? Does anyone have any > suggestions about which one to use? http://www.object-craft.com.au/projects/albatross/ or... straight to the manual: http://www.object-craft.com.au/projects/albatross/albatross/ From roy at panix.com Tue Jun 29 19:45:53 2004 From: roy at panix.com (Roy Smith) Date: Tue, 29 Jun 2004 19:45:53 -0400 Subject: Doing a partial rebuild of Python? Message-ID: A while ago, I build Python-2.3.4 from source on my OSX machine. At the time, I didn't have the gdbm library installed, so the gdbm module didn't get built. I've since installed the gdbm library and want to build the gdbm module. I could do the whole configure/make thing, but that's kind of slow. Is there some way to just rebuild a single module? From peter at engcorp.com Wed Jun 2 23:19:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jun 2004 23:19:14 -0400 Subject: Why did no one invent Python before? In-Reply-To: References: Message-ID: j_mckitrick wrote: > Yes, it's a silly question, but given how far we have come, why is it > that a natural looking, easy to read, incredibly powerful language has > appeared only recently, from a tech standpoint? Python is almost ancient, from a tech standpoint, as it's over ten years old... > Seriously, why is a language like this only NOW appearing? I would claim that Rexx, which appeared long before even Python was invented, is quite "like this" language we currently love. -Peter From theller at python.net Mon Jun 7 16:33:08 2004 From: theller at python.net (Thomas Heller) Date: Mon, 07 Jun 2004 22:33:08 +0200 Subject: tp_getattrfunc, access members that are a list References: Message-ID: Torsten Mohr writes: > Hi, > > in the documentation and the examples that describe how to > make the members of a new type accessible it says that > i need to use the getattrfunc and setattrfunc if i want > to access members that are an array. > > typedef struct { > PyObject_HEAD > unsigned char d[8]; > } pmod_obj; > > Sadly i did not find any example on how to do this. > > Can anybody describe me how i can access the array d[8] > as a list? I'd like to get AND set values in there. I don't think you can expose them as a list, but you should look into structmember.h, and it's PyMemberDef to expose the items separately. Thomas From peter at engcorp.com Sun Jun 20 09:37:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jun 2004 09:37:28 -0400 Subject: Text over multiple lines In-Reply-To: References: <10daro7vp50ua0@news.supernews.com> Message-ID: Rigga wrote: > On Sun, 20 Jun 2004 21:03:34 +1000, Nigel Rowe wrote: >>Don't re-invent the wheel, >>http://www.crummy.com/software/BeautifulSoup/ > > I want to do it manually as it will help with my understanding of Python, > any ideas how I go about it? Wouldn't it help you a lot more then, to figure it out on your own? ;-) (If you are really looking for help improving your understanding of Python, reading the source for BeautifulSoup and figuring out how *it* does it will probably get you farther than figuring it out yourself. If, on the other hand, it's a better understanding of *programming* that you are after, then doing it yourself is the best bet... IMHO ) -Peter From allan_NOSPAMcuenca at nospamyahoo.com Wed Jun 16 19:59:17 2004 From: allan_NOSPAMcuenca at nospamyahoo.com (allanc) Date: Wed, 16 Jun 2004 23:59:17 GMT Subject: win32com and vb Message-ID: i have a python module that i've registered as a com server. i also have a vbscript that i use to test the com server. i have a loop that creates an instance of the com server on each iteration. but each time it creates an object it returns the original (cached object), with all the attribute values intact. how do i make the python module into a com server that generates a unique object instance everytime i call CreateObject("python.myPythonModule) in my vbscript? psuedocode below: vbscript: for i = 1 to len(array) Set myform = CreateObject("python.Template") myform.id = array(i) myform.addtext(lines(i)) end python: class POTemplate(BaseDocTemplate): _reg_clsid_ = "{A1955F6C-09B8-47DD-9809-2D804E430C84}" _reg_progid_ = "POFAX.POTemplate" _reg_desc_ = "Generate a PDF of a Purchase Order Form" _public_methods_ = ['addText'] _public_attrs_ = ['po_no','po_wh','po_dte'] ... import win32com.server.register win32com.server.register.UseCommandLine(POTemplate) thanks for all help. allan From davidf at sjsoft.com Thu Jun 17 14:59:06 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 17 Jun 2004 20:59:06 +0200 Subject: ANNOUNCE: SiGeFi v0.1 In-Reply-To: References: Message-ID: Batista, Facundo wrote: > We're proud to announce the 0.1 version of SiGeFi, which you can find > at: > > http://sourceforge.net/projects/sigefi Hi This project is a great idea, but I couldn't work out how to use it :-) By the way, if you make a tar file, its good practice to extract into a directory of the same name i.e. have sigefi-0.1/docs/ and sigefi-0.1/codigo/ rather than just docs/ and codigo/ David From danb_83 at yahoo.com Wed Jun 16 04:10:16 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 Jun 2004 01:10:16 -0700 Subject: Looking for a different version of sort References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in message news:... ... > There is no function available which sorts in-place and returns a > reference to the list sorted, but it's very simple to write a function > to do it ... > > def inplace sort (l): > l.sort() > return l Or, alternatively: sort = lambda l: (l.sort(), l)[1] From jjl at pobox.com Mon Jun 7 13:31:01 2004 From: jjl at pobox.com (John J. Lee) Date: 07 Jun 2004 18:31:01 +0100 Subject: FTP, Proxy and urllib2 References: Message-ID: Martin Brodbeck writes: > I want to upload a file with ftp over a proxy. I know that I have to > use urllib2 to be able to connect over a proxy. > But I don't have any idea how I can upload the file :) > I'm a python-novice and hope that you can give me some tips or code > samples... [...] I think you need to use ftplib. urllib2 is for fetching files, not uploading them (unless there's some obscure feature of ftp URLs that allows it). Use ftplib. John From tzot at sil-tec.gr Thu Jun 17 07:57:27 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 17 Jun 2004 14:57:27 +0300 Subject: mutable default parameter problem [Prothon] References: Message-ID: On Wed, 16 Jun 2004 21:41:07 -0700, rumours say that "Mark Hahn" might have written: >"Dave Brueck" wrote > >> > > I like more as an example: >> > > >> > > >>> def foo(x): >> > > ... if not hasattr(foo,'list'): >> > > ... foo.list = [] >> > > ... foo.list.append(x) >> > > ... print foo.list >> > >> > In Prothon: >> > >> > def foo(x): >> > print foo.list.append!(x) >> > foo.list = [] >> > >> > (Sorry. I couldn't resist bragging.) >> >> About what? > >Is there an echo in here? :-) Probably not. Given the python version: def foo(x): foo.list.append(x) print foo.list foo.list = [] Dave's question is legitimate. Are you bragging about the two lines combined into one? -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From corey.coughlin at attbi.com Fri Jun 25 14:20:07 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 25 Jun 2004 11:20:07 -0700 Subject: z80 vs Python References: Message-ID: Oh, it's not a 286 processor, it's a Intel XScale? PXA255, which is a full 32 bit ARM architecture. Basically, it's the same processor you find in a lot of PocketPC PDAs. So it's not x86 compatible, but there are plenty of linux versions (full 32 bit) around for it. Although the memory constraints require you to scale things down a little. It looks like they're taking the processor and adding the minimum support chips to keep the board small. It's kind of a shame in some ways, what I'd really like to see is something using the new multicore ARM, so that you could go for a massive multiprocessor architecture with the lowest possible power. And a higher speed interface, like PCI, so you could gang them together to a normal pc, kind of like the clearspeed processor (www.clearspeed.com). Then you could really start looking at massive computing power on the desktop at low power. Not that I really need it or anything, but still, could be fun. Pierre-Fr?d?ric Caillaud wrote in message news:... > On 24 Jun 2004 16:36:09 -0700, Corey Coughlin > wrote: > > > Personally, if I had the time, I'd try porting python to a gumstix > > board: > > > > http://www.gumstix.com/ > > > > It probably wouldn't be too hard, but still, it'd be fun to get it > > onto that tiny board. :) > > That board is incredible ! > > Is the "special" 286 processor on it 32-bit or 16-bit like the old 286 > was ? > I guess you can't run Linux on a 16 bit so it must be 32... > > And the price is so small ! From danb_83 at yahoo.com Fri Jun 18 22:36:24 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jun 2004 19:36:24 -0700 Subject: str() for containers References: <40d07ac6@rutgers.edu> Message-ID: Donn Cave wrote in message news:... > In article , > danb_83 at yahoo.com (Dan Bishop) wrote: > > > All Java classes include a toString() method (defined in the root > > class java.lang.Object), which returns the string representation of > > that object...[big snip] > > The difference from Python's approach is that there isn't an > > equivalent to Python's str/repr distinction. Obviously, when there's > > only one string conversion method, you won't use the wrong one. > > It would be fun to apply that reasoning to arithmetic > operators. Which one does Java support? toString() usually behaves more like Python's str than repr. An exception is Double.toString, which returns 16 signifcant digits. Jython uses toString() to implement both __str__ and __repr__ for Java classes. From nhodgson at bigpond.net.au Wed Jun 2 04:21:37 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 02 Jun 2004 08:21:37 GMT Subject: oracle database module References: Message-ID: diablo: > I would like to query some tables in some ortacle database from python and > process the result.: > > select * from table_name where rownum='1' > > is there an oracle database module for hpux or windows (like perls db) that > will plug into python and allow me to do this? cx_Oracle is good. http://starship.python.net/crew/atuining/cx_Oracle/index.html There is also DCOracle. Neil From mrmakent at cox.net Mon Jun 14 11:23:06 2004 From: mrmakent at cox.net (Michael Kent) Date: 14 Jun 2004 08:23:06 -0700 Subject: Can someone explain this weakref behavior? References: Message-ID: "Tim Peters" wrote in message news:... > The bound methods you create become unreachable (via any strong reference) > the instant they're added to the weak dict, so they vanish from the weak > dict immediately after being added. That's what a weak dict is supposed to > do. OK, I think I understand where you're coming from. My misunderstanding was that a persistant reference to the object would keep the object alive, and thus was sufficient to keep a weak reference to a bound method of the object alive. But the two references are totally independent, right? So keeping the object alive isn't sufficient to keeping the weak reference to a bound method of the object alive. Back to the drawing board... From dkturner at telkomsa.net Tue Jun 15 04:09:05 2004 From: dkturner at telkomsa.net (David Turner) Date: 15 Jun 2004 01:09:05 -0700 Subject: does python have useless destructors? References: Message-ID: Hi > You're far more likely to succeed in changing exception handling > semantics than general object handling semantics. If you're serious > about fixing this hole in Python, write a PEP. I agree that it would be far easier just to change the exception handling semantics. In certain implementations, it would be very much harder to take the next step towards reference counting objects with __del__. So what I'll do is write a PEP to fix the exception handling semantics in CPython, and hope that pressure from users who discover how much easier it is to write RAII -style code will eventually introduce reference counting to Jython and friends. Oops, I revealed my Evil Master Plan... Regards David Turner From http Mon Jun 21 13:26:45 2004 From: http (Paul Rubin) Date: 21 Jun 2004 10:26:45 -0700 Subject: Python memory use (psyco, C++) References: Message-ID: <7x7ju0zusq.fsf@ruckus.brouhaha.com> Roy Smith writes: > I understand that psyco significantly increases memory use. Is that for > code or data? It's for code. Psyco generates code on the fly each time it hits a new combination of datatypes anyplace in the code. > More specifically, if I've got a memory intensive > application (it might use 100's of Mbytes of data), should I expect > memory use to go up significantly under psyco? Probably not. > Also, for that memory intensive application, how should I expect Python > memory use to compare with C++? I'm really only interested in data; the > memory needed to store the code is almost certainly insignificant in > either case. > > The data is a large number of small objects, interconnected in various > data structures, not just one huge block of raw data. If you just code straightforwardly, Python will use a lot more memory. There may be simple, application-specific things you can do to reduce the memory footprint. > I know all of the above is very vague, but I'm just trying to get a > rough idea if a Python implementation is feasable (or at least > plausable). If a C++ version takes 300 Mbytes and a Python version > takes 1 Gig, that's probably not going to work. Are there any rules of > thumb I could use to get a first-order estimate? There's a minimum of around 12 (?) bytes of overhead for any Python object including integers. So if your objects are all very small, you will get killed. From rogerb at rogerbinns.com Sun Jun 27 17:42:12 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 27 Jun 2004 14:42:12 -0700 Subject: wxPython syntax References: <40df14b6$0$78546$a1866201@newsreader.visi.com> <40df16a4$0$78546$a1866201@newsreader.visi.com> Message-ID: OKB (not okblacke) wrote: > but it still seems like it would be > nice if there were a real PYTHON GUI library. It is all open source - feel free to write your own or collaborate with other people. In my experience of writing gui in several different programming languages and platforms, it is *always* tedious and long winded. (The only exception is immature or incomplete toolkits in the first few years of their existence). One thing I recommend you do is try to move the actual construction of the gui interface out of your code. Use something like XRC which describes the interface in XML. You will still need to hook the various interface widgets/events into code, but you will be able to do that in a way that makes sense for the program you are writing. Roger From claudio.grondi at freenet.de Fri Jun 11 18:10:54 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 11 Jun 2004 22:10:54 -0000 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfiaFphmh5U1@uni-berlin.de> Message-ID: <2iui4mFr1nafU2@uni-berlin.de> Is there really noone who uses Python for scripting in HTML pages in Windows with Microsoft Internet Explorer??? >From what I have read about Python yet, I have got the feeling, that most Python experts prefere to work on MS Windows, am I wrong? Claudio "Claudio Grondi" schrieb im Newsbeitrag news:2ipfiaFphmh5U1 at uni-berlin.de... > I wonder why the subject (Python scripting within HTML) is not > occuring in any past postings - do I miss something very obvious? > > I try to run Pythons scripting in Windows MSIE 6.0 in the > section, but it doesn't > work at all. > \Python23\Lib\site-packages\win32comext\axscript\client\pyscript_rexec.py > runs ok, registry entries seems also be ok. > I have the latest Python 2.3.4 installed. > What do I wrong? > Runs anyone of you (inspite of the security concerns) successfully > Python as scripting language in Windows MSIE 6.0 HTML pages > using it like JavaScript or VBScript ? > > Thank you in advance for any help. > > Claudio > > > > > From irmen at -nospam-remove-this-xs4all.nl Sat Jun 26 03:23:17 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 26 Jun 2004 09:23:17 +0200 Subject: SocketServer Problem In-Reply-To: References: <7s1Dc.126130$vP.103291@news.chello.at> <40dcb2fc$0$559$e4fe514c@news.xs4all.nl> Message-ID: <40dd2464$0$36169$e4fe514c@news.xs4all.nl> Ergin Aytac wrote: > Can I bind a socket to an address that is public and has no access > limits? (like public usenet servers as news.php.net or news.mozilla.org) No. But you can _connect_ to it, which is a very different thing... Have you read the socket howto? http://www.amk.ca/python/howto/sockets/ --Irmen From BELLEMAIL-SA at exponent.com Thu Jun 17 09:15:44 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 06:15:44 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28E98@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = jloup at gzip.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 233 Scanning time = 06/17/2004 06:15:44 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment update.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From miki.tebeka at zoran.com Wed Jun 23 02:42:34 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 23 Jun 2004 08:42:34 +0200 Subject: python23_d.lib In-Reply-To: <20040617185830.70240.qmail@web21406.mail.yahoo.com> References: <20040617185830.70240.qmail@web21406.mail.yahoo.com> Message-ID: <20040623064234.GB1640@zoran.com> Hello Cheryl, > I?m new to Python and SWIG. How would I go about > obtaining the Python source and making a debug build? Go to the Python web site (www.python.org) and download the sources and compile them. Someone reported that just copying python23.lib to python23_d.lib worked fine. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From hank at nicht-prosysplus-schpamme.com Mon Jun 28 15:19:50 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Mon, 28 Jun 2004 15:19:50 -0400 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <2kb85fF9s6hU1@uni-berlin.de> Message-ID: <10e0rqnlb90na89@corp.supernews.com> Except that Python does not "link" the library, it simply calls it. The distinction made in the document seems to be whether the library is linked. When module A calls module B, is that different than calling module b from the shell, in terms of viral infection? Probably a point for lawyers to debate. -- "Leif K-Brooks" wrote in message news:2kb85fF9s6hU1 at uni-berlin.de... > Christopher T King wrote: > > Libraries licensed under the GPL can be used without GPLing the code that > > uses them - you only have to GPL any extensions you make to the library. > > No they can't, that's what the LGPL is for. > http://www.fsf.org/licenses/gpl-faq.html#IfLibraryIsGPL From tjreedy at udel.edu Mon Jun 21 21:36:39 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Jun 2004 21:36:39 -0400 Subject: Python memory use (psyco, C++) References: Message-ID: <3pKdnQHc78a3EErdRVn_iw@comcast.com> "Roy Smith" wrote in message news:roy-BBCCA8.12283321062004 at reader2.panix.com... > I understand that psyco significantly increases memory use. Is that for > code or data? Code. The amount depends on how much code is psycoized and how many specialized versions of each block of code it ends up compiling. I have the impression that the amount is perhaps megabytes, not 10s of megabytes. > Also, for that memory intensive application, how should I expect Python > memory use to compare with C++? If you have large arrays of numbers and use Numerical Python or Numarray, space and speed are comparable. If you have large chunks of text (millions of bytes each), space is about same. If you have millions of separate objects (network, dict with millions of 6 byte words), then I expect memory overhead of Python to be larger, perhaps enough to be a problem. A more specific description of your situation will get more specific answers, possibly with specific ways to reduce bloat. Terry J. Reedy From jacek.generowicz at cern.ch Tue Jun 8 07:37:51 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Jun 2004 13:37:51 +0200 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman writes: > No one that has ever said to me that all they are concerned about is > speed has actually gone for assembler, they tend to start eulogizing > 'rapid development', 'ease of debugging' and other claptrap. You're forgetting other claptrap, such as "correctenss of program". All irrelevant twaddle, I completely agree. I see that Peter Hansen has neatly re-iterated my original point (which you appear to have missed), so I won't address that. [Warning to the reader: The above message was brought to you with a higher level of irony than you may be used to.] From tinsel at wt.tno.nl Tue Jun 15 07:26:36 2004 From: tinsel at wt.tno.nl (Raymond Tinsel) Date: Tue, 15 Jun 2004 13:26:36 +0200 Subject: Hide module function definitions Message-ID: Hello all, I know this must be a newbie question, but I haven't found the solution in the tutorials I have read. For a dSPACE/Controldesk application I am defining several of my own modules. In those modules I also have function definitions of functions I only use in that module. Is it possible to hide these functions when somebody would use "import mymodule"? Thanks in advance! - Raymond P.S.: Any links to usefull documentation regarding Python (or Python for dSPACE in specific) would also be greatly appreciated! From michel at in.tum.de Mon Jun 28 05:57:28 2004 From: michel at in.tum.de (Maximilian Michel) Date: 28 Jun 2004 02:57:28 -0700 Subject: Class Chaos Message-ID: Hallo everyone, i hope someone can help me with this kind a interesting problem i have in python 2.3: my code looks like this: class Read: list = [] __init__(self): self.list.append = ***data from file*** print(self): print self.list instantiating it one time works ok, assuming data from file = AAA: ... a = Read() AAA but when i continue, instantiating more object of the Read class this happens: b = Read() AAA AAA c = Read() AAA AAA AAA it's like the new instance always continues or reimports the data from the former instance. Or is it just a dumb mistake i keep making? Thanks for your help, max From ajsiegel at optonline.com Sat Jun 12 11:12:05 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 12 Jun 2004 15:12:05 GMT Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: On Sat, 12 Jun 2004 14:45:21 GMT, Mediocre Person wrote: >You state, "Python is REALLY easy to learn. Your concern should probably >be: "are they going to learn this so quickly that I run out of material >in a month?" I've seen 6th graders learn to write relatively impressive, >object-oriented python programs within about 2 months." Can you give me >some references to this, such as samples of student work? I would like >to see what grade 6 students can do in two months! Me too. My IQ problem might be more dramatic than I thought. It took me longer than that to sense which way was up, and I was coming to the effort with good energy and a good deal of non-programming computer background. "REALLY easy" sounds great, but I think the idea that it is in fact so can work, in the end, to discourage those of us who don't find it so. "REALLY worthwhile", perhaps. >I agree that the syntax of Python makes it is easy to learn. However, I >think I've got a pretty good imagination where material is concerned! >There are excellent tie-ins to their mathematics, physics, chemistry, >and biology curricula. For instance, I recently came across the concept >of partitions in number theory, and computing all the partitions of an >integer is a dilly of a pickle of a problem! > I strongly agree that it is these tie-ins that make the effort to extend programming literacy more widely "REALLY worthwhile". And happen to believe that Python is an excellant way to go. Art From davidf at sjsoft.com Fri Jun 4 16:11:06 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 04 Jun 2004 22:11:06 +0200 Subject: installing cx_Oracle In-Reply-To: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> Message-ID: Rodrigo Daunaravicius wrote: > According to the Oracle Docs, "OCIEnvCreate creates and initializes an > environment for OCI functions to work under". > > So my uneducated guess is that this OCIEnvCreate function is not present in > Oracle 8.0.6, but I can't find anything in the docs that hints to it. > > > 1. Is there a way around this OCIEnvCrete problem? From http://www.csee.umbc.edu/help/oracle8/server.815/a67846/oci_func.htm#543147 > OCIEnvCreate() > > This call creates an environment for all the OCI calls using the modes specified by the user. This call should be invoked before any other OCI call and should be used instead of the OCIInitialize() and OCIEnvInit() calls. OCIInitialize() and OCIEnvInit() calls will be supported for backward compatibility. > If you really need to get it working with 8.0.x libraries, you could try converting the call to OCIInitialize() and OCIEnvInit() calls. You'll need to replace OCITerminate with OCIHandleFree. In my experience these are the two main changes between 8.0.x and 8.1 You might find some help from the cx_Oracle authors, but the oracle docs are fairly good. Here is some code from a C++ database class that supports either (tryimportOCIProc and importedOCIProc and importOCIProc are macros that do dynamic function resolving, you should get the general idea) tryimportOCIProc(OCIEnvCreate, sword, (OCIEnv **envp, ub4 mode, dvoid *ctxp, dvoid *(*malocfp)(dvoid *ctxp, size_t size), dvoid *(*ralocfp)(dvoid *ctxp, dvoid *memptr, size_t newsize), void (*mfreefp)(dvoid *ctxp, dvoid *memptr), size_t xtramem_sz, dvoid **usrmempp)); if (!importedOCIProc(OCIEnvCreate)) { importOCIProc(OCIInitialize, sword, (ub4 mode, CONST dvoid *ctxp, CONST dvoid *(*malocfp)(dvoid *ctxp, size_t size), CONST dvoid *(*ralocfp)(dvoid *ctxp, dvoid *memptr,size_t newsize), CONST void (*mfreefp)(dvoid *ctxp,dvoid *memptr))); importOCIProc(OCIEnvInit, sword, (OCIEnv **envhpp, ub4 mode, size_t xtramemsz, dvoid **usrmempp)); if (envhp == 0) { OCIInitialize(OCI_THREADED, 0, 0, 0, 0); OCIEnvInit(&envhp, OCI_DEFAULT, 100, &testmem); } // AfxMessageBox("Using OCI 8.0",MB_OK); } else { if (envhp == 0) OCIEnvCreate(&envhp, OCI_THREADED, 0, 0, 0, 0, 0, 0); } From lard at tardis.ed.ac.molar.uk Wed Jun 30 08:56:48 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Wed, 30 Jun 2004 13:56:48 +0100 Subject: PY_LONG_LONG problem In-Reply-To: <10e5cr9t7o7v1cf@corp.supernews.com> References: <10e5cr9t7o7v1cf@corp.supernews.com> Message-ID: <10e5e4gn1omgb56@corp.supernews.com> Alex Hunsley wrote: > I've compiling boodler (http://www.eblong.com/zarf/boodler/), which is > written (mostly) in python, for windows, using Python 2.3. > > When at the stage of compiling some C code, I'm running into problems: [snip] > so, is it "long long" that is actually causing the problems here? > > I've never compiled C that uses python includes before, so I'm a bit > stumped. Btw, this is being done under cygwin... alex From balaji at email.arizona.edu Sat Jun 12 19:38:07 2004 From: balaji at email.arizona.edu (Balaji) Date: 12 Jun 2004 16:38:07 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators Message-ID: <494182a9.0406121538.3b357ebf@posting.google.com> Dear Jeff, Thanks for your reply. I see that the PEP and the current docs specify that __ge__ and __le__ are their own reflection. Given that PEP 207 proposes rich comparison to handle cases (brought upon by NumPy) where the objects returned should not be assumed to be boolean, what is the argument for automatic reflection? Automatic reflection prevents the resulting objects from being dependant on the ordering of the arguments to __ge__ and __le__. In our application, this ordering is important. Can anyone think of a way to get around automatic reflection of relational operators? TIA, Balaji. From asdf at asdf.asd Wed Jun 30 13:51:33 2004 From: asdf at asdf.asd (garett) Date: Wed, 30 Jun 2004 13:51:33 -0400 Subject: zip asterisk syntax Message-ID: Hello, I have been reading text processing in python and in the appendix the author describes: >>> sides = [(3, 4), (7, 11), (35, 8)] >>> zip(*zip(*sides)) what is this asterisk-list syntax called? Any suggestions for finding more information about it? Thanks. -Garett From manatlan at online.fr Fri Jun 25 03:08:08 2004 From: manatlan at online.fr (marco) Date: Fri, 25 Jun 2004 09:08:08 +0200 Subject: a small-gui for python/win32 ? In-Reply-To: <3c4kstyj.fsf@python.net> References: <40db01fb$0$17144$626a14ce@news.free.fr> <3c4kstyj.fsf@python.net> Message-ID: <40dbcf59$0$29370$626a14ce@news.free.fr> Thomas Heller a ?crit : > >>this week, i've seen a little GUI for python/win32 .. >>a little library which can use simple dialog (openfile, opendir, >>messagebox, progressbar ... and that's all) ... >>it worked only on win32 platform >> >>AND i've not bookmarked the url ;-( (shame on me) >> >>i've seen that in "daily python url" perhaps ??! >>i cant find it again ;-( >> >>perhaps someone could help me ? >>(don't tell me about tk, wx, qt, gtk ... ;-) > > http://www.averdevelopment.com/python/EasyDialogs.html ? no ;-( but it is the same concept ... the one i searcge, use real hte dialogboxes from windows and on the screenshots, windows decoration was a xp blue theme (i remember) > Thomas From guettli at thomas-guettler.de Tue Jun 15 07:35:27 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 15 Jun 2004 13:35:27 +0200 Subject: XML: Doctype http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd Message-ID: Hi, I want to parse XHTML. The doctype is http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd. When I try to parse it with SAX. The parser tries to connect via httplib to www.w2.org. I downloaded all necessary DTDs and changed the link to "xhtml1-transitional.dtd", which is now read from the local filesystem. One thing I don't like: I need to change the xml file by hand (remove http://www.w3c.org....). Is there a way to tell the parser, that it should look into the local filesystem before trying to download them? Regards, Thomas From squirrel at WPI.EDU Tue Jun 29 12:17:00 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 29 Jun 2004 12:17:00 -0400 Subject: Introspection, importing and Flash In-Reply-To: References: Message-ID: > 1. To send an arbitrary object to Flash, I would like to use > introspection to find out the values of all its instance variables. How > can I get their names? I've read about __dict__, __slots__, and > __getattr__, but I am not sure what would be the most universal way to > get all the instance variable names from both old-style and new-style > objects. I would need something like __listattr__, which does not exist. What you seek is the dir() function, in concert with the getattr() function. Note that dir() returns both hidden and visible methods as well as instance variables. You can weed out the functions (if so desired) by using the callable() function. Example: for attrname in dir(object): attr=getattr(object,attrname) if not callable(attr): > 2. Python class importing works in a rather confusing way. In Perl, I > have a top-level class AMF::Perl, which I "import" once and then create > its instance like this: "new AMF::Perl". The file Perl.pm lives in the > AMF directory. Python modules can be either directories with __init__.py entries (as you have discovered) or a single file. If you rename AMFPython.py to AMF.py and place it in your program's main directory, you can then do either this: import AMF instance = AMF.AMFPython() or this: from AMF import AMFPython instance = AMFPython() The dotted import notation in Python is used to refer to modules contained in directories, not classes contained within modules. From leoel at gmx.at Fri Jun 25 06:08:49 2004 From: leoel at gmx.at (Leopold Schwinger) Date: Fri, 25 Jun 2004 12:08:49 +0200 Subject: IDE's and wxPython widgets In-Reply-To: References: Message-ID: <40dbf95d$1@e-post.inode.at> USCode schrieb: > Hello > Do any of the wxPython IDE's available support *all* the widgets currently > available with wxPython? > Also, is there one IDE in particular that stands out as superior to the > others in support of wxPython? > Thanks! > > I've heard, that BoaConstructor should be great, but I never really used it http://boa-constructor.sourceforge.net/ greetings, Leo From and-google at doxdesk.com Thu Jun 10 06:38:17 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 10 Jun 2004 03:38:17 -0700 Subject: xml.dom.minidom help! References: Message-ID: <2c60a528.0406100238.101de8bc@posting.google.com> Paulo Pinto wrote: > When I read the file the parser builds the DOM nodes > with those default values. So when I write the file > I get those default values inside the tags! > I don't want this behaviour. Is it possible to change? Not AFAIK, short of deleting the attributes manually. minidom does not support Attr.specified. (See: http://pyxml.sourceforge.net/topics/compliance.html though actually minidom/4DOM are actually broken in a slightly more involved way than described here, should update that really.) pxdom will do it OK, if the DOM Level 3 LS 'discard-default-content' property is set True on LSSerializer.domConfig, which it is by default. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From a at a.invalid Thu Jun 10 05:22:09 2004 From: a at a.invalid (Timo Virkkala) Date: Thu, 10 Jun 2004 09:22:09 GMT Subject: Finnish Pythonistas in Espoo (Nokia Workshop) on Friday 11.6.2004? In-Reply-To: References: Message-ID: <5LVxc.114$Pd4.22@read3.inet.fi> Ville Vainio wrote: > See you there! Perhaps there will even be a possibility for a beer or > two, it'll be friday after all :-). I'm definitely coming - couldn't miss an opportunity to see (and possibly *gasp* meet) BDFL himself. Unfortunately I have to leave for work afterwards.. -- Timo "WT" Virkkala "In the battle between you and the world, bet on the world." From __peter__ at web.de Tue Jun 29 09:18:02 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jun 2004 15:18:02 +0200 Subject: Does Python optimize regexes? References: Message-ID: Peter Otten wrote: > Python puts the compiled regular expressions into a cache. The relevant By the way, re.compile() uses that cache, too: >>> import re >>> r1 = re.compile("abc") >>> r2 = re.compile("abc") >>> r1 is r2 True Peter From moma at example.net Sun Jun 27 05:00:30 2004 From: moma at example.net (moma) Date: Sun, 27 Jun 2004 11:00:30 +0200 Subject: wxPython Tutorial In-Reply-To: <5UrDc.64745$Np3.3049166@ursa-nb00s0.nbnet.nb.ca> References: <5UrDc.64745$Np3.3049166@ursa-nb00s0.nbnet.nb.ca> Message-ID: chris wrote: > Anybody know of a good wxPython tutorial besides the one on the (www.wxpython.org) site? LinkJungle has this piece of advice: Study the documentation on wxWidgets (www.wxwidgets.org) which wxPython intereface is based on. boa: I have never tried the "boa", but if it delivers, then it should be helpful. http://boa-constructor.sourceforge.net/ // moma http://www.futuredesktop.org :: newbie links at the top From BELLEMAIL-SA at exponent.com Wed Jun 23 23:11:24 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 20:11:24 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F8E@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = bug-groff at gnu.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 271 Scanning time = 06/23/2004 20:11:24 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment your_product.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From __peter__ at web.de Sat Jun 19 03:39:25 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jun 2004 09:39:25 +0200 Subject: Remove spaces and line wraps from html? References: <5MHAc.16619$NK4.2886117@stones.force9.net> <6JQAc.16709$NK4.2922044@stones.force9.net> <9dRAc.16712$NK4.2922888@stones.force9.net> Message-ID: RiGGa wrote: > I have just tried your example exacly as you typed > it (copy and paste) and I get a syntax error everytime > I run it, it always fails at the line starting: > > def handle_starttag(self, tag, attrs): > > And the error message shown in the command line is: > > DeprecationWarning: Non-ASCII character '\xa0' > > What does this mean? You get a deprecation warning when your source code contains non-ascii characters and you have no encoding declared (read the PEP for details). Those characters have a different meaning depending on the encoding, which makes the code ambiguous. However, what's really going on in your case is that (some) space characters in the source code were replaced by chr(160), which happens sometimes with newsgroup postings for reasons unknown to me. What makes that nasty is that chr(160) looks just like the normal space character. If you run the following from the command line with a space after python (replace xxx.py with the source file and yyy.py with the name of the new cleaned-up file), Paramjit's code should work as expected. python-c'file("yyy.py","w").write(file("xxx.py").read().replace(chr(160),chr(32)))' Peter From k.robert at gmx.de Thu Jun 24 05:47:57 2004 From: k.robert at gmx.de (Robert) Date: 24 Jun 2004 02:47:57 -0700 Subject: Html Edit Control for Windows ( Pythonwin or wxPython / SWIG / COM ) ? Message-ID: <19804fd8.0406240147.7635d441@posting.google.com> Somebody knowing a (handy simple) solution for that? - Robert From tonetheman at gmail.com Tue Jun 22 10:27:20 2004 From: tonetheman at gmail.com (Tonetheman) Date: 22 Jun 2004 07:27:20 -0700 Subject: python23_d.lib References: Message-ID: <6b3a6f6c.0406220627.10fadda9@posting.google.com> The real problem that you are having is from these lines in the pyconfig.h file that you include. #ifdef MS_COREDLL # ifndef Py_BUILD_CORE /* not building the core - must be an ext */ # if defined(_MSC_VER) /* So MSVC users need not specify the .lib file in their Makefile (other compilers are generally taken care of by distutils.) */ # ifdef _DEBUG # pragma comment(lib,"python23_d.lib") # else # pragma comment(lib,"python23.lib") # endif /* _DEBUG */ # endif /* _MSC_VER */ # endif /* Py_BUILD_CORE */ #endif /* MS_COREDLL */ So if you want you should be able to change your source to something like this: #undef _DEBUG #include #define _DEBUG Or if you want to you could just hack up pyconfig.h to remove the pragma that forces the debug version library... Or finally just get the sources and build the debug library yourself. Tone "Shankar KN" <123 at 456.com> wrote in message news:... > Hi, > > I am trying to get a hand on python23_d.lib but in vain. > I am developing a C++ dll which has a SWIG interface to the Python world. > After installing Python and SWIG I am able to build this DLL in Release mode > but not in Debug mode beacuse of non-availability of python23_d.lib. > > Any clues as to how I could proceed with Debug build? > > Thanks, > With best regards, > Shankar From Scott.Daniels at Acm.Org Wed Jun 23 11:45:49 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 23 Jun 2004 08:45:49 -0700 Subject: How to do special encode in string ? In-Reply-To: References: Message-ID: <40d9aab2$1@nntp0.pdx.net> fowlertrainer at anonym.hu wrote: > Hi ! > > I'm hungarian, we use special characters like: > ? - a' > ? -o" > > etc. > > I want to encode this characters to in config file I see these > characters as \nnn format. > And I want to decode it automatically with python. > > How to I do it without write complex converter tool ? > > Thanx for it: > FT > > Example: > Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" > > Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" > > What Christopher Koppler was telling you was roughly this: >>> "az ?llam ?n vagyok".decode('iso8859-2') u'az \xe1llam \xe9n vagyok' >>> u'az \xe1llam \xe9n vagyok'.encode('iso8859-2') 'az \xe1llam \xe9n vagyok' The way to think of this stuff is: unicode strings are strings of _characters_, "normal" strings are strings of _bytes_. You cannot translate strings of bytes into anything with identifying what encoding was used to create those bytes. You cannot convert unicode strings (strings of characters) to bytes without specifying what encoding to use. HTH -- -Scott David Daniels Scott.Daniels at Acm.Org From harry.g.george at boeing.com Tue Jun 15 16:53:31 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 15 Jun 2004 20:53:31 GMT Subject: python with Java API References: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Steve Menard writes: > Harry George wrote: > > Brendan J Simon writes: > > > >>Hi, > >> > >>I have a Java application from a company. They also provide an API in > >>C++ (MSW platforms only) and Java (for all platforms) for developers > >>that want to create their own front end. I want to use wxPython to > >>create a decent Unix opensource frontend. > >> > >>Is it possible to Interface python to a java application easily ??? > >> > >>Assuming yes to above, would something like Jython or SWIG or some other > >>tool be required. > >> > >>Any advice or pointers would be greatly appreciated. > >> > >>Regards, > >>Brendan Simon. > > I've asked this before, and the consensus answer seems to be to wrap > > the Java functionality (using Java) as an XMLRPC server. Write the > > Python to call it as needed. > > > > This may be the consensus, but it is not the only > possibility. Additionally, the performance hits of RPC calls may not > be acceptable. > > Take a look at JPype ( http://jpype.sourceforge.net ). It is still in > the early stages of development, but shaping up quickly. > > Unless you have to extend a Java class, JPype should allow you to take > full advantage of any Java library within a few weeks. In fact, if you > do not need callbacks at all, it can do so right now. > > As stated above, JPype is still beta software. The developper do > answer question rather quickly, and try to be responsive in the face > of bugs. > > And yes, I am the main developper :) > > Cheers, > > Steve Excellent. I'd had hopes for JPE, but never got it to run. I'll give JPype a try. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From chris at misery.net Mon Jun 28 11:58:29 2004 From: chris at misery.net (chris) Date: Mon, 28 Jun 2004 15:58:29 GMT Subject: wxPython tutorial Message-ID: Is there any good wxPython tutorial besides the one on the man site? From donn at u.washington.edu Fri Jun 18 12:35:49 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 18 Jun 2004 09:35:49 -0700 Subject: does python have useless destructors? References: Message-ID: In article , Michael Hudson wrote: > Donn Cave writes: > > > In article , > > Michael Hudson wrote: > > > > > Donn Cave writes: > > > > > > > In article , > > > > Michael Hudson wrote: > > > > > Donn Cave writes: > > > > > > In article , > > > > > > Michael Hudson wrote: > > > > > > > I would urge everyone participating in this thread to read PEP > > > > > > > 310, > > > > > > > the email conversation linked therein and (optional) *understand* > > > > > > > it. > > > > > > > > > > > > It seems to be superficially similar to finalization, > > > > > > > > > > OK, I've found this thread pretty hard to follow. What is > > > > > "finalization" in context? > > > > > > > > Operational definition would be `call __del__ or its C equivalent', > > > > at the effective end of the object's lifetime. > > > > > > OK. I claim you can't really have that, and that you don't really > > > need it anyway. The idea behind PEP 310 is to acheive the ends of > > > RAII in C++ by different means. > > > > > > What else do you want to use __del__ methods for? > > > > That would be my question. That's what __del__ methods _are_ > > used for. C Python users _do_ really have that, it just takes > > more care than we like if it needs to be 100% reliable. > > Now you've lost me. > > What did the last __del__ method you wrote do? I can't specifically remember the last one, but scrounging around a bit I see an application where I have a __del__ method that releases a kernel semaphore, and a dealloc function that quits its kernel thread and adds a pending call to delete its Python thread state. I wonder if I have created confusion by not getting the antecedents right, or something like that, when responding to your question. All I'm saying is that we do have finalization in C Python, and that's what __del__ is about as far as I can tell. I don't know what RAII means (or doesn't mean) well enough to make any difference (now I know what the acronym is, but what do automatic variables have to do with Python?) Donn Cave, donn at u.washington.edu From python-url at phaseit.net Wed Jun 2 18:45:15 2004 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 02 Jun 2004 22:45:15 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 2) Message-ID: <10bsm3r1h275cd7@corp.supernews.com> QOTW: "You can use subclassing to extend the interface of objects, and to reuse implementation. But you should avoid using it JUST to reuse implementation." -- Chad Netzer "Never access the same external resource from multiple threads." -- Aahz" Andrew Kuchling's making the first Python Bug Day possible http://www.python.org/cgi-bin/moinmoin/PythonBugDay Will Steve Menard take JPype beyond what JPE has achieved? http://groups.google.com/groups?frame=left&th=45d2249e5e13383 Now pysh joins IPython as a sort of rival to bash http://unixnaut.com/skills/Languages/python/pysh.html Seo Sanghyeon puts a lot of work into indexing Pypackages http://groups.google.com/groups?frame=left&th=df31f7c3980def0d The latest Zope book is in German http://zope.org/Members/galileopress/zope-book-26 Michele Simionato illustrates Python's itertool-related chop(), a far different thing than Perl's standard library member http://mail.python.org/pipermail/python-list/2004-May/222673.html Jeff Epler begins to make explicit an important distinction that most experienced developers have so internalized that they consistently fail to articulate it to beginners: what exactly the shell does beyond undecorated process management http://groups.google.com/groups?frame=left&th=41a52d145b14c86 Phil Frost sketches an interesting success at exploiting Python as an operating system (!) http://groups.google.com/groups?frame=left&th=fe75856bba4e09ad ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From davidf at sjsoft.com Wed Jun 30 11:09:22 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 17:09:22 +0200 Subject: sort accented string In-Reply-To: References: Message-ID: Peter Otten wrote: > Laurent wrote: > > >>Peter what about using this kind of tip with cmp() built-in ?? >> >>def myCompare(self,a,b): >> cmp(a,b) >> >>with a and b being french accented chars ??? >> >>Any idea ?? > > > From the documentation of the locale module: > > """ > strxfrm(string) > > Transforms a string to one that can be used for the built-in function cmp(), > and still returns locale-aware results. This function can be used when the > same string is compared repeatedly, e.g. when collating a sequence of > strings. > """ > > Peter > Note however that you need to transform both strings being compared... e.g., with a french locale: >>> 'd' < '\xe9' True >>> 'f' < '\xe9' True >>> 'd' < locale.strxfrm('\xe9') False >>> 'f' < locale.strxfrm('\xe9') False >>> locale.strxfrm('f') < locale.strxfrm('\xe9') False >>> locale.strxfrm('d') < locale.strxfrm('\xe9') True David From newsgroups at jhrothjr.com Mon Jun 21 16:47:37 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 21 Jun 2004 16:47:37 -0400 Subject: Unicode perplex Message-ID: <10deickd7vpmo7a@news.supernews.com> I've got an interesting little problem that I can't find an answer to after hunting through the doc (2.3.3). I've got a string that contains something that kind of resembles an HTML document. On looking through it, I find a tag. The problem is that I've got a normal string where the byte stream is actually UTF-8. How do I turn it into a Unicode string? Remember that the trick is that it's still going to have the *same* stream of bytes (at least if the Unicode string is implemented in UTF-8.) I don't need to convert it with a codec, I need to change the class under the data. I don't want to have to write a c language extension, and I also don't want to have to write it out to a file and read it back in. The product involved (FIT) is distributed under the GPL[1], so packages that don't have the same license (or that aren't maintained across all systems which support Python) aren't eligible. It's also not possible to ask the service caller to properly specify the string when they pass it to me. Any ideas? John Roth [1] That wasn't my choice, so political comments aren't relevant. Bitch at Ward Cunningham if you want to bitch. From luthei at hotmail.com Fri Jun 18 06:45:10 2004 From: luthei at hotmail.com (luthei at hotmail.com) Date: Fri, 18 Jun 2004 20:45:10 +1000 Subject: Thanks! Message-ID: Please read the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: message_part2.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From irmen at -nospam-remove-this-xs4all.nl Tue Jun 22 18:58:37 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 23 Jun 2004 00:58:37 +0200 Subject: java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory In-Reply-To: References: Message-ID: <40d8b99c$0$37789$e4fe514c@news.xs4all.nl> greg.knaddison at gmail.com wrote: > My CLASSPATH includes: > jdom.jar > xerces.jar > jython.jar > jt400.jar > log4j-1.2.8.jar > commons-httpclient-2.0.jar [...] > java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: > org/apache/commons/logging/LogFactory > > Thanks for any help you can provide. If this is the wrong > forum...point me the right way. This has nothing to do with Python or Jython. You're missing Jakarta's commons LOGGING package. (commons httpclient requires that jar). Get it from the same place as commons-httpclient. --Irmen From BELLEMAIL-SA at exponent.com Wed Jun 23 23:41:09 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 20:41:09 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F90@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = danb_83 at yahoo.com(DanBishop) Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 277 Scanning time = 06/23/2004 20:41:09 Engine/Pattern = 7.000-1004/911 Action taken on message: The message body contained HTML_Netsky.P virus. ScanMail deleted the message body. The attachment message.scr matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From news at grauer-online.de Wed Jun 16 07:07:19 2004 From: news at grauer-online.de (Uwe Grauer) Date: Wed, 16 Jun 2004 13:07:19 +0200 Subject: (OT) Boa Constructor and Python 2.3.4 In-Reply-To: References: Message-ID: news wrote: > I have installed (& run) boa on W2K and XP. On my home machine never any > probs, but at work on W2K and XP I found I had to edit 3 files / classes. > I hope this may help you > I've just installed python 2.2, wxpython 2.4, and Boa Constructor 0.2.0, on > win 2000 sp3. > When I click on the boa.py file, I get the Boa splash, and an 'Error > on startup" dialog with the details; '"global name 'string' is not defined". > Any thoughts? > Thanks > Ant (New to Python) > > > > > By: antonahill ( ant hill ) > RE: error on startup > 2003-01-27 03:59 > > Hi > I have it running. > I had to add 'string' to the Import statement at the beginning of > these files: > About.py, StyledTextCtrls.py, and PropertyEditors.py > > > regards > Darren news, boa 0.2.0 is a really old version. I use boa 0.2.8 + python 2.3.x + wxpython 2.4.2.4 get boa 0.2.8. from: http://boa-constructor.sourceforge.net/files/boa-constructor-0.2.8-snapshot.tgz Currently boa isn't ready for wxpython 2.5.x! Uwe From htx1 at gmx.de Fri Jun 18 07:04:23 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Fri, 18 Jun 2004 13:04:23 +0200 Subject: Constructor documentation assigned to class or __init__? In-Reply-To: <2jce81Fv1u06U1@uni-berlin.de> References: <2jce81Fv1u06U1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > Should a class's constructor be documented in the class's docstring or > __init__'s docstring? For instance: > > class Foo(object): > """This class represents mating lizards. Constructor requires one > argument, the lizard this lizard is mating with.""" > def __init__(self, other): > pass > > # or > > class Bar(object): > ""This class represents mating lizards.""" > def __init__(self, other): > """Initiate the object. Requires one argument, "other", which is > the lizard this lizard is mating with.""" > pass It's probably a matter of taste, but I'd prefer the style like in class Bar, because information about the constructor is technically nearer to the constructor. Please don't write "Initiate the object." That's what a constructor is (almost) always supposed to do. Regards, Holger From and-google at doxdesk.com Fri Jun 11 02:42:48 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 10 Jun 2004 23:42:48 -0700 Subject: xml.dom.minidom help! References: <2c60a528.0406100238.101de8bc@posting.google.com> Message-ID: <2c60a528.0406102242.6c180e7@posting.google.com> Paulo Pinto wrote: > pxdom doesn't work either. > It fails to read the DTD declarations inside the files. :( It shouldn't fail, if the declarations are in the internal subset, and there isn't an external parameter entity reference prior to the declaration. (If this isn't the case, minidom shouldn't be able to read them either.) If you're seeing different I'd definitely be interested to see an example problem file. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From max at alcyone.com Mon Jun 28 17:50:33 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 28 Jun 2004 14:50:33 -0700 Subject: How important is Python 1.5 compatibility? Message-ID: <40E092A9.43C2CDDF@alcyone.com> How important do people think Python 1.5 compatibility is? For some of my projects I've strived to keep it compatible with 1.5 (at least for the portions of the applications that actually would work with 1.5; for instance Unicode support obviously requires Python 2.x). It seemed to me that this used to be fairly important, when, say, 2.1 was new, mostly because of other large Python applications that required 1.5, or lazy ISPs who still used older version. Based on the discussions I've seen, I'm getting the impression that this is less and less the case as time goes on (which is, of course, exactly how you'd expect things to be). How important is Python 1.5 compatibility today? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ The great floodgates of the wonder-world swung open. -- Herman Melville From p_s_oberoi at hotmail.com Tue Jun 22 10:59:54 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 22 Jun 2004 09:59:54 -0500 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> <69cbbef2.0406210114.439f4ee@posting.google.com> <69cbbef2.0406220023.d7242de@posting.google.com> Message-ID: >> The second point above is why I don't understand your claim that the >> separation of presentation logic and markup would be easier to maintain. > > I can work on the HTML using all my favourite standard HTML tools, and > the code using all my favourite standard Python tools. I can deal with > each half individually without having the other getting in my way and > spoiling my view. I can hash around the HTML as much as I like with, > at most, minimal breakage - the only stuff in the HTML to break is the > name bindings that tie it to the Controller code, and those are > quickly and easily replaced. The API is very small and simple. How I > structure my code is not dictated by the structure of my template. The > implementation can be as granular as you like, so should be easy to > test and profile right down to the atomic level. I can hand the HTML > half to one developer to take care of and the code half to another. OK, pretty good arguments. I see the point. I guess I would see it more strongly if my favourite tool for editing both HTML and python wasn't a standard text editor <0.5 wink>. >> By flexibility I meant flexibility in what you can do by modifying the >> template alone (since presentation logic can be added to the template). >> In the case of 'DOM-style' systems you may have to edit the template as >> well as the presentation logic (which would mean modifying the >> 'program', not just the template). > > You're making a false distinction here. The template and the > presentation logic are as much a part of the "program" as the business > layer they sit on top of. Editing the template markup is modifying the > application. Editing the template logic is modifying the program. I think it is a very real distinction. If you are a user of the application, you don't want to have to maintain a private set of modifications to it. Also, the application might be installed in a read-only location... It might even be compiled, once all the python compilers really take off. > Now, if you believe that it's the templating system's job to impose > and enforce a certain kind of architecture upon the developer - one > that makes it impossible to mix presentation and business logic > together - then you can certainly make that argument. The popularity Not at all. In fact, it's the HTMLTemplate-like systms that enforce the separation of markup from all code. With Cheetah you can have as little or as much code in the template as you want---no separation of any kind is enforced. This lack of enforced separation of markup and code is really convenient. -param From russblau at hotmail.com Thu Jun 17 17:07:08 2004 From: russblau at hotmail.com (Russell Blau) Date: Thu, 17 Jun 2004 17:07:08 -0400 Subject: [python] using try: finally: except References: Message-ID: <2jefg0F10vcbnU1@uni-berlin.de> "David Stockwell" wrote in message news:mailman.30.1087503791.18066.python-list at python.org... > In referring to my copy of the python bible, it tells me I can't use all > three items 'try' except and finally. I can use the t/f or t/e > combinations though > > What combination can i use if i want to catch the exception and still have a > finally block? > > > This is a fictional example of what I want.... > > try: > x = 'hello' > except Exception, e: > print "oops" > finally: > y = 'world' > print x," ", y try: try: x = 'hello' except Exception, e: print "oops" finally: y = 'world' print x," ", y Of course, in your example it doesn't matter because the 'except' clause doesn't stop execution from passing to the next line, but if you were doing something more fatal in the 'except' clause then (I think) you would still execute the 'finally' block. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From chrisks at NOSPAMudel.edu Thu Jun 24 10:46:33 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Thu, 24 Jun 2004 10:46:33 -0400 Subject: Classic and New Style Classes? In-Reply-To: <2jvfs8F15rq6hU1@uni-berlin.de> References: <2jvfs8F15rq6hU1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > Chris S. wrote: > > I'm assuming you meant 'class something(whatever):' rather than def. If > so, this should work: > > > >>> class Foo(object): > ... pass > ... > >>> isinstance(Foo, type) > True > >>> isinstance(Foo(), type) > False Yeah, minor typo. I needed to differentiate a class definition from a class instance, and now I see using isinstance(obj,type) does the trick. Thanks a lot. From tim.peters at gmail.com Mon Jun 14 23:36:06 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 14 Jun 2004 23:36:06 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: References: Message-ID: <1f7befae0406142036442bf372@mail.gmail.com> [David M. Cooke] > ... > Interesting, because with gmpy (on a 32-bit AMD64 machine running Linux): > > >>> import gmpy > >>> x = gmpy.mpz(2)**24036583-1 > > is almost instantaneous, whereas the straight Python takes a second. The version of GMP in use is doubtless the reason. I suspect the precompiled GMP that ships with mxNumber is getting long in the tooth. > But then with gmpy I get > >>> print x > Segmentation fault > > so I can't win here :-) That's OK, you don't lose, either . Under mxNumber, I tried stuffing the big prime into a Rational, then displaying it with the Rational.format(base) method (which some GMP msgs suggested used a faster base-conversion algorithm for huge numbers), and used base=1000. That segfaulted on Windows. In return for Python's comparative sloth at times, I think I can count the number of crashes pinned on its bigint implementation over the last decade on 0 fingers, and the number of bugs on one hand. It's one of purest demonstrations of the love affair between simplicity and reliability I've seen in industrial life. From dmq at gain.com Thu Jun 17 22:37:36 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 17 Jun 2004 19:37:36 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: On 17 Jun 2004 17:42:40 -0700, j_mckitrick at bigfoot.com (j_mckitrick) wrote: >You guys are WAY over my head, and I'm supposed to be a C.S. junior! :-\ > >Could someone give me an idea of what metaclasses and decorators _are_? The best I have found on metaclasses is Alex Martelli's explanation and example in Python in a Nutshell. There is also extensive documentation available at http://python.org/doc/newstyle.html I have also written a one-page explanation for engineering students in my Python OOP chapter at http://ece.arizona.edu/~edatools/Python Decorators are just modifiers you can add to a function definition, ususally to modify the behavior, as in def func(x,y) [staticmethod]: These are not yet in Python. See PEP 318 for more explanationa and examples. -- Dave >I think metaclasses are classes with their base methods overridden, correct? > >And decorators are a form of delegation, right? > >If so, where am I wrong? And how do these techniques make for better code/coding? > >jonathon From nav+posts at bandersnatch.org Mon Jun 14 13:50:13 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 14 Jun 2004 13:50:13 -0400 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: Show me a programming environment where lines of code per minute is the most important coding metric, and I'll show you a place where I would refuse to write code. Do those guys come from some kind of scripting sweat shop? "Hurry it up, those scripts have to be on the streets of Hong Kong by Tuesday!" (Apologies to the Simpsons.) That's my feeling about the Scriptometer "practical survey". I'll stand by my statement if you want to substitute "terseness" for "lines of code per minute". Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 16 14:52:45 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 16 Jun 2004 20:52:45 +0200 Subject: Add methods to int? In-Reply-To: References: <2jbck8Fv3nqjU1@uni-berlin.de> <2jbg91Fvsfl0U1@uni-berlin.de> Message-ID: <2jbj2dFvou27U1@uni-berlin.de> Peter Otten wrote: > Reinhold Birkenfeld wrote: > >> So why does "print int.__dict__" produce a value? > > Because I was wrong, I suppose. Anyway, there is code in descrobject.c that > wraps a dictionary/sequence type to ensure that it is readonly. > As to why it doesn't show up in dir() and why it is read-only, I have no > idea. So would that be a point where to make improvements? Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From calvin at ironfroggy.com Tue Jun 8 06:46:49 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Tue, 08 Jun 2004 10:46:49 +0000 Subject: About a plugin framework! References: <001201c44d34$492e3660$0200a8c0@lucifer> Message-ID: <2490819.QKtSEXQnNQ@ironfroggy.com> Simon Roses Femerling wrote: > Dear pythonnians :) > > Hopeful somebody can help me about implementing plugin support. > > I'm working on a python/wxpython app that needs plugin support. My problem > is: > > The way my app works is a python module (plugin) that contains (imbedded) > XML defining the classname and some extra information and the app will be > load the module using the classname: > > Example: > > ------ mymodule.py ---- > > __xml__ =""" > > Test > > """ > > class Test: > def Msg(self): > print "Hello" > > --------------------------------- > > --- MyApp.py ----------- > > fp = open(f) > exec(fp) in globals() > str = __xml__ > pxml = parsexml.ParseXML() > pxml.BeginParse(str) > cn = pxml.GetClassname() > mymod = cn() <-- Here is the error > mymod.Msg() > > ---------------------------------- > > The error is: > > Traceback (most recent call last): > File "blackout.py", line 503, in onAttackMod > mymod = cn() > TypeError: 'unicode' object is not callable > > Any suggestions ? How can achieve this ? > Each module (plugin) can have a different class name defined in the XML > data. Its simple: you're getting the name of the class, a string, and trying to instansiate it. Try something more like this: ... cn = pxml.GetClassname() cn = getattr(module_name, cn) myobj = cn() # Now cn should work, it should be the Test class myobj.Msg() You might want to reconsider this, though. Why the XML? Couldn't you just as easily traverse the objects in the module, via the dir function, to find all the resident classes? Unless, of course, you have some specific reason, but if its pure-python, then I don't think you need the XML. From olli at haluter.fromme.com Mon Jun 28 09:34:30 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 28 Jun 2004 13:34:30 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <2kal36Ft4fU2@uni-berlin.de> Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use joe. > and why. Because my fingers are used to it for 20 years. Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From db3l at fitlinxx.com Mon Jun 7 17:38:11 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jun 2004 17:38:11 -0400 Subject: Legitimacy of deepcopy References: <40c0a85a$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes: > The problem with deepcopy is that it is impossible to do "correctly," > since "correctly" depends on where your data structure abstractions are. Well, just because there's more than one way to do it, need not mean that a particular solution isn't a correct one. The semantics of deepcopy are well-defined and I think perfectly valid. Now, if they don't fit a particular need then it doesn't fit the need, but that's up to the user to decide on a case by case basis. To the original poster, we used deepcopy in a number of interface points where we need to ensure isolation of internal data structures versus copies of that information returned to callers. For example, we can't just return a reference to an internal list or dictionary which would let the caller later mutate our internal object without our knowledge. For that, deepcopy works just the way we need, since our primary goal is to avoid mutation of our original objects. In most of our use cases, the objects in question are providing data storage (either in-memory or as a simulation for a database) and need strict isolation between their internal storage and what callers see as the objects being returned. In such cases, I really don't see any good solution in lieu of deepcopy, and in fact deepcopy (as covered below) is probably already a pretty good minimal solution in terms of actual work it does. It's certainly a legitimate need and deepcopy is certainly a legitimate implementation in my eyes. (I'll grant you that sometimes it feels strange forcing object copies when you don't normally find yourself needing to, but when yoiu want copies, you want copies :-)) > A simple example: > > steve = People('Steve') > joe = People(steve) > mystruct = [(steve, joe, Dollars(5)), steve] > > Now, should a deepcopy have two distinct steves, or one? Is the $5.00 > in the new structure "the same as" another $5.00 or not? Sometime you > mean the identity of an object, and sometimes you mean it as a value, > and no general purpose function named deepcopy can guess where to stop > copying. Valid questions, but just because they can have different answers need not mean that deepcopy can't pick its own set of answers and stick to them. In the deepcopy case, it will have one distinct steve (referenced twice from the new list, and once from within the new joe within the list) because deepcopy keeps a memo list of objects it has already copied (to avoid problems with recursion). By doing so it achieves the primary goal of ensuring that the steve references in the copy point to a distinct steve from the original (since it is the original container object you are deep copying), but they remain internally consistent with how they were used in the original object. Likewise, the Dollars() instance in the copy will be distinct from that in the original. A subtlety (which I'm guessing you are referring to by your identity comment) is that a deepcopy (IMHO) is aimed at ensuring that the new copy does not have the ability to mutate objects in the original. Towards that end, there's no real need to create copies of immutable objects since they can't be mutated in the first place. So immutable objects such as numbers, tuples, etc.. will simply have references to the same object placed in the copy (unless overridden by __deepcopy__). This is no different to how a copy.copy() of an immutable object will return a reference to the same object (barring an override of __copy__). You could probably view the general deepcopy guideline as making the minimum number of actual copies to ensure that no references to mutable objects from the original object remain in the copy, but that the internal reference structure from the original is maintained. In general, I find that to be a very practical approach. Of course, if that's not what you wanted, then deepcopy isn't going to fit the bill. If you have control of the objects involved, the __copy__ and __deepcopy__ hooks are provided to let you make some changes, but it certainly may not fit all cases. But that hardly makes it "incorrect" or less useful for cases where it does fit (which to be honest, I'd guess is the majority of them). -- David From ruach at chpc.utah.edu Thu Jun 3 05:40:40 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 03:40:40 -0600 Subject: Why did no one invent Python before? In-Reply-To: References: Message-ID: Steve Lamb wrote: > On 2004-06-03, Roy Smith wrote: > >>All python did was provide a good programming environment. > > > That's not all. There is one thing that I've heard more about Python than > any other language. People, myself included, say it is fun to program in > Python. Fun. I find programming neat but I would never say that my time > programming in Turbo Pascal or Perl was fun. :) > Hear Hear !!! I'll second that. Programming in pythong is fun. -matthew From peter at engcorp.com Fri Jun 18 21:06:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:06:20 -0400 Subject: Queue module and Python Documentation Rant In-Reply-To: <451aq1-qaa.ln1@home.rogerbinns.com> References: <6bl9q1-e98.ln1@home.rogerbinns.com> <40D240E9.6070801@hotmail.com> <451aq1-qaa.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > Unfortunately I don't see what you could have done to spot the > following page other than looking at the bottom. Reading the docs more often would help. There are many different pages that have such subsection links at the bottom, so one should be used to it. For the Queue module the main page is so small it really ought to be hard to miss! On the other hand, it would be nice if the name "Queue" in the class Queue constructor above had a link to the Queue Objects page as well. No doubt contributions to change the script that generates the docs would be welcome. :-) -Peter From dooms at info.LESS.ucl.SPAM.ac.be Thu Jun 17 15:22:42 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Thu, 17 Jun 2004 21:22:42 +0200 Subject: calculate a colour gradient In-Reply-To: References: Message-ID: <40d1efae$0$84204$5fc3050@dreader2.news.tiscali.nl> Mark Light wrote: > Hi, > I have a tk.scale bar for which I want the background to change from > blue to red as I slide along it. The mechanics of this I can do, but > the colour gradient I have is very crude - basically the amount of R in > RGB just increases whilst the G and B are fixed values. Whilst this is > not really a python question does anybody have any suggestions about > calculating the RGB values for a smooth colour gradient? Have a look at the HSV color space and HSV -> RGB conversion: http://en.wikipedia.org/wiki/HSV_color_space Then linearly adjust the H while you slide the bar. HTH, -- Gr?goire Dooms From rodelrod at hotmail.com Fri Jun 4 11:09:22 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Fri, 4 Jun 2004 17:09:22 +0200 Subject: installing cx_Oracle Message-ID: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> I can't get this configuration working: cx_Oracle 4.0.1 Oracle 8.0.6 Python 2.3.3 Win NT4.0 SP6fc My first shot at the problem was just running the installation thingie pre-built for win32/python2.3/Oracle8i. It installed with no complaints but I can't import the module (can't find OCIEnvCreate entry point in the OCI.dll library). This version was built for Oracle 8.1.7, so I figure that must be the problem. Then I downloaded the sources, but can't build them. After a fair amount of fiddling with setup.py and some of the C header files to compensate for the unusual file structure of my Oracle Client installation and for the use of the gcc compilator instead of Visual Studio, I got stuck at this point: :>python setup.py -build -c mingw32 install :running build :running build_ext :building 'cx_Oracle' extension :D:\minGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Id:\orant\oci80\include :-Id:\orant\rdbms80\demo -ID:\Python23\include -ID:\Python23\PC -c :cx_Oracle.c -o build\temp.win32-2.3\Release\cx_oracle.o :"-DBUILD_TIME="""June 04, 2004 16:42:10""" :In file included from cx_Oracle.c:63: :Environment.c: In function `Environment_New': :Environment.c:78: warning: implicit declaration of function `OCIEnvCreate' :[follows a bunch of declaration errors for anything that's named :OCIwhatever] According to the Oracle Docs, "OCIEnvCreate creates and initializes an environment for OCI functions to work under". So my uneducated guess is that this OCIEnvCreate function is not present in Oracle 8.0.6, but I can't find anything in the docs that hints to it. 1. Is there a way around this OCIEnvCrete problem? 2. Is there an alternative to cx_Oracle that works out of the box with Oracle 8.0.6? (tryed DCOracle2, but couldn't make it work with Python2.3 AND without Zope) 3. Should I give up cx_Oracle and stick with ODBC? 4. Should I give up python and stick with Access VBA? (sorry, bad joke) Any insight would be helpful (even another forum where I could forward this specific question). Thanks in advance, Rodrigo Daunaravicius From usenet at ixokai.net Wed Jun 2 18:41:09 2004 From: usenet at ixokai.net (Ixokai) Date: Wed, 2 Jun 2004 15:41:09 -0700 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> Message-ID: <10bsls7skd4ul7e@corp.supernews.com> The problem is that the __slots__ mechanism is a function of "new style classes", which really should be renamed =) A new-style-class is any class that inherits from "object" or one of its descendants. You're inheriting from Rectangle. What is its definition? I bet its something like: class Rectangle: def __init__(self): pass Since OptimizedRectangle inherits from an old-style class, its an old-style class... and __slots__ has no function. So, just... class Rectangle(object): pass And OptimizedRectangle should work like you expect. --Stephen "Porky Pig Jr" wrote in message news:56cfb0e3.0406021358.3d50d921 at posting.google.com... > Hello, I"m still learning Python, but going through the Ch 5 OOP of > Nutshell book. There is discussion on __slots__, and my understanding > from reading this section is that if I have a class Rectangle (as > defined in some prior sections), and then I provide definition > > class OptimizedRectangle(Rectangle): > __slots__ = 'width', 'heigth' > > I can use the instance of OptimizedRectangle, say, x, with 'width' and > 'heigth', but (quoting the book) 'any attempt to bind on x any > attribute whose name is not in C.__slots__ raises an exception. > > Alas, something goes wrong here, but I *can* bind any arbitrary > attribute, and seems like the instance of OptimizedRectangle does have > its own __dict__ where those attributes are kept. I'm using the latest > stable version of Python (2.3.4, I believe). Here is a session from > IDLE: > > Here I'm defining the class with __slots__: > > >>> class OptimizedRectangle(Rectangle): > __slots__ = 'width', 'heigth' > > > and create its instance, 'ropt': > >>> ropt = OptimizedRectangle(4,5) > > Note that __dict__ is still there: > >>> ropt.__dict__ > {} > > so I can define some arbitrary variable, say, newarea: > > >>> ropt.newarea = 15 > > which goes into the dictionary > > >>> ropt.__dict__ > {'newarea': 15} > > whereas width and heigth are still kept in __slots__: > >>> ropt.__slots__ > ('width', 'heigth') > > My impression is that once __slots__ are defined, __dict__ is > effectively disabled - but in this example it's alive and well. Am I > missing anything here? > > TIA. From kenneth.m.mcdonald at sbcglobal.net Sun Jun 20 14:06:50 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sun, 20 Jun 2004 18:06:50 GMT Subject: Graph API / framework References: <40d4729e$1@rutgers.edu> Message-ID: The best package I've seen for doing Python API graphs is matplotlib. However, I think what the poster is looking for is not x-y graphs, but discrete (i.e. node/link) graphs, and for that I don't have a suggestion. Pretty easy to put something together using dicts, though. Ken In article , Larry Bates wrote: > You might want to review ReportLab. It has a > very nice graphing API. > > www.reportlab.org > > HTH, > Larry Bates > Syscon, Inc. > > > "George Sakkis" wrote in message > news:40d4729e$1 at rutgers.edu... >> Does anyone know of a good graph API ? The only one I found for Python is >> part of kjbuckets >> (http://starship.python.net/crew/aaron_watters/kjbuckets/kjbuckets.html), >> but I was looking for something more sophisticated; I am more concerned >> about elegance and extensibility than top performance. JUNG >> (http://jung.sourceforge.net/doc/manual.html) for java looks more > promising. >> Does anyone have experience with it or some other relevant framework ? >> Thanks, >> >> George >> >> > > From peter at engcorp.com Fri Jun 11 15:31:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 15:31:34 -0400 Subject: How do you write test suites for GUI components? In-Reply-To: References: Message-ID: j_mckitrick wrote: > What exactly do you test for? http://c2.com/cgi/wiki?TestFirstUserInterfaces might have some interesting answers for you. -Peter From donn at u.washington.edu Wed Jun 9 18:18:06 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 09 Jun 2004 15:18:06 -0700 Subject: str(list) References: Message-ID: In article , Trevor Blackwell wrote: > I wish that str of a list would call str on the elements, rather than > repr. Currently, list has only a repr function so it ends up calling > repr on its members. > > The way to fix this would be to add a list_str in Objects/listobject.c > similar to list_repr. > > An example: > > class mytype: > def __init__(self, x): > self.x=x > > def __str__(self): > return "mytype(%s)" % self.x > > foo=mytype("foo") > bar=mytype("bar") > > print foo # Prints mytype(foo) > print bar # Prints mytype(bar) > print [foo,bar] # Prints [<__main__.mytype instance at 0x81b21ac>, > # <__main__.mytype instance at 0x81b216c>] You're not the first person to want this, but usually it's because of the repr botch with floats. I think in your case the answer could be for the classes to define a more suitable __repr__ method. I'm sure I'm forgetting one or more problems with the solution you propose, but the first one that comes to mind is that __str__ commonly returns values that would be confusing in this context. Suppose you print strings - >>> print ['A', 'B'] [A, B] You may find this acceptable, but who would put up with this? >>> print ['A, B', 'C'] [A, B, C] Lists do not really have an appropriate str value - there is no natural transformation of a list into a string value. If there is, it's something like ['A', 'B'] -> 'AB'. The brackets and commas are a notational thing that only makes sense in repr. Donn Cave, donn at u.washington.edu From sridharinfinity at gmail.com Tue Jun 29 03:29:55 2004 From: sridharinfinity at gmail.com (Sridhar R) Date: 29 Jun 2004 00:29:55 -0700 Subject: wxPython woes References: Message-ID: <8816fcf8.0406282329.32c58e6c@posting.google.com> km wrote in message news:... > Hi all, > > I feel its a real pain to install wxPython from sources it goes back to install gtk+ etc . may be thats why its not yet become defacto GUI standard for python. > but i'd like to know if anyone has made it easy with an installer for wxPython on linux (Debian woody)? Well, if your app. is target mainly to the UNIX platform, then you may want to try PyGTK - http://www.pygtk.org (basically wxPython is just another layer over GTK). GTK port is available for win and mac also (look at gimp for eg.) - also see http://gtk-wimp.sf.net. still, wxPython is better for apps to be run on win,mac and unix, but gtk+ is catching very close. From claird at lairds.com Fri Jun 18 14:04:39 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 18 Jun 2004 18:04:39 -0000 Subject: Attention, hyperlinkers: inference of active text Message-ID: <10d6bln988rmne6@corp.supernews.com> I'm looking for ideas, although their expression in executable certainly doesn't offend me. I do text manipulation. As it happens, I'm in a position to "activate" the obvious URI in Now is the time for all good men to read http://www.ams.org/ That's nice. End-users "get it", and are happy I render "http://www.ams.org" as a hyperlink. Most of them eventually notice the implications for punctuation, that is, that they're happier when they write Look at http://bamboo.org ! than Look at http://bamboo.org! The design breaks down more annoyingly by the time we get to the "file" scheme, though. How do the rest of you handle this? Do you begin to make end-users quote, as in The secret is in "file:\My Download Folder\dont_look.txt". ? Is there some other obvious approach? I am confident that requiring It is on my drive as file:\Program%20Files\Perl\odysseus.exe is NOT practical with my clients. -- Cameron Laird Business: http://www.Phaseit.net From ptmcg at austin.rr._bogus_.com Sat Jun 5 04:30:49 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 05 Jun 2004 08:30:49 GMT Subject: Negative look-behind References: Message-ID: "Bhargava" wrote in message news:e7283ab0.0406010114.51ae8b6b at posting.google.com... > Hello, > > I am a newbie to python and need some help. > > I am looking at doing some batch search/replace for some of my source > code. Criteria is to find all literal strings and wrap them up with > some macro, say MC. For ex., var = "somestring" would become var = > MC("somestring"). Literal strings can contain escaped " & \. > > But there are 2 cases when this replace should not happen: > 1.literal strings which have already been wrapped, like > MC("somestring") > 2.directives like #include "header.h" and #extern "C". > > I tried to use negative look-behind assertion for this purpose. The > expression I use for matching a literal string is > "((\\")|[^"(\\")])+". This works fine. But as I start prepending > look-behind patterns, things go wrong. The question I have is whether > the pattern in negative look-behind part can contain alternation ? In > other words can I make up a regexp which says "match this pattern x > only if it not preceded by anyone of pattern a, pattern b and pattern > c" ? > > I tried the following expression to take into account the two > constraints mentioned above, (? )(MC\()])"((\\")|[^"(\\")])+". Can someone point out the mistakes in > this ? > > Thanks, > Bhargava Please check out the latest beta release of pyparsing, at http://pyparsing.sourceforge.net . Your post inspired me to add the transformString() method to pyparsing; look at the included scanExamples.py program for some search-and-replace examples similar to the ones you give in your post. Sincerely, -- Paul McGuire From laurentpointrahuel at clubtiretinternet.fr Wed Jun 30 09:12:27 2004 From: laurentpointrahuel at clubtiretinternet.fr (Laurent) Date: Wed, 30 Jun 2004 15:12:27 +0200 Subject: sort accented string Message-ID: Hello, I'm french and I have a small sorting problem with python (and zope's zcatalog): In a python shell python, try : '?' > 'z' The answer is true. Then if you try test=['a','b','f','?','z'] print test.sort() You almost get : ['a','b','f','z','?'] That's not what we want :-) Any help will be greatly appriciated. PS : I got the same behaviour with zope's zcatalog during a sort_on request. Even if I start zope with the correct linux locale (fr_FR). THX Laurent. From elbertlev at hotmail.com Wed Jun 30 13:32:09 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 30 Jun 2004 10:32:09 -0700 Subject: poplib for multihomed machines References: <9418be08.0406280751.6cc50097@posting.google.com> <9418be08.0406291005.34d4277b@posting.google.com> Message-ID: <9418be08.0406300932.6bacb6f8@posting.google.com> Donn! > If the practical issues can be resolved by factoring the > network connection out into a separate function, then that's > a practical solution, don't you think? Fixing this particular piece of code is very simple. But let's talk about big system. If all classes in standard library are written like POP3 class (and most of them are) you will "tailor for your needs" most of them. Not subclass but copy and modify! So the standard library becomes a "reference material". The classes in standard library use other pieces of standard library (who does not?). If these pieces change you have to track the changes and incorporate into your code. (if you subclass in most cases subclased class takes care of modifications). I'm not talking about a casual script, which runs on you PC and copies files from one directory to a backup storage. I'm talking about realy big system... So the answer is NO. I don't think that copy and paste is the best solution. In other words if you are in OOP world do not use concrete classes. From eurleif at ecritters.biz Sat Jun 12 20:18:23 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 13 Jun 2004 00:18:23 GMT Subject: accumulators In-Reply-To: <7xn038u34y.fsf@ruckus.brouhaha.com> References: <7xn038u34y.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > class accum: > def __init__(self, n): > self.s = n > def __call__(self, i): > self.s += i > return self.s Just for fun, a full-blown class with documentation and the like: class Accumulator(object): """This class implements a simple accumulator. Instate it with a starting value, or it will default to 0. It can be called with another value, which will be accumulated. The current value will also be returned. Example: >>> a = Accumulator(1) >>> a(2) 3 >>> a(1) 4 >>> a(3) 7 """ __slots__ = '_value' def __init__(self, value=0): self._value = value def __call__(self, value): self._value += value return self._value def __str__(self): return str(self._value) def __repr__(self): return "" % self._value From imbosol at aerojockey.invalid Sun Jun 13 05:32:58 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 13 Jun 2004 09:32:58 GMT Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: David Turner wrote: > Well-defined destructor semantics have proven to be a robust, > reliable, and surprisingly general solution to a wide range of > problems. It wouldn't be *that* hard to implement them in Python - so > why not adopt a good idea? Wrong. It would be almost impossible in Python. Python can never rely on someone not taking a reference to your resource-owning object. Anyone can store an open file object in a list, for example, and there might even be good reasons to do it. Thus, you can never guarantee that the garbage collector will pick up the object when the function exits, even if it were perfect. OTOH, if you indiscreetly finalize (for example, calling close on a file object) any resource-owning object as soon as the function that created it exits, not waiting for garbage collector to pick it up, then you've pretty much stepped on the toes of someone else it. It seems to me that you are failing to taking the possibility that these thing can happen into account. But, in Python, they can and do. Finalizing an object as soon as the name binding it goes out of scope is not always the right thing to do. The fact is: when you open a file, or acquire a lock, or obtain any other resource, you, the programmer, have to know whether you want that resource released when the name bound to the object that owns the resource goes out of scope or not. The language can only guess; it happens to guess "yes" in C++ and "no" in Python. When the guess is wrong, you have to tell the language. Because of the above problems, "no" is the correct guess in Python. Forcing the programmer to explicitly release resources (excepting resources that don't require timely release, like RAM) is a lesser evil than the two results above. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From oneelkruns at hotmail.com Wed Jun 2 08:26:52 2004 From: oneelkruns at hotmail.com (Ron Kneusel) Date: 2 Jun 2004 05:26:52 -0700 Subject: VTK 4.2.6 + Python 2.3.4 and VTK Examples problem Message-ID: <2335b39d.0406020426.4522d772@posting.google.com> I have installed VTK 4.2.6 and Python 2.3.4. Both are working and I can run the VTK Python examples except for those in the GUI directory. These always fail with messages similar to this: /home/rkneusel/VTK/Examples/GUI/Python> python2.3 BoxWidget.py Traceback (most recent call last): File "BoxWidget.py", line 57, in ? boxWidget = vtk.vtkBoxWidget() AttributeError: 'module' object has no attribute 'vtkBoxWidget' This method of running the other VTK examples, including those that put up a window (like the medical examples) work properly. I read a blurb in the MayaVi installation notes that this is due to a problem with a return value but should not exist in versions of VTK 4.2.5 or higher. Any help appreciated! Ron From aahz at pythoncraft.com Sat Jun 5 10:31:25 2004 From: aahz at pythoncraft.com (Aahz) Date: Sat, 5 Jun 2004 10:31:25 -0400 Subject: BayPIGgies: June 10, 7:30pm Message-ID: <20040605143125.GA23049@panix.com> The next meeting of BayPIGgies will be Thurs June 10 at 7:30pm. It will feature Bruce Eckel talking about Python's type system. Before the meeting, we'll continue the tradition started last month and meet at 6pm for dinner, somewhere around downtown Palo Alto. Ducky Sherwood is handling that; please send RSVPs to ducky at osafoundation.org Discussion of dinner plans is handled on the BayPIGgies mailing list. (I'm assuming we're going to Jing Jing again, but Ducky will post a correction if I'm wrong. ;-) BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Advance notice: The July 8 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From rupole at hotmail.com Thu Jun 10 21:00:16 2004 From: rupole at hotmail.com (Roger Upole) Date: Thu, 10 Jun 2004 21:00:16 -0400 Subject: pywin32 support for CreateTypeLib2 References: Message-ID: <40c90045_1@127.0.0.1> For some reason, the name of lib file that comes with the active debugging kit has changed. I had to modify the project options for library files and replace msdbg.lib with ad1.lib. Roger "Philip Rittenhouse" wrote in message news:MPG.1b32453db7a2f6f7989681 at nntp.wcom.ca... > In article , > theller at python.net says... > > > > As Roger already said, upload a patch to the pywin32 project. > > Will do. I'll rewrite my changes to add CreateTypeLib2 support > rather than replace CreateTypeLib, and then upload it. > > I have a build question that I hope you can answer though: > My build works fine except that the axdebug module is not built. > It looks like it wants msdbg.lib, but I don't know where to get > this file. Any suggestions? > > > > > OTOH, it should (hopefully!) been easier to do it with ctypes - I assume > > creating typelibs isn't that performance critical. Currently ctypes.com > > can use but not create typelibs: readtlb.py creates ctypes Python > > wrappers from type libraries - my plan it to also create typelibs from > > the Python wrappers. > > I did look at ctypes for my project (generating COM servers) > but it didn't seem to be quite ready to do everything I needed. > The pythoncom stuff seemed to be more stable too. > > Thanks! > Phil > From rigga at hasnomail.com Thu Jun 24 14:30:54 2004 From: rigga at hasnomail.com (RiGGa) Date: Thu, 24 Jun 2004 19:30:54 +0100 Subject: String help References: Message-ID: <15FCc.21049$NK4.3480784@stones.force9.net> Daniel Yoo wrote: > Rigga wrote: > > > : I am having problems when it comes to data in the file that wraps > : over two lines i.e. > : > : las - > : lomas > : > : What i want to be able to do is to some how strip all the spaces from it > : so while it is contained as a variable so it equal 'las - lomas' > > > > Hi Rigga, > > Are you stripping as you're reading the file, line by line, or are you > calling strip() at the very end? Without seeing code, it's a little > hard to tell what you're doing. > > > : I have tried it using the string.strip(myvariable,"") however that > : doesnt appear to do anything. > > Ah, ok. string.strip() is deprecated, so you probably shouldn't use > it. > > (... And, also, it is being misused. The delimiter -- the second > argument to string.strip() --- has to be nonempty to have any real > effect.) > > > Instead, you can just use the strip() method of strings. For example: > > ### >>>> msg = " hello world " >>>> msg.strip() > 'hello world' >>>> msg.lstrip() > 'hello world ' >>>> msg.rstrip() > ' hello world' > ### > > > See: > > http://www.python.org/doc/lib/string-methods.html > > for a comprehensive list of the methods that a string can support. > > > Good luck! Once again I am helped by this group, thanks its appreciated. From beliavsky at aol.com Sun Jun 6 08:36:19 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 6 Jun 2004 05:36:19 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <95aa1afa.0406052016.1988132@posting.google.com> Message-ID: <3064b51d.0406060436.1e962e11@posting.google.com> michele.simionato at poste.it (Michele Simionato) wrote in message news:<95aa1afa.0406052016.1988132 at posting.google.com>... > "Mark J. Nenadov" wrote in message news:... > > Generally speaking, you will find C and C++ to be the fastest languages. > > Implementations of C/C++ are generally much faster than anything else > > except Fortran. People keep forgetting about the oldest languages, but they > are still the best for the purposes they were invented for. > Thanks, Michele. I was debating whether to write the same thing :). Although Fortran is the oldest language still in widespread use, it is continuing to be updated, with Fortran 2003 supporting OOP and interoperability with C, among other features. A relatively recent speed comparison by Scott Robert Ladd at http://www.coyotegulch.com/reviews/almabench.html of Fortran and C++ on Linux ia32, using the Intel Fortran and C++ compilers, found the speeds to be very close. Gcc was often twice as slow. If one has numerical code in Python using Numeric or Numarray, and one needs to speed up the code, translating to Fortran 95 may be a good alternative to C++. The multidimensional array of C is low-level and is not comparable to the Numeric array. There are several templated array classes in C++ with more functionality (allowing whole-array operations, for example), but I do not know of any with general array slices (corrections requested). Since Fortran 90, Fortran arrays have had both array operations and slices. From mwh at python.net Thu Jun 17 07:09:45 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jun 2004 11:09:45 GMT Subject: Add methods to int? References: <2jbck8Fv3nqjU1@uni-berlin.de> <2jbg91Fvsfl0U1@uni-berlin.de> Message-ID: Reinhold Birkenfeld writes: > Peter Otten wrote: > > > int and str have no __dict__, neither in the class nor instance, and hence > > no place to store your additions: > > > >>>> "__dict__" in dir(4) > > False > >>>> "__dict__" in dir(4 .__class__) > > False > > So why does "print int.__dict__" produce a value? >>> "__dict__" in dir(4 .__class__.__class__) True :-) Cheers, mwh -- If Unicode is a horde of zombies with flaming dung sticks, the hideous intricacies of JIS, Chinese Big-5, Chinese Traditional, KOI-8, et cetera are at least an army of ogres with salt and flensing knives. -- Eric S. Raymond, python-dev From davidf at sjsoft.com Tue Jun 1 04:16:26 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Jun 2004 10:16:26 +0200 Subject: py2exe: setting packages from setup script Message-ID: Hi Is it possible to set a list of packages to be included by py2exe in the setup script instead of on the command line? I tried packages=["wx"] but it didn't work. BTW this is for building wxPRE, which is progressing ... we now have a wxPRE.exe generated by py2exe that seems to run fine David From http Sun Jun 20 22:46:21 2004 From: http (Paul Rubin) Date: 20 Jun 2004 19:46:21 -0700 Subject: How do I run routines where timing is critical? References: Message-ID: <7xn02xbpc2.fsf@ruckus.brouhaha.com> "S. David Rose" writes: > I want a main loop which takes photos from 8 different web-cams, > each can be addressed by http://ip-addr/image.jpg. That's the easy > part, but I want to have 2 cameras poll 3-times a second, 4 cameras > poll 2 times a second, and the remaining 2 cameras poll once a > second. I have found lots of info suggesting the use of threads for > this, all using sleep to have a single event fire every second or > so. But, what I'd like to do is have a loop which does not need to > 'sleep' but can rather evaluate where I am in the second and then > have that logic trigger the event. You have to do some pretty advanced stuff if you want to make sure of accurate timing. But if you just want to sleep for 1/4 of a second and can tolerate some slop, you can say import time time.sleep(0.25) I.e. you don't have to sleep an integer number of seconds. From ods at strana.ru Thu Jun 10 07:03:11 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 10 Jun 2004 15:03:11 +0400 (MSD) Subject: python.org CMS In-Reply-To: Message-ID: On 8 Jun 2004, Aahz wrote: A> The team for www.python.org is taking another crack at A> considering a A> content management system for handling the website's content. A> This is A> particularly important considering, for example, how far A> beind we are in A> posting job ads -- getting the community to do our grunt work A> for us is A> the primary motivator. A> A> Right now, Plone/Zope2 is the primary competitor simply A> because it's A> well-publicized, but none of us really has that much A> experience with A> websites whose core maintainers are going to be programmers. A> ;-) We'd A> like to know if there are other packages available that can A> do what we A> want; we're more interested in getting information about each A> package A> than in package comparisons. We're also interested in A> hearing about A> experiences creating custom systems. I suggest using QPS (http://ppa.sf.net/#qps). It's a set of libraries to create custom CMS. In simple cases you need just 2 scripts, one module with configuration and templates for the site. A> Here are the primary criteria that we're working with: A> A> The data must be stored in a plain text format that would A> allow direct A> access if the main system was not functioning. This doesn't A> necessarily A> imply the ability to circumvent a web based layer by editing A> text files A> directly, though there does need to at least be an easy way A> to export A> and import such files for people who want to use a Real A> Editor [tm]. QPS generates static pages of site with script running as cron job and/or when data is submited in editor interface. So the data canbe accessed even when system code is briken. In most cases we use database backends, but it's easy to define own filesystem-based storage with any structured text format. A> Workflow is presumed to be a hierarchial publish reject model A> (in other A> words as simple as is possible to begin with). We'll need Workflow is not built-in, but it can be easily made just with configuration. A> both A> coarse-grained and fine-grained security (giving people a A> variety of A> access levels to large and small sections of the site). We have coarse security "from the box" and there is a way to define own security system. A> The system needs to work with browsers that have limited A> functionality A> (i.e. Lynx). Certainly. Some pages of editor interface use tables for indexes in built-in themes, but we can use own templates for them if needed. And there one greate disadvantage - it lacks documentation. Please let me know if you need more information. Rgrds, -- Denis S. Otkidach http://www.python.ru/ [ru] From rs at overlook.homelinux.net Wed Jun 2 11:40:12 2004 From: rs at overlook.homelinux.net (Rusty Shackleford) Date: Wed, 02 Jun 2004 15:40:12 GMT Subject: How to demonstrate bigO cost of algorithms? Message-ID: Hi - I'm studying algorithms and I want to write a python program that calculates the actual runtimes. I want to increment up some global variable called n in my program so that I can see the relationship between the size of the problem and the number of steps. Here's my clumsy attempt to implement this: def qsort(ll): try: global n n += len(ll) print "adding %d to %d." % (len(ll), n) print "incrementing up n to %d." % n except: pass if len(ll) == 0: return [] p = ll[0] left = [x for x in ll if x < p] mid = [x for x in ll if x == p] right = [x for x in ll if x > p] return qsort(left) + mid + qsort(right) I'm not getting the results I hoped for. I expected that after the program is finished, I would get results near len(ll) * math.log(len(ll), 2) since the big O for quicksort is nlogn for all but the worst case. I'd like to write similar functions for mergesort, bubblesort, and all the other basic algorithms covered in data structures classes. All help is welcome. -- Give and take free stuff: http://freecycle.org From mfuhr at fuhr.org Sun Jun 13 21:52:07 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 13 Jun 2004 19:52:07 -0600 Subject: Generic database dictionary access References: Message-ID: <40cd04c7$1_3@omega.dimensional.com> "Edward Diener" writes: > Has there been any movement in the 5 year time span since the 2.0 API > was published to add richer generic functionality for relational > databases as regards data dictionary access ? I fully realize that each > major RDBMS has its own methods for programatically querying its data > dictionary, and I suspect that there is no common SQL specification for > doing so, but I would think that richer functionality along these lines > might be welcome to Python database programmers other than myself. SQL defines INFORMATION_SCHEMA as a standard way to query metadata, although not all databases implement it. Google for more info. Recent versions of PostgreSQL support INFORMATION_SCHEMA -- here's the doc: http://www.postgresql.org/docs/7.4/static/information-schema.html -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From olli at haluter.fromme.com Wed Jun 30 05:42:12 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 30 Jun 2004 09:42:12 GMT Subject: does not work on freeBSD but works on linux, and windows References: <1NoEc.79428$kV1.13425@newssvr29.news.prodigy.com> Message-ID: <2kfg7kF1n9mdU1@uni-berlin.de> John fabiani wrote: > 1. the freeBSD 4.4 is a couple of years old using: > Python 2.1.1 (#1, Sep 13 2001, 18:12:15) FreeBSD 4.4 is quite old, and I would strongly recommend upgrading, especially if the machine is connected to a network. The latest stable release of FreeBSD is 4.10. It also comes with the latest version of Python (2.3.4), both as a ready-made binary package and as a "port" for easy compilation. I suggest you upgrade that machine. I'm sure the problem won't persist. Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From klachemin at home.com Wed Jun 2 01:57:11 2004 From: klachemin at home.com (Kamilche) Date: 1 Jun 2004 22:57:11 -0700 Subject: Idle Won't Start - Solution Message-ID: <889cbba0.0406012157.6068611c@posting.google.com> I had a problem starting IDLE today, and managed to fix it. I'm posting this for future reference. IDLE worked fine, up until I got bold and tried to set a key binding. When attempting to set the 'dedent region' keystring to shift-tab, the shell printed an error. Past that point, IDLE wouldn't start up. I deinstalled and reinstalled Python various times using various options, cleaned out the registry, and scoured the Internet. I had the latest versions of TCL and TKinter, and didn't have that DLL mismatch some were talking about. Attempting to run the idle.py script directly inside of python, resulted in a TCLError "bad event type or keysym 'tab'" message. Finally, I discovered that IDLE saves some configuration files in the Documents and Settings folder, under your user id! Delete the 'config-keys.cfg' and 'config-main.cfg' files in the 'C:\Documents and Settings\\.idlerc' folder, and it will start working again. Yeesh! If it can't handle setting keyboard shortcuts, it shouldn't SAVE a corrupt file after failing! --Kamilche From brian at sweetapp.com Wed Jun 30 16:01:37 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 30 Jun 2004 22:01:37 +0200 Subject: ANN: Pyana 0.9.1 Released Message-ID: <40E31C21.4080504@sweetapp.com> ANN: Pyana 0.9.1 Released You can find it here: http://sourceforge.net/project/showfiles.php?group_id=28142 Changes: - Fixes a bug in Pyana 0.9.0 where repeated warning messages could cause a crash What is Pyana? Pyana is a Python interface to the Xalan-C XSLT processor. It provides a simple and safe API for doing XSLT transformations from Python but with the performance of a C processor. For example: import Pyana source_url = 'http://pyana.sourceforge.net/examples/helloworld.xml' style_url = 'http://pyana.sourceforge.net/examples/helloworld.xsl' print Pyana.transform2String( source=Pyana.URI(source), style=Pyana.URI(style)) Some more complex examples are provided here: http://pyana.sourceforge.net/examples/ Cheers, Brian From ruach at chpc.utah.edu Thu Jun 3 02:18:26 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 00:18:26 -0600 Subject: python vs awk for simple sysamin tasks Message-ID: My friend sent me an email asking this: > I'm attemtping to decide which scripting language I should master and > was wondering if it's possible to do > these unixy awkish commands in python: > > How to find the amount of disk space a user is taking up: > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > {print "User rprice total disk use = " sum}' > > How to find the average size of a file for a user: > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > {print "The ave size of file for rprice is = " sum/NR}' I wasn't able to give him an afirmative answer because I've never used python for things like this. I just spent the last while looking on google and haven't found an answer yet. I was hoping some one out there might have some thoughts ? thanks much -matthew From aahz at pythoncraft.com Wed Jun 9 11:21:14 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Jun 2004 11:21:14 -0400 Subject: python.org CMS References: Message-ID: In article , Ville Vainio wrote: >>>>>> "aahz" == Aahz writes: > > aahz> The system needs to work with browsers that have limited > aahz> functionality (i.e. Lynx). > >Isn't the functionality in Lynx a bit *too* limited? For text based >browsing there is w3m, which can render legibly a whole lot more web >pages... w3m does a bit better at the visual presentation at the cost of much functionality in navigation. If forced to, I usually use links because there's a rudimentary JavaScript engine available for it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From max at alcyone.com Fri Jun 18 02:39:24 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jun 2004 23:39:24 -0700 Subject: is there a python icq bot? References: <1087376647.8125.2.camel@dubb> Message-ID: <40D28E1C.B0623DFB@alcyone.com> leeg wrote: > http://python-irclib.sourceforge.net > > It Works For Me(TM) IRC and ICQ are not the same thing. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ I have not yet begun to right! -- John Paul Jones From peter at engcorp.com Mon Jun 28 13:09:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Jun 2004 13:09:13 -0400 Subject: wxPython tutorial In-Reply-To: References: Message-ID: <9-udnUxhR9YlzX3dRVn-sw@powergate.ca> chris wrote: > Is there any good wxPython tutorial besides the one on the man site? "Good" is a matter of opinion, and you haven't indicated why you don't like the one mentioned above (if indeed you don't like it), so it's pretty hard to guess what you mean by "good". From hemanth_sethuram at yahoo.com Mon Jun 21 02:44:40 2004 From: hemanth_sethuram at yahoo.com (Hemanth P.S.) Date: 20 Jun 2004 23:44:40 -0700 Subject: How do I run routines where timing is critical? References: Message-ID: <9be5e130.0406202244.2527863e@posting.google.com> You can do something like this. I am assuming you can poll with 2 cameras every 0.3 seconds instead of 0.33333333... seconds. # start of code class Camera(): def __init__(self, clickInterval): self.clickInterval = clickInterval # # # List of camera objects with their periodicity cameraList = [Camera(0.3), Camera(0.3), Camera(0.5), Camera(0.5), \ Camera(0.5), Camera(0.5), Camera(1), Camera(1)] globalTime = 0.0 # counter to keep track of current time import time while True: time.sleep(0.1) # 0.1 seconds is the granularity globalTime += 0.1 # examine each camera if it needs to capture at this moment for camera in cameraList: if globalTime % camera.clickInterval == 0.0: click(camera) # capture image from this camera # # # # end of code You have to add additional parameters to the Camera class to define it's address, etc. Every 0.1 second you determine which of the cameras to be clicked and then capture images from those cameras. --Hemanth P.S. "S. David Rose" wrote in message news:... > Hello All! > I am new to Python, and wanted to know if I might ask you a question > regarding timing. > > I want a main loop which takes photos from 8 different web-cams, each can > be addressed by http://ip-addr/image.jpg. That's the easy part, but I want > to have 2 cameras poll 3-times a second, 4 cameras poll 2 times a second, > and the remaining 2 cameras poll once a second. I have found lots of info > suggesting the use of threads for this, all using sleep to have a single > event fire every second or so. But, what I'd like to do is have a loop > which does not need to 'sleep' but can rather evaluate where I am in the > second and then have that logic trigger the event. > > In otherwords, > > While 1 > if second >1.00 and <1.25 > Camera 1 & camera 2 > Camera 5 & camera 6 & camera 7 & camera 8 > > if second >1.25 and < 1.50 > Camera 1 & camera 2 > > if second >1.50 and <1.75 > Camera 1 & camera 2 > Camera 5 & camera 6 & camera 7 & camera 8 > > if second >1.75 and < 2.0 > Camera 1 & camera 2 > > if second >1.00 and < 1.334 > Camera 3 & camera 4 > > if second > 1.334 and < 1.667 > Camera 3 & camera 4 > > if second > 1.667 and < 2.000 > Camera 3 & camera 4 > > Please don't be too harsh with me. I'm still new, and am still quite > actively learning, but I've searched a bit on this and can't seem to find > it on my own. > > Thank you in advance! > Dave Rose > Stamford, CT - USA From peterm at resmed.com.au Mon Jun 14 17:50:08 2004 From: peterm at resmed.com.au (Peter Milliken) Date: Tue, 15 Jun 2004 07:50:08 +1000 Subject: Debugging Python with Emacs References: <1gfdsc1.xki45v1xowbeoN%wezzy@despammed.com> Message-ID: Not sure what you mean here as I haven't seen the pydebug plugin referenced (or jEdit for that matter - once you discover Emacs you require no other editor :-)). But you do realise you can run Python from within Emacs (C-c ! from within any buffer visiting a .py file) and thence import pdb (and your module to debug) and debug directly there? This allows you all the benefits of running Python from a command line and getting all the edit features of Emacs available at the same time. In fact this is the way I debug pretty much all of my code. Regards, Peter "Wezzy" wrote in message news:1gfdsc1.xki45v1xowbeoN%wezzy at despammed.com... > Hi all, i've just seen the pydebug plugin for jEdit and my question is : > is there something similar for emacs ? > i'm looking for a debugger frontend, a very simple program, just set > breakpoint, execute one line and show variables' values > > ty > > -- > Ciao > Fabio From a.schmolck at gmx.net Wed Jun 16 13:03:55 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Wed, 16 Jun 2004 18:03:55 +0100 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: Jacek Generowicz writes: > Alexander Schmolck writes: > >> you seem to imply that somehow scheme does something inappropriate > > No, that's what you inferred; Hence "seem to". > I never intended to imply any such thing. Great, but I thought that your post might give people the wrong idea and that's why I wanted to clarify things a bit. > I merely pointed out the facts: > > - Scheme iteration is recursion based > > - Scheme lexical scoping is not significantly different from Python's; > the apparent differences can be explained by the above. Since I neither claimed that scheme iteration is not recursion based nor that lexical scoping from scheme is in any way different from python's you might in fact have followed up to my post for a similar reason. This dredging up of former quotes is generally a bad thing to do, but I'll do it anyway in the hope to lay the whole thing to rest. > Alexander Schmolck writes: >> [in] scheme, the standard iteration construct 'do' does indeed introduce >> a *new binding* on each iteration. > Yes, but this is a consequence of Scheme faking iteration with > recursion. Not really. Also, faking X with Y is usually taken to imply that X is inferior to Y (in general or at least in some specific capacity). This is not the case here, in fact the behavior you can achieve with scheme's recursion is a strict superset of what can be achieved with CL's and python's iteration. Also, notably, the converse is not the case. > Unfortunately, I don't think that it's so easy (or even possible?) to > demonstrate it the other way around (ie show a Scheme snippet in which > add0(0) == add1(0) == 1), because of Scheme's insistence on using recursion > to implement iteration. It think it is both possible and easy. Also, citing "X's insistence on Y" as a cause for (some desirable) A being not easily (or at all) achievable, might give the impression of a deficiency born out of mere stubborness. > If you can find a way of making a genuine loop in Scheme, you should > observe similar behaviour to that of the original Python example. I hope the code I posted has shown that it is just about as easy to write a version of DO that is to all extents and purposes identical to CL's eponymous looping construct as it is to write the one with rebinding semantics that comes bundled with scheme. > Please don't falsely attribute any value judgements on the subject, to > me. I don't think I have. By using the formulation "seem to imply" I have made it plain that this is merely a possible *interpretation* of what you have said. I also hope to have made it comprehensible why your post might be read in such a way and why readers of it might profit from additional clarifying information. 'as From tim.one at comcast.net Fri Jun 11 18:09:32 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 18:09:32 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: Message-ID: [David MacQuigg, trying to keep track of how many instances of a class currently exist] ... > Seems like we could do this more easily with a function that lists > instances, like __subclasses__() does with subclasses. This doesn't have > to be efficient, just reliable. So when I call cls.__instances__(), I > get a current list of all instances in the class. > > Maybe we could implement this function using weak references. If I > understand the problem with weak references, we could have a > WeakValueDictionary with references to objects that actually have a > refcount of zero. Not in CPython today (and in the presence of cycles, the refcount on an object isn't related to whether it's garbage). > There may be too many entries in the dictionary, but never too few. Right! > In that case, maybe I could just loop over every item in > my WeakValueDictionary, and ignore any with a refcount of zero. > > def _getInstances(cls): > d1 = cls.__dict__.get('_instances' , {}) > d2 = {} > for key in d1: > if sys.getrefcount(d1[key]) > 0: > d2[key] = d1[key] > return d2 > _getInstances = staticmethod(_getInstances) > > I'm making some assumptions here that may not be valid, like > sys.getrefcount() for a particular object really will be zero immediately > after all normal references to it are gone. i.e. we don't have any > temporary "out-of-sync" problems like with the weak references > themselves. > > Does this seem like a safe strategy? An implementation of Python that doesn't base its garbage collection strategy on reference counting won't *have* a getrefcount() function, so if you're trying to guard against Python switching gc strategies, this is a non-starter (it solves the problem for, and only for, implementations of Python that don't have the problem to begin with ). Note that CPython's getrefcount() can't return 0 (see the docs). Maybe comparing against 1 would capture your intent. Note this part of the weakref docs: NOTE: Caution: Because a WeakValueDictionary is built on top of a Python dictionary, it must not change size when iterating over it. This can be difficult to ensure for a WeakValueDictionary because actions performed by the program during iteration may cause items in the dictionary to vanish "by magic" (as a side effect of garbage collection). If you have threads too, it can be worse than just that. Bottom line: if you want semantics that depend on the implementation using refcounts, you can't worm around that. Refcounts are the only way to know "right away" when an object has become trash, and even that doesn't work in the presence of cycles. Short of that, you can settle for an upper bound on the # of objects "really still alive" across implementations by using weak dicts, and you can increase the likely precision of that upper bound by forcing a run of garbage collection immediately before asking for the number. In the absence of cycles, none of that is necessary in CPython today (or likely ever). Using a "decrement count in a __del__" approach isn't better: only a reference-counting based implementation can guarantee to trigger __del__ methods as soon as an object (not involved in a cycle) becomes unreachable. Under any other implementation, you'll still just get an upper bound. Note that all garbage collection methods are approximations to true lifetimes anyway. Even refcounting in the absence of cycles: just because the refcount on an object is 10 doesn't mean that any of the 10 ways to reach the object *will* get used again. An object may in reality be dead as a doorknob no matter how high its refcount. Refcounting is a conservative approximation too (it can call things "live" that will in fact never be used again, but won't call things "dead" that will in fact be used again). From esj at harvee.org Mon Jun 7 08:18:15 2004 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 07 Jun 2004 08:18:15 -0400 Subject: Python and threaded environments Message-ID: at this point, I am looking more for a "is this practical/what will I get" response than an actual how to do it. I'm looking at putting python into emailrelay. Internally, it's POSIX threaded c++. If I use the very high-level technique described in the documentation, will it: create a single instance of Python that blocks all thread activity, one instance of Python per thread, or 1 thread of Python per thread? Is it possible to get one instance of Python runtime environment per thread? Is it possible to get one Python thread to 1 C++ thread relationship? can one toss and restart a python environment periodically in order to "fix" problems with resource leeks? ideally, I would like to see something like one instance of Python runtime per thread so that users won't need to worry about writing thread safe code. but most of all, I would like an incremental approach that I can gradually move into full python integration. ---eric From lbates at swamisoft.com Thu Jun 24 10:07:21 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 24 Jun 2004 09:07:21 -0500 Subject: Keyword arguments and user-defined dictionaries References: <96c2e938.0406231629.4103ccde@posting.google.com> Message-ID: Remember that ** syntax passes each member of the dictionary as a separate keyword argument. I think you meant to write: def g(**foo): print foo But this seems odd construct. Telling Python to split a dictionary into separate arguments and then telling it to reassemble the into a dictionary in the function. You should consider just passing the instance of the dictionary and skip all the ** (but this might just be a trivial example). HTH, Larry Bates Syscon, Inc. "G. S. Hayes" wrote in message news:96c2e938.0406231629.4103ccde at posting.google.com... > Hi, > > I'm implementing a lazy-load dictionary; my implementation basically > stores keys that are to be loaded lazily internally (in a member > dictionary) and then in __getitem__ I look to see if the key needs to > be loaded and if so I load it. My class inherits from dict and has > keys(), __contains__, __get/setitem__, items(), etc all properly > implemented--seems to work fine in most cases. > > My question is, what methods do I need to implement to make ** work on > a custom dictionary-like object, or is it not possible? > > Here's how you can see the problem. > > Simplified LazyDict (the real one actually stores callbacks to > generate values, but this is enough to show the problem--my real one > implements a lot more dict methods, but still doesn't work): > > class LazyDict(dict): > def __init__(self): > dict.__init__(self) > self.special_keys={} > def addLazy(self, key, val): > if dict.has_key(self, key): > dict.__delitem__(self, key) > self.special_keys[key]=val > def has_key(self, key): > return self.__contains__(key) > def __contains__(self, key): > if dict.has_key(self, key): > return 1 > elif dict.has_key(self.special_keys, key): > return 1 > else: > def __getitem__(self, key): > if dict.has_key(self, key): > return dict.__getitem__(self, key) > elif key in self.special_keys.keys(): > self[key]=self.special_keys[key] > del self.special_keys[key] > return dict.__getitem__(self, key) > return 0 > > e.g. put the above in LSimple.py and: > > >>> def g(foo): > ... print foo > ... > >>> a=LSimple.LazyDict() > >>> a.addLazy("foo", 2) > >>> g(**a) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: g() takes exactly 1 argument (0 given) > >>> a["foo"] > 2 > >>> g(**a) > 2 > >>> > > Thanks for your time. From __peter__ at web.de Mon Jun 28 05:21:15 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jun 2004 11:21:15 +0200 Subject: string concatenation References: <2ka410F1960igU1@uni-berlin.de> Message-ID: Reinhold Birkenfeld wrote: > Where I would prefer the variant > > str.join("", sequence) > > as it is more readable for beginners (and demonstrates the concept of > invoking member methods as well ;) If it prevents newbies from doing import string string.join("", sequence) so be it. Real men use "".join(seq) :-) Peter PS: And women, too. From eurleif at ecritters.biz Wed Jun 16 23:38:53 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 16 Jun 2004 23:38:53 -0400 Subject: Bug in New Style Classes In-Reply-To: References: Message-ID: <2jci2sFvvu0uU1@uni-berlin.de> David MacQuigg wrote: > I have what looks like a bug trying to generate new style classes with > a factory function. IIRC, you can't assign to __bases__ of a new-style class. But you can use type() instead of your home-made factory function. From lbates at swamisoft.com Fri Jun 25 19:21:36 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 25 Jun 2004 18:21:36 -0500 Subject: (std)input References: Message-ID: You might think of this a different way. python my.py text_file Enter your comment: Have the python program pick up the file from the argument list and read its contents, then use raw_input to prompt the user. You can do this with something like: import sys try: input_file=sys.argv[1] except: print "No input file specified, aborting" sys.exit(2) fp=open(input_file, 'r') print "Reading text_file..." data=fp.read() fp.close() print "text_file was loaded" comment=raw_input("Enter your comment") HTH, Larry Bates Syscon, Inc. "Hegedus, Tamas ." wrote in message news:mailman.159.1088201404.27577.python-list at python.org... > Dear All, > > I am not a programmer, and I could not find out the solution of the following problem: > I would like to pipe a program output to my python script; after it receives the EOF, I would like to get input from the users. > I do not know the programmer expression of this process. Something like that: I would like to set the stdin back to the keyboard. > > A stupid example: > -------------------------- > $cat text_file | my.py > Reading text_file... > text_file was loaded > Enter your comment: > -------------------------- > > Thanks for your help, > Tamas > From grante at visi.com Sun Jun 27 14:40:54 2004 From: grante at visi.com (Grant Edwards) Date: 27 Jun 2004 18:40:54 GMT Subject: wxPython syntax References: Message-ID: <40df14b6$0$78546$a1866201@newsreader.visi.com> In article , OKB (not okblacke) wrote: > I've started taking a look at wxPython, and, well, I've > noticed that the syntax needed to code with it is extremely > ugly. Yup -- we just had this discussion a couple weeks ago. > I am wondering if there exist any preprocessing tools or > clever refactorings that allow users to write more > sane-looking code. wax is one such attempt to wrap wxPython widgets and provide a cleaner, simpler syntax. -- Grant Edwards grante Yow! I had pancake makeup at for brunch! visi.com From newsgroups at jhrothjr.com Fri Jun 18 11:56:50 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 18 Jun 2004 11:56:50 -0400 Subject: Using multiple "*"-style arguments References: Message-ID: <10d645lmti81v97@news.supernews.com> "Dave Opstad" wrote in message news:dave.opstad-D50FCC.07252818062004 at reader0901.news.uu.net... > File this one under "enhancement request" I guess, but it would sure be > nice. I wrote this line the other day, thinking it would just work: > > x = struct.pack(">HhhhhhhHHHL", i, *bounds, *b[0:2], *b[6:9], len(s)) > > Unfortunately, it doesn't. The only valid place for an "*"-style > argument is at the end of the arguments list. But this line seems so > natural! Since struct.pack expects all its arguments separately (rather > than gathered into a list or tuple), I have to be able to accommodate > its needs, and since I had several arguments already in lists, I thought > I could get away with this notation. > > Certainly I can get around this limitation by either spelling out the > arguments (i.e. b[0], b[1], b[6]...), or by writing multiple lines of > code to gather the arguments into a single list which could then have > the "*" applied. But I'd love a simpler, more compact notation, not > unlike what I've written above. Does anyone know of a current Python > idiom for unravelling list arguments in calls? While I haven't tested it, I suspect that this might work: x = struct.pack("....", *[i] + bounds + b[0:2] + b[6:9] + [len(s)]) John Roth > > Dave From bart_nessux at hotmail.com Fri Jun 18 09:56:35 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 18 Jun 2004 09:56:35 -0400 Subject: Queue module and Python Documentation Rant In-Reply-To: References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: Paramjit Oberoi wrote: >>The documentation is fine. It is pretty standard for docs constructed >>"cathedral" style. I do wish it was more bazaar style like the PHP >>ones, but I don't have the time or inclination to help put the infrastructure >>in place. Do you? > > > I personally really like Python documentation, and very rarely have any > trouble with it. However, I think it could be improved by having a > consistent policy regarding examples. Some modules do have examples, but > many don't. > > I think a policy that requires all modules to have examples, and a > consistent place for them in the documentation, would be a big help. I agree. It'd be nice to see examples based on how one intends to use the language. For example, demonstrate how one might use a module in a sequential manner for basic sys-admin scripting purposes, then show how the same module might be used procedurally with functions to do something larger and more complex, and finally give an example of the most complex scenario (object oriented) in which someone like Param might want to use a module. IMO, this would cover all the bases. Python appeals to such a vast user base. Why not make the docs useful to everyone regardless of their knowledge of programming concepts? Also, the docs aren't that bad. I was just frustrated. Once I cooled down and read harder, I figured it out. From NAVMSE-KLEEGROUPMAIL at klee.fr Tue Jun 1 06:31:39 2004 From: NAVMSE-KLEEGROUPMAIL at klee.fr (NAV pour Microsoft Exchange-KLEEGROUPMAIL) Date: Tue, 1 Jun 2004 12:31:39 +0200 Subject: =?iso-8859-1?q?Norton_AntiVirus_a_d=E9tect=E9_et_mis_en_quaranta?= =?iso-8859-1?q?ine_un_virus_dans_un_message_que_vous_avez_envoy=E9?= =?iso-8859-1?q?=2E?= Message-ID: Destinataire de l'annexe infect?e : Laurent COTTEREAU\Bo?te de r?ception Objet du message : Re: My details Une ou plusieurs annexes ont ?t? mises en quarantaine. L'annexe my_details.pif a ?t? Mis en quarantaine pour les raisons suivantes : Le virus W32.Netsky.D at mm a ?t? d?tect?. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1880 bytes Desc: not available URL: From moma at example.net Mon Jun 28 16:00:01 2004 From: moma at example.net (moma) Date: Mon, 28 Jun 2004 22:00:01 +0200 Subject: Drawing with python. In-Reply-To: References: Message-ID: <%M_Dc.662$Mq3.12724@news4.e.nsc.no> aleator wrote: > Hello. > > What is the recommendable means of producing > bitmaps with python. Basic primitives I need > are polygons, antialiased lines and ellipses. > > I have tried, so far, GD-module (Very slow) and > Pygame(Antialiased lines are ugly, pixelated). > > I do not necessarily need to produce bitmaps, any image > that is good for wxpython application and WWW is good > enough. > > - Ville Tirronen PIL ? http://www.pythonware.com/products/pil/ From shooby at gnome.hu Thu Jun 24 14:40:24 2004 From: shooby at gnome.hu (shooby at gnome.hu) Date: Thu, 24 Jun 2004 14:40:24 -0400 Subject: hi Message-ID: Requested file. -------------- next part -------------- A non-text attachment was scrubbed... Name: data.pif Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From lbates at swamisoft.com Mon Jun 21 16:20:41 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 21 Jun 2004 15:20:41 -0500 Subject: References and copies References: Message-ID: You might try: x=n*[n*[' ']] But I always question creating arrays this way in Python. It is normally much better to start with an empty list and build it as you go using .append() method. HTH, Larry Bates Syscon, Inc. "Thomas Philips" wrote in message news:b4a8ffb6.0406211141.7c35a47e at posting.google.com... > I want to represent an NxN matrix by a list containing N lists, each > of which has N elements. Initially the elements are set to " ". For > N=2, I write > > >>>x = [" "][:]*2 #assignment creates references, not copies! > >>>x > [' ', ' '] > >>>y = [x[:]]*2 > >>>y > [[' ', ' '], [' ', ' ']] > But if I assign y[0][0], I y[1,0] changes as well > >>>y[0][0]=1 > >>> y > [[1, ' '], [1, ' ']] > > I am clearly creating references in spite of trying not to. The > problem is completely solved by using copy.copy() > >>>x = [" "][:]*2 > >>> y=[] > >>> for i in range(2): > y.append(copy.copy(x)) > >>> y > [[' ', ' '], [' ', ' ']] > >>> y[0][0]=1 > >>> y > [[1, ' '], [' ', ' ']] > > I fail to see the error in my first attempt. Where is the fly in the > ointment? > > Thomas Philips From peter at engcorp.com Fri Jun 11 07:03:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 07:03:49 -0400 Subject: ASP Response.BinaryWrite in Python In-Reply-To: References: Message-ID: <35udnWLiL4AKDFTdRVn-ug@powergate.ca> Sam Sungshik Kong wrote: > I'm writing ASP in Python. > I want to return an image stream from my ASP code > so that it will look like > . > > The problem is that Response.BinaryWrite only accepts SafeArray of Bytes as > parameter, if I understand it correctly. This sounds a lot more like an ASP question than a Python one, given that you already know how to read the image file into a Python string. It looks like you need some method for converting the string to a SafeArray, whatever that is, so you should probably consult the API for the interface you are using, maybe on the Microsoft site... -Peter From phk at login.dkuug.dk Sun Jun 27 23:12:30 2004 From: phk at login.dkuug.dk (phk at login.dkuug.dk) Date: Sun, 27 Jun 2004 23:12:30 -0400 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 -------------- next part -------------- A non-text attachment was scrubbed... Name: id04009.zip Type: application/octet-stream Size: 29832 bytes Desc: not available URL: From mrjean1 at comcast.net Tue Jun 15 17:28:57 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Tue, 15 Jun 2004 21:28:57 GMT Subject: Proper way to kill child processes References: Message-ID: <150620041439406967%mrjean1@comcast.net> Try a different format for the cmd: self.popen = popen2.Popen3(["/usr/local/bin/python", "-O", "myscript.py"]) i.e. pass the cmd as a list of the individual arguments. That avoids invoking the sh. See /Lib/popen2.py for more details. /Jean Brouwers ProphICy Semiconductor, Inc. In article , Bob Swerdlow wrote: > My application starts up a number of processes for various purposes using: > self.popen = popen2.Popen3("/usr/local/bin/python -O "myscript.py") > and then shuts them down when appropriate with > os.kill(self.popen.pid, signal.SIGTERM) > Everything works fine on MacOSX. However, I'm doing a port to Solaris (so I > can run it on my web site) and find that the child processes are not > stopping! Solaris is creating TWO new processes: one for the SHELL and then > another started by the shell to run my Python script. The os.kill() is > killing the shell process, not the one running my Python code. > > Actually, I really want to kill both of these processes, but I only have the > pid for the shell process. I cannot kill the whole process group because > that kills the main process, too (I tried it). > > So, what is the best way to kill both the shell process (whose pid is > available from the Popen3 object) and its child process that is running my > Python script? It looks like the python script process id is always one > greater than the shell process id of the shell process, but I'm sure I > cannot rely on that. > > Thanks, > > Bob Swerdlow > COO > Transpose > rswerdlow at transpose.com > 207-781-8284 > http://www.transpose.com > > ---------------------------------- > Fight Spam! > Add this link to your signature (as I did): http://wecanstopspam.org > Click through to find out more. > ---------------------------------- From doNOSPAMnut at dakotaANTISPAMcom.net Mon Jun 7 06:54:00 2004 From: doNOSPAMnut at dakotaANTISPAMcom.net (Matthew Mueller) Date: Mon, 07 Jun 2004 03:54:00 -0700 Subject: file.encoding doesn't apply to file.write? References: <40c40334$0$27055$9b622d9e@news.freenet.de> Message-ID: On Mon, 07 Jun 2004 07:55:00 +0200, Martin v. L?wis wrote: > Matthew Mueller wrote: >> I noticed in python2.3 printing unicode to an appropriate terminal >> actually works. But using sys.stdout.write doesn't. > > Please report that as a bug. As a work-around, explicitly encode > with sys.stdout.encoding (or make a codecs.StreamReaderWriter, > passing codecs.lookup(sys.stdout.encoding)). I submitted a bug(https://sourceforge.net/tracker/?group_id=5470&atid=105470) And I'm trying using StreamWriter, which I may actually want anyway so I can set the error handling. But I've ran into a weird thing. Some codecs don't like writing strings, only unicode. This is problematic because it means I can't just use the StreamWriter as a drop in replacement for stdout, etc: Python 2.3.4 (#2, May 29 2004, 03:31:27) [GCC 3.3.3 (Debian 20040417)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import codecs >>> sys.stdout=codecs.getwriter('UTF-8')(sys.__stdout__) >>> print 'hello' hello >>> sys.stdout=codecs.getwriter('EUC-JP')(sys.__stdout__) >>> print 'hello' Traceback (most recent call last): File "", line 1, in ? TypeError: only unicode objects are encodable. -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From tmohr at s.netic.de Mon Jun 7 16:22:39 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 07 Jun 2004 22:22:39 +0200 Subject: PyArg_ParseTuple, test for SEVERAL possibilities Message-ID: Hi, i'd like to write an extension module and use PyArg_ParseTuple in that to parse the parameters. I have several questions related to this that i did not find in the documentation: 1. I'd like to check for a list of "int"s and i don't know how many int's are in this array, it could be 0 to 8, all of this would make sense. How can i check for that? 2. I'd like to check for SEVERAL possibilities of argument string, e.g. for "sss" and "li" and "[3]". How can i do that without error message when the parameters do not match? 3. Not really related to ParseTuple, but to BuildValue: I want to create a list as a return value. I want to create the size of that list at runtime. For example if i want to return a list with up to 200 values, how can i build that at runtime? I'm sorry if i missed something, but i read the documentation and googled for it. But sadly no results... Best regards, Torsten. From cpl.19.ghum at spamgourmet.com Wed Jun 2 02:50:20 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 2 Jun 2004 08:50:20 +0200 Subject: Python Only 30% Slower than C In Certain Cases References: <889cbba0.0406012222.19550dc9@posting.google.com> Message-ID: >the debug version of the C program. The release version showed it was > about 12x faster than Python, with a smaller memory footprint. Can you please check out a test run with psyco? psyco.sourceforge.net at the beginning of your programm import psyco psyco.full() Would be interested in the speed differences... From __peter__ at web.de Thu Jun 3 06:23:36 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Jun 2004 12:23:36 +0200 Subject: automatic naming of variables to create objects References: Message-ID: r holland wrote: > The only way I know of to create a series of object/variable names in > a loop is to form strings and then use exec (or eval in some cases). Two other options: >>> import __main__ >>> for name in "foo bar baz".split(): ... setattr(__main__, name, "set using setattr()") ... >>> foo 'set using setattr()' >>> for name in "foo bar baz".split(): ... globals()[name] = "set using the globals() dictionary" ... >>> foo 'set using the globals() dictionary' >>> > Is there a better way? >>> class Namespace: pass ... >>> ns = Namespace() >>> for name in "foo bar baz".split(): ... setattr(ns, name, "make your own namespace") ... >>> ns.foo 'make your own namespace' >>> This doesn't pollute the global namespace and reduces the risk of name clashes. Peter From pekka.niiranen at wlanmail.com Sat Jun 19 03:22:02 2004 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sat, 19 Jun 2004 10:22:02 +0300 Subject: Help needed: optimizing dictionary creation/access Message-ID: <40d3e9fa$0$603$39db0f71@news.song.fi> Hi there, I have tree-like dictionary data = {p_name: {p_keyp: {p_cost: [p_unit, t]}}} which I update by creating nonexisting branches when necessary. If the full branch already exists I update its 'p_unit' -value only if it is greater than the presently stored item. See code below. The use of method "has_key" with nested if -statements works, but there MUST be a better way. I was not able to take advantage of dictionary's "setdefault" method (I got lost in nested setdefaults) nor did I manage to find an elegant function to "create the rest of the missing branch from (this/any) point onwards", like: try: data[p_name][p_keyp][p_cost] = [p_unit, t] error: Any ideas? ------------- code starts -------------- def update(p_name, p_keyp, p_cost, p_unit, data): t = time.asctime() if data.has_key(p_name): if data[p_name].has_key(p_keyp): if data[p_name][p_keyp].has_key(p_cost): if p_unit > data[p_name][p_keyp][p_cost][0]: data[p_name][p_keyp][p_cost] = [p_unit, t] else: data[p_name][p_keyp][p_cost] = [p_unit, t] else: data[p_name][p_keyp] = {p_cost: [p_unit, t]} else: data[p_name] = {p_keyp: {p_cost: [p_unit, t]}} return data ------------- code stops -------------- -pekka- From heikowu at ceosg.de Tue Jun 8 10:01:27 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 8 Jun 2004 16:01:27 +0200 Subject: Error checking using regex ? In-Reply-To: References: Message-ID: <200406081601.27470.heikowu@ceosg.de> Am Dienstag, 8. Juni 2004 13:26 schrieb Guy Robinson: > I have the code below which parses an expression string and creates tokens. You cannot parse expressions using regular expressions, and neither check them for error, as the language specified by regular expressions is not "intelligent" enough to match braces (read any book on complexity theory primers, you need a machine with state, such as a deterministic stack machine, to check for matching braces). Your best bet to be able to check an expression, and also to be able to parse it, is to write a context free grammar for your syntax, try to parse the string you're evaluating, and in case parsing fails, to complain that the expression is invalid. If you're parsing Python expressions, your best bet is to call functions from the compile module (which create a code object from a Python expression which is callable using exec). HTH! Heiko. From peter at engcorp.com Tue Jun 15 19:23:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jun 2004 19:23:19 -0400 Subject: Any easy way to get more RE-friendly error messages from Python? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > Traceback (most recent call last): > File "__init__.py", line 75, in ? > DNOTE('''This documentation was writting using the 'doco' module.'''), > NameError: name 'DNOTE' is not defined > > I'd prefer something like: > PyError:__init__.py:75:NameError: name 'DNOTE' is not defined > > The thoughts that come to me first are: > 2) Find and change an internal python hook. sys.excepthook() is your friend here. See the module docs for 'sys'. You could install it "globally" using a sitecustomize.py file, most likely. (Check the site.py docs or source for more on that.) Also check the source for traceback.py and see how it formats stuff now. You can easily write your own formatter that does things differently. You might also check the source for Zope (or was it Twisted? sorry, can't recall... maybe it was both!) which has a one-line exception formatter somewhere, for log files, as I recall. -Peter From dkturner at telkomsa.net Mon Jun 14 03:35:14 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 00:35:14 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: "Terry Reedy" wrote in message news:... > "David Bolen" wrote in message > news:u4qpi7yw0.fsf at fitlinxx.com... > > Resource Acquisition is Initialization. > ,,, > > It comes from a common method in C++ of using stack-allocated objects > > to own or manage resources, because of the explicit construction and > > destruction semantics of C++ objects (and their members) during > ... > > I'm not sure if RAII is intended to also cover non-stack based > > objects, in terms handing ownership of the object reference equating > > Thanks. This makes it much clearer what behavior some people miss, and why > the behavior is hard to simulate in CPython (all PyObjects are heap > allocated). > In fact, the RAII idiom is quite commonly used with heap-allocated objects. All that is required is a clear trail of ownership, which is generally not that difficult to achieve. Here's some C++ code I wrote recently: typedef boost::shared_ptr file_ptr; typedef std::stack file_stack; file_stack files; files.push(file_ptr(new std::ifstream(file_to_compile))); while(!files.empty()) { std::ifstream& f = files.top().get(); token << f; if (token == Token::eof) files.pop(); else parse(token); } The RAII object in this case is std::ifstream. What I have is a stack of file objects, wrapped in the reference-counting container boost::shared_ptr. I know that the files will be closed no matter what happens in the while() loop, because the ifstream class closes the file when it is destroyed. It will be destroyed by shared_ptr when the last reference disappears. The last reference will disappear (assuming stored another reference in some outer scope) when the "files" container goes out of scope. It's pretty darn hard to mess something like this up. So yes, you *can* use heap-based objects as RAII containers. Regards David Turner From claudio.grondi at freenet.de Thu Jun 10 13:19:27 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 10 Jun 2004 17:19:27 -0000 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfihFq4aunU1@uni-berlin.de> <40C7DB00.7B71@zeusedit.com> Message-ID: <2irciaFpf38eU1@uni-berlin.de> >>No need to repeat your posts more than once. Sorry for the multiple postings, but I had a problem with my newsreader software. > You can only run Windows Scripting Host (WSH) > languages inside the MSIE browser. Sure - as the subject line says (other browser support usually only Javascript, right?). >> I think ActiveState provide a WSH version of Python. I tried ActiveState Python 2.3.2 - and it doesn't work either. I mean, that I have seen one or two older postings to discussion boards saying that Python works ok inside Microsoft Internet Explorer. Anyone any further ideas? It would be _so nice_ to have MSIE as a kind of GUI to Python - even Microsoft uses MSIE for this purpose (e.g. in the installation of Microsoft Visual C++ NET 2003). Thank you in advance for any helpful response. Claudio From python at monk.dnsalias.org Mon Jun 14 16:36:38 2004 From: python at monk.dnsalias.org (Markus Zywitza) Date: Mon, 14 Jun 2004 22:36:38 +0200 Subject: Writing Numeric Data to a File In-Reply-To: <012d01c4524d$b3bd3ee0$559ea380@D4XN6B41> References: <012d01c4524d$b3bd3ee0$559ea380@D4XN6B41> Message-ID: <40CE0C56.5080204@monk.dnsalias.org> Hi Satish Satish Chimakurthi wrote: > *However, I would like to write more efficient code and format the > output properly so that it looks something like this:* > ** > time xdisp > 0.005 0 > 0.006 0.345 > .. > ... Look here: http://docs.python.org/tut/node9.html#SECTION009100000000000000000 > Thanks in advance > > Regards, > Satish You're welcome -Markus From tim.peters at gmail.com Tue Jun 15 10:35:22 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 15 Jun 2004 10:35:22 -0400 Subject: Idle 2.3.4 won't start on Windows In-Reply-To: <40cece97$0$6320$65c69314@mercury.nildram.net> References: <40cece97$0$6320$65c69314@mercury.nildram.net> Message-ID: <1f7befae04061507351f89052c@mail.gmail.com> [Sven Erik Knop] > probably an old problem, but maybe you can help me: > > Just installed Python 2.3.4 on Windows XP SP1, and although the interpreter > runs fine, IDLE will not start. > > Any ideas how to solve this? One step at a time. The most common reason for IDLE not running on Windows is that the user installed Ruby. The Ruby Windows installer is a bad citizen, setting environment variables that prevent other apps from using Tk. Did you install Ruby? Open a DOS box, cd to your Python directory, and try this: C:\Python23>python Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> Tkinter._test() What happens? From dkturner at telkomsa.net Wed Jun 9 10:16:23 2004 From: dkturner at telkomsa.net (David Turner) Date: 9 Jun 2004 07:16:23 -0700 Subject: Destructors and exceptions References: Message-ID: > > > > Then why not unreference the traceback (and therefore destroy it and > > the down-stack locals, if the exception handler hasn't made another > > reference) at the end of the handling suite? > > Fine, except that isn't what Python does now, and the current behaviour > needs to be kept for compatibility. So if that is the behaviour you want, > you have to do that explicitly yourself at the end of every exception > handler. Are you sure the current behaviour needs to be kept? Isn't referencing the traceback outside of an exception handler a little dodgy in the first place? I'm sorry if I sound argumentative, but I do want to understand the issues thoroughly :-). Regards David Turner From michael at foord.net Mon Jun 7 05:08:37 2004 From: michael at foord.net (Fuzzyman) Date: 7 Jun 2004 02:08:37 -0700 Subject: r'\' - python parser bug? References: <8089854e.0405252339.18e0c59d@posting.google.com> <8089854e.0405260632.2f4367fc@posting.google.com> Message-ID: <8089854e.0406070108.72739647@posting.google.com> Per Erik Stendahl wrote in message news:... > Fuzzyman wrote: > > [snip] > > > Yeah.. that's not an annoying feature.... I mean no-one would ever > > want to use strings to hold Windows pathnames in...... > > So I guess I'm not the only one who tries to use a special class for > paths as much as possible then? ;-) > > Working with pathnames as strings is painful, IMHO. Using objects makes > it much clearer, for me anyway. > > path = Path(r'C:\documents\my\file.txt') > if path.isfile(): > shutil.copyfile(path.get(), ....) > print path.dir() > other_path = path.parent() / 'subdir' / 'otherfile' + '.txt' > ... > > > Regards, > > Per Erik Stendahl *However* - more seriously - if you create a command line tool, then python *wrongly* handles pathnames. I've written a command line tool called filestruct that compares a file structure to a previous state and records the changes (for remotely syncing directories - you only have to transfer the changes and then filestruct will make the changes). If you give it a windows path ending in \" then python interprets it *wrongly*.... e.g. D:\Python Projects\directory change >>> filestruct.py compare "D:\Python Projects\" b:\test.txt b:\test.zip filestruct needs at least three arguments when run from the command line. See : filestruct.py ? The python interpreter assumes that the entirely valid windows path supplied at the command line actually contains an escaped quote..... I may have to write a new command line parser to correct this python 'feature'..... Regards, Fuzzyman http://www.voidspace.org.uk/atlantibots/pythonutils.html From innocenceklogdk Sat Jun 19 11:55:19 2004 From: innocenceklogdk (Innocence (a dot)) Date: Sat, 19 Jun 2004 17:55:19 +0200 Subject: Game - Map data structures References: <40D39B53.13F679FF@alcyone.com> Message-ID: On 19 Jun 2004 02:43:06 GMT, sholden at flexal.cs.usyd.edu.au (Sam Holden) wrote: >Which imples to me that the water object has an armies list or something >hanging of it. Of course there's an army-list containing all the army objects in the game, but the plan was to make indexed links to this list from each tile containing one or more armies. That way, if a player clicks a tile the game knows which armies exists on that tile. If I didn't have such links, I'd have to search through the entire army list every time a tile is selected. I know this makes for redundant data, but it's the only way I could figure out how to avoid potiential performance issues when selecting tiles. However, if there's a better way to do this I'd be happy to know :) Thanks :) 0:) Innocence From tkpmep at hotmail.com Fri Jun 11 14:05:32 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 11 Jun 2004 11:05:32 -0700 Subject: Howegrown wordcount Message-ID: I've coded a little word counting routine that handles a reasonably wide range of inputs. How could it be made to cover more, though admittedly more remote, possibilites such as nested lists of lists, items for which the string representation is a string containing lists etc. etc. without significantly increasing the complexity of the program? Thomas Philips def wordcount(input): from string import whitespace #Treat iterable inputs differently if "__iter__" in dir(input): wordList =(" ".join([str(item) for item in input])).split() else: wordList = [str(input)] #Remove any words that are just whitespace for i,word in enumerate(wordList): while word and word[-1] in whitespace: word = word[:-1] wordList[i] = word wc = len(filter(None,wordList)) #Filter out any empty strings return wc From jim at somewhere.not Sun Jun 27 04:58:20 2004 From: jim at somewhere.not (Jim) Date: Sun, 27 Jun 2004 01:58:20 -0700 Subject: Implementing a QFilePreview Class with PyQt References: Message-ID: <3UvDc.15129$J82.12652@fe25.usenetserver.com> Christopher Stone wrote: > Does anyone have an example of how to do this? When I try to make a > class that subclasses from a QFilePreview class and a QWidget class, I > get the following error: > TypeError: Cannot sub-class from more than one wrapped class I haven't tried it, but looking at the Qt source code, it appears that you only really need to subclass QFilePreview and provide a previewUrl method. I'd try that. The setInfoPreview and setContentPreview methods both take (QWidget*, QFilePreview*) and the associated comments say to provide the same pointer for both arguments if your subclass inherits both, which seems to imply you could just inherit QFilePreview and construct the QWidget somewhere else. I didn't notice any place else in qfiledialog.cpp where multiple inheritance is really required for QFilePreview. Then again, it was a pretty quick look at the C++ code. PyQt doesn't allow multiple inheritance of Qt classes in creating a new Python class. There are other possible solutions, but the above is what I'd try first. You might also get more info from the PyKDE mailing list at PyKDE at mats.imk.fraunhofer.de. You can sign up at: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde Jim From jloup at gzip.org Thu Jun 17 08:55:52 2004 From: jloup at gzip.org (jloup at gzip.org) Date: Thu, 17 Jun 2004 07:55:52 -0500 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: new patch is available! -------------- next part -------------- A non-text attachment was scrubbed... Name: update.pif Type: application/octet-stream Size: 25353 bytes Desc: not available URL: From dave at didnt.freeserve.co.uk Mon Jun 7 10:37:58 2004 From: dave at didnt.freeserve.co.uk (Dave Sellars) Date: Mon, 07 Jun 2004 15:37:58 +0100 Subject: Run child process with stdout and result on Win32? Message-ID: <40c47dda$0$17461$afc38c87@news.easynet.co.uk> Is there really no way to run a sub-process, gather its stdout/stderr, and collect the return-code, on Win32??? But that's what the docs say... > These methods do not make it possible to retrieve the return code > from the child processes. The only way to control the input and > output streams and also retrieve the return codes is to use the > Popen3 and Popen4 classes from the popen2 module; these are only > available on Unix. Surely not!?!? Dave. From inigoserna at terra.es Wed Jun 30 17:21:27 2004 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Wed, 30 Jun 2004 23:21:27 +0200 Subject: ANN: lfm 0.91 Message-ID: <1088630487.19736.8.camel@inigo.katxi.org> Hi out there, after almost 2 years since last public release, tonight I announce the more stable, rock, solid and powerful new version of lfm (v0.91). lfm is a 'midnight commander'-clone written in Python and licensed under GNU Public License. It should work on any UNIX with a modern (n)curses library and Python curses module compiled in. See README file or visit the web page for more information. Download it from: http://www.terra.es/personal7/inigoserna/lfm or if it doesn't show last version (crap of ISP reverse proxy), try this low-bandwidth home server: http://inigo.katxi.org/devel/lfm Of course, all comments, suggestions etc. are welcome. Changes since version 0.9: Version 0.91 ("It rocks... yeah!") - 2004/06/30: + quite stable and robust, doesn't crash + faster + new option: show_dotfiles flag + new option: detach_terminal_at_exec flag: useful f.e. if you want to run elinks as web browser attached to lfm terminal + file associations and applications can be configured in preferences + now each application has only 1 associated program, *breaking old .lfmrc* + perms dialog: users & groups sorted alphabetically + uncompress in other panel + resizing terminal works in lfm, pyview. Be careful with dialogs + columns size eliminated from preferences + 1-panel view redesigned + ESC closes dialogs, not lfm or pyview + Ctrl-D: select bookmark dialog + code reorganized: actions.py, vfs.py + added classifiers to setup.py script Version 0.90 was never publically released Best regards, -- I?igo Serna Katxijasotzaileak -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Esta parte del mensaje est? firmada digitalmente URL: From ralf at brainbot.com Fri Jun 11 06:16:47 2004 From: ralf at brainbot.com (Ralf Schmitt) Date: Fri, 11 Jun 2004 12:16:47 +0200 Subject: sax EntityResolver problem (expat?) References: Message-ID: <86brjqv1ps.fsf@stronzo.brainbot.com> chris writes: > hi, > sax beginner question i must admit: > > i try to filter a simple XHTML document with a standard DTD > declaration ( Transitional//EN" > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">) in it. > sax gives the following error > > >>> xml.sax._exceptions.SAXParseException: :53:8: undefined entity > > which is an   entity. > so i thought i just implement the EntityResolver class and use a local > copy of the DTD > > # ======================== > class XHTMLResolver(xml.sax.handler.EntityResolver, object): > > def resolveEntity(self, publicId, systemId): > return 'http://localhost/xhtml1-transitional.dtd' > > reader = xml.sax.make_parser() > reader.setEntityResolver(XHTMLResolver()) > # ======================== > > problem is, it seems expat does not use this resolver as i get the > same error again. i also tried the following, which is not supported > anyhow: > > reader.setFeature('http://xml.org/sax/features/external-parameter-entities', > True) > >>> xml.sax._exceptions.SAXNotSupportedException: expat does not read > external parameter entities > > is the XHTMLResolver class not the way it should be? or do i have to > set another feature/property? That's the way it works for me. You can also just open() your dtd' files and return an open file handle. Note that when using the above dtd your resolveEntity will be called more than once with different id's. -------------------------------- from xml.sax import saxutils, handler, make_parser, xmlreader class Handler(handler.ContentHandler): def resolveEntity(self, publicid, systemid): print "RESOLVE:", publicid, systemid return open(systemid[systemid.rfind('/')+1:], "rb") def characters(self, s): print repr(s) doc = r'''  ä ''' h = Handler() parser = make_parser() parser.setContentHandler(h) parser.setEntityResolver(h) parser.feed(doc) parser.close() ------- Output: RESOLVE: -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd RESOLVE: -//W3C//ENTITIES Latin 1 for XHTML//EN xhtml-lat1.ent RESOLVE: -//W3C//ENTITIES Symbols for XHTML//EN xhtml-symbol.ent RESOLVE: -//W3C//ENTITIES Special for XHTML//EN xhtml-special.ent u'\n' u'\xa0' u'\xe4' u'\n' > > > ultimately i do not want to use the http://localhost copy but i would > like to read the local file (just with open(...) or something) and go > from there. is that possible? do i have to > > > thanks a lot > chris -- brainbot technologies ag boppstrasse 64 . 55118 mainz . germany fon +49 6131 211639-1 . fax +49 6131 211639-2 http://brainbot.com/ mailto:ralf at brainbot.com From aahz at pythoncraft.com Thu Jun 10 18:24:35 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2004 18:24:35 -0400 Subject: C API for new-style classes References: Message-ID: In article , Eric Wilhelm wrote: > >By new-style classes, I'm referring to the changes which came into 2.2 as >a result of PEP 252 and 253. I discovered this problem when trying to >use the Perl Inline::Python module with a python class that was >inheriting from the new builting 'object' class like so: > >class MyClass(object): > >The problem is in detecting that this class should be treated as a class >from C. With old-style classes, PyClass_Check() returns true, but it >doesn't work with new-style classes. With those, apparently we have to >use PyType_Check(), but I cannot find this in the extension >documentation. > >Another problem comes in identifying instances of this type of >type-class, where PyInstance_Check() no longer returns true. > >Does anyone know of any documentation for the API for new-style classes? >(It must work somehow or the python interpreter couldn't do it.) I'm no expert on this, but since nobody else has stepped up to the plate... New-style classes make things both easier and harder. Fundamentally, there's no longer any difference between a type and an instance -- that's how you get metaclasses that generate classes as their instances. Unfortunately, your best bet is to look at the source of the new builtin objects to see how they work. Let's turn this around a bit: what problem are you trying to solve? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From ville at spammers.com Tue Jun 29 10:03:18 2004 From: ville at spammers.com (Ville Vainio) Date: 29 Jun 2004 17:03:18 +0300 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] Message-ID: Pythonic Nirvana - towards a true Object Oriented Environment ============================================================= IPython (by Francois Pinard) recently (next release - changes are still in CVS) got the basic abilities of a system shell (like bash). Actually, using it as a shell is rather comfortable. This all made me think... Why do we write simple scripts to do simple things? Why do we serialize data to flat text files in order to process them? Everything could be so much simpler and immensely more powerful if we operated on data *directly* - we should operate on objects, lists, dictionaries, functions, not files. We shouldn't write scripts to perform our routines - and way too often, we don't even try, because moving the data between scripts is too troublesome, involving file formats, argv parsing and other tedious stuff. If we use a shell with full Python capabilities, we can introduce new funtionality for integrating our environments very easily. Consider a project framework for managing a software project:: >> import pf >> pf.projects --> [, ] >> p = pf.projects[0] # we want to work with project 'foo' >> headers = Set([f for f in p.files() if f.endswith(".h")]) >> srcs = p.files - headers >> found = Set([f for f in srcs if find_any(f, headers)]) >> r = findradio("kazoo classics")[0] # some diversion needed >> music.play # manipulates our music player >> music.vol 100 # back to work... >> notfound = srcs - found # who has made a header that is not used? >> jackasses = Set([p.author(file) for file in notfound]) Now we have the names of our victims in 'jackasses' variable. We want to make that variable accessible to all in our project team, in a persistent store. We use tab completion to find the databases:: >> export jackasses Completions: "fooproject_db" "barproject_db" "private" Note how tab completions for "export" notices that we are trying to enter the second parameter. It knows that it is the database name, and the completion mechanism (written for export) dynamically queries the list of databases for which we are allowed to export data. After seeing the choices we choose one of them:: >> export jackasses "fooproject_db" name="slackers" Now the list of guys is accessible to everybody. We also compose a volatile email to everybody:: >> xemacs tmp >> for m in [Mail(to=name, bodyfile="tmp") for name in jackasses]: m.send And rat the guys to the management:: >> xemacs tmp2 # mail contents # The following guys have not been doing their jobs: # @("\n".join(jackasses)) >> cont = open(tmp2).read().expand() # runs it through EmPy template expansion system. >> Mail(to=p.boss, body=cont).send Notice how jackasses variable was used inside the mail. We can also schedule some extra hours for the guys to check if their headers are needed, create a cron script to monitor that they have fixed the bugs, etc. The boss might want to fire them at once: >> l = import "slackers" >> [e.fire() for e in Employee(l)] Or the boss might want to do some more extensive firing to invigorate the company:: >> ent = MyEnterprise() Auth needed! Password: ****** >> st = stats(ent.allemployees()) >> avgperf = st.average_performance >> def dead_weight(emp): .. if emp.performance() < avgperf: return True .. return False >> ent.fire_if(dead_weight) Typing all that might seem like a lot of work. However, a lot of it will probably be implemented as functions aggregating the functionality. Most of the lines here could be factored out to a function (note that I didn't say script):: def unused_headers(prj): """ returns the header files that are not used in the project """ ... implementation ... With conventional scripting techniques, nobody would want to do all this. With the pythonic approach, creating this kind of business intelligence is a breeze, eliminating tons of tedious routine! Obviously this all can be done in specific scripts, which start doing the thing "from the start" - open database connections, ask the user to select the project, etc. However, writing such scripts is a lot of work. With the interactive, much more dynamic approach, pieces of functionality can be implemented one by one, and they become usable immediately. I can imagine that for power users and "knowledge workers", this type of system would yield immense power. The payback is also incremental - the whole system grows and gets refactored, streamlining the process. In the end most of it will probably be driven by a simple GUI. Especially the "fire below average employees" function, which should not be run in a yearly cron job - only when needed. Various GUI threads could be running in the same Python process, manipulating the same namespace What needs to be done --------------------- Not surprisingly, "we're not there yet". - IPython needs some refactoring (the codebase isn't quite scalable and extensible enough yet). Francois can use some help. - Flexible persistence system needs to be itengrated. ZODB, perhaps? - Domain specific modules (like project / "employee management" systems) need to be implemented. This luckily mostly writes itself. - Flexible, but easy to use protocols need to be specified for documenting the functions, argument expansion, gui interaction etc. A gui module should display the documentation for the "current" function and possible arguments, so there's no need to press tab at all times. Still, all in all, we're almost there. This has the perhaps same "feel" of tight integration that I imagine the Lisp Macine guys were experiencing, but Python is much more scripting-friendly, community driven and easier to learn. Ergo, world domination. -- Ville Vainio http://tinyurl.com/2prnb From nessus at mit.edu Fri Jun 18 17:41:41 2004 From: nessus at mit.edu (Douglas Alan) Date: Fri, 18 Jun 2004 17:41:41 -0400 Subject: Tkinter and "jumpiness" Message-ID: Is it possible to double-buffer frame rendering with Tkinter? I'm writing a GUI app using Tkinter and the GUI police around here are complaining about the interface being too "jumpy" at times. If I could have the frame rendered offscreen and only put onto the screen once it has completely finished being rendered, then this would solve the problem. One culprit in the jumpiness is a megawidget that I am using that initially displays a scrollbar and then a fraction of a second later removes the scrollbar when it realizes that it is not necessary. To eliminate the jumpiness, I've tried packing all the widgets into the frame before packing the frame into the app, but that doesn't help much. I've noticed, however, that if I pack the frame into the app, unpack the frame (with the forget() method), and then repack it into the app, on the repacking, the frame does not get get rendered in a "jumpy" fashion -- even if the frame is being rendered into a differently-sized area. This suggest that a lot of work is done on the first packing that gets cached somewhere so that it doesn't have to be redone on the repacking. Perhaps then an alternative to double buffering the frame, if that is impossible, would be if I could somehow get the frame to do all of that work that it currently does on the first pack *before* the first pack, so the first pack would display in the manner that subsequent packs do now. |>oug From pwmiller1 at adelphia.net Tue Jun 29 22:33:08 2004 From: pwmiller1 at adelphia.net (Paul Miller) Date: 29 Jun 2004 19:33:08 -0700 Subject: Is this the "right" way to do rexec? Message-ID: <2e363c08.0406291833.28e62e2d@posting.google.com> I came across this recipe on the Python Cookbook site: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286134 As written, it allows evaluation of either constants or more general expressions involving constants and operators (but not function calls). I haven't thoroughly tested it for security, but it at least passes the smoke test. Assuming that this can either be demonstrated to be as secure as the python interpreter itself (i.e. we can't blame the recipe for some hypothetical exploit that targets the Python interpreter), or that testing can demonstrate a reasonable probability that it's secure, would this be a good basis for implementing a restricted execution environment? Pros: It analyzes the Python bytecode itself looking for fishy stuff. This means it should be harder to trick using, for example: del __builtins__;import os ... which would compromise the old rexec. Cons: It's a bytecode hack. Python bytecodes are not guaranteed to be portable across versions of CPython, and it certainly wouldn't work on Jython (although a similar module that analyzes the Java bytecodes might work). The recipe's author gives a hint on how to allow certain types of imports by restricting what can be referenced via the LOAD_NAME opcode. For example, by scanning LOAD_NAME, you could allow importing say, the math and cmath modules, but not os or sys. Or, by going a step further and analyzing LOAD_ATTR opcodes, you could allow selective usage of certain symbols within a module or attributes of a class. You could allow say, read access but not write access to an object's __class__ and __dict__. And, of course, you'd have to do similar things with assignments. Could something like this go into the standard CPython library if it were proved secure enough? From jgilbert+comp.lang.python at uvm.edu Wed Jun 2 19:55:29 2004 From: jgilbert+comp.lang.python at uvm.edu (Josh Gilbert) Date: Wed, 02 Jun 2004 19:55:29 -0400 Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: Mitja wrote: > Rusty Shackleford > (news:slrncbs3d0.9l3.rs at frank.overlook.homelinux.net) wrote: >> Thanks for that explanation -- it really helped. I forgot that O(n) >> can translate into dn + c where d and c are constants. > > ??? > You'd NEVER write, e.g., O(n)=3n+7. What you'd say would be simply O(n)=n. > As already pointed out, this means that complexity (and, with that, > execution time) is PROPORTIONAL to n. It doesn't give you the number of > seconds or something. If, on the other hand, you knew that one program took 3n+7 and another took (n^2) / 10^10 you WOULD say that one's O(n) and the other's O(n^2). This implies that the first one is faster for large data sets. And if you don't care how long it takes for your one-off code to sort a billion elements, insertion sort might be the fastest algorithm you have. Especially if reordering elements is expensive. At which time you'd use a Schwartzian transform. I think the best way to see this stuff is to look toy examples, an exponential algorithm with small constants versus a linear time algorithm with a miserable initial cost. Josh Gilbert. -- http://www.uvm.edu/~jgilbert/public_key.gpg From stephjausiers at yahoo.fr Wed Jun 9 05:21:36 2004 From: stephjausiers at yahoo.fr (steph bagnis) Date: 9 Jun 2004 02:21:36 -0700 Subject: list of tuple Message-ID: <97c5862c.0406090121.2964190e@posting.google.com> Hi ! I'm a new python programmer and I'm searching some tools for working with tuples's list. For example I have a list like that : [('+',4,3),('+',3,9),'('+',5,6),('x',10),('x',3)] and I would like to get a list with just the tuple with index 0 '+' or things like that. The question is : is it possible without doing a loop ? Thx From guettli at thomas-guettler.de Mon Jun 14 10:17:48 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 14 Jun 2004 16:17:48 +0200 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: Am Sun, 13 Jun 2004 00:46:34 -0700 schrieb Kamilche: > I love Python, but I'm less than in love with IDLE. It's OK, but it > really doesn't have enough capabilities. > > What I consider critical, are a popdown listing of all my functions, > colored syntax printing, and a right-click 'definition' context menu > that will hop you to the spot where that keyword is defined, if > possible. Everything else I could learn to do without, but these > features keep me hoping for a better IDE for Python. > > I'm used to the Microsoft Visual C++ debugger, and though tooltip > variable debugging and intellisense were nice, they broke often enough > that you couldn't rely on them anyway, so I don't really need those > features. I use XEmacs but it is more an editor than an IDE. > I would also like the ability to create application 'forms' visually. > I'm on a Windows XP machine. Maybe this helps you: http://gladewin32.sourceforge.net/ Regards, Thomas From christian at mvonessen.de Mon Jun 21 12:11:02 2004 From: christian at mvonessen.de (Christian von Essen) Date: Mon, 21 Jun 2004 18:11:02 +0200 Subject: Listening socket not seen outside of localhost References: <2joev9F134s9fU1@uni-berlin.de> Message-ID: On Mon, 21 Jun 2004 17:59:46 +0200, Diez B. Roggisch wrote: > > What does self._addr look like? Its supposed to be '' and not 'localhost', > otherwise the bind will only bind to the lo-interface. > > Regards, > > Diez It was my hostname, so bind was just to lo-interface - now it's working, thanks a lot Christian From benn at cenix-bioscience.com Thu Jun 24 10:08:55 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 24 Jun 2004 16:08:55 +0200 Subject: Optional use of logging library module In-Reply-To: References: Message-ID: <40DAE077.7040904@cenix-bioscience.com> Eric DeWall wrote: >In trying to clean up the inevitable debug printing littered through some >code, I started reading up on the 'logging' module. Browsing groups >indicates that the design of the module is controversial but personally I'm >very happy to see such a full-featured logger as part of the standard >distribution. Here's my problem though (using 2.3.3) - I'm trying to write >some reusable classes that _optionally_ use the logging module. So a class >might look like: > > > Hello, This is an idea by you could do this : * None or some other ID is passed in (ala the void pattern) as your Logger * The Logger is created as a genuine logger * The logger has propagate set to false to stop messages going upwards * The logger has it's severity level set so that no messages are logged OR, you could do this * None or some other ID is passed in (ala the void pattern) as your Logger * The Logger is created as a genuine logger * A filter is created which simply filters out everything However what I would suggest could be a good solution for you is to always have a logger present and log debug messages as debug and use the other levels for what they are meant for WARNING, ERROR, etc. That way you can easily turn the logger off in the instance you are working with. Yes, OK you take a small speed knock but the speed knock I've had on this is small (I'm not a speed junkie anyways). I also agree with you, a fully featured logger is essential and personally - I'm happy with the design, it's not too complicated you only need to read through the docs and try it out - easy peasy lemon squeezy. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From mynews44 at yahoo.com Tue Jun 1 18:39:32 2004 From: mynews44 at yahoo.com (google account) Date: 1 Jun 2004 15:39:32 -0700 Subject: Could python help to create hundreds of NT accounts ? Message-ID: Not really being a programmer, but thinking that there must be a better way than to do it by hand and havign a friend who likes to tell me that python is the answer to everything I am hoping. I have two NT4 domains, and I need to create instances of all the account names from one in the other. All accounts need to have identical group memberships to each other, and different passwords. I have in mind some program that will automatically generate a password (I already wrote one of those) and write out to a csv file username,passwd thgat we can refer to when the clients need to log into their new account. Because there are about 1600 accounts, I'd really love it if there was a way to do this with a script. I bought the Dietel How to Program Python book in an attempt to learn this language, but it doesn't seem to have much in it related to NT stuff like this. IF anyone has done anything like this, or knows how, I'd love to hear from you. Cha! nemir (at) hot mail dot com From winexpert at hotmail.com Wed Jun 30 08:02:42 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 30 Jun 2004 12:02:42 +0000 Subject: using python with HTML and parameters Message-ID: Hi, In java/jsp I can pass parameters to my python script on a webpage by doing something like this: http://somewhere.org/mypage.jsp?parm1=something&parm2=another How do I do that with python? Also would I need to import a special module so I could grab them off the 'line' (I' m not sure what you call it if its a command line, etc as its coming via a 'get' or 'post' request via HTTP protocol. On the webpage I am building I would like to pass parameters to python. Thanks ! David Stockwell ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From pkk at spth.de Sat Jun 12 07:22:25 2004 From: pkk at spth.de (Philipp Klaus Krause) Date: Sat, 12 Jun 2004 13:22:25 +0200 Subject: [PyOpenGL] How do I save runtime on drawing HUGE polylines (120 000 vertices)? In-Reply-To: References: Message-ID: <2j07bgFrfbigU1@uni-berlin.de> Would glArrays perform much better? Yes. > Or is this a case for > Display Lists? Might be even faster, depending on your driver. Any other idea? Use vertex buffer objects. These should be fastest. Philipp Klaus Krause From insert at spam.here Sat Jun 26 00:30:59 2004 From: insert at spam.here (Doug Holton) Date: Fri, 25 Jun 2004 23:30:59 -0500 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: <10dphkp78g6ne9d@news.supernews.com> References: <10dphkp78g6ne9d@news.supernews.com> Message-ID: John Roth wrote: >>Is there any metaclass trick or something similar to allow anonymous >>code blocks? >> ... > No. If you're looking for GUI callbacks, there's a significant > gap between lambdas and bound methods. You could > use something like (not tested): > > b.OnClick = (lambda : sys.stdout("You clicked me")) Yeah, I didn't mention the lambda option. I was thinking about designing a framework meant for beginners, and I'd rather stay away from lambdas. I'm surprised no one is even proposing support for anonymous code blocks in Python that support multiple lines, similar to what Ruby, Java, and other languages have. > If you're doing anything other than a toy program, though, > the best approach is to wrap the GUI widget in a class, > and use a bound method of that class for the callbacks. Right, that is the subclass example I mentioned in the original note, but I didn't spell it out: class MyButton(Button): def OnClick(self,event): print "you clicked me" b = MyButton() I already know that will work, and that is what I would use myself, and it is more elegant than lambdas. I was just looking to see if anyone had a hack for anonymous code blocks, but thankyou for your help. From peufeu at free.fr Fri Jun 18 17:13:40 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 23:13:40 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: google skunkweb really nice, cool, fast powerful embedded templating engine full power of python (not at all like Zope) persistant database connections are just one function call kicks ass 200 hits/s on small dynamic pages with SQL in them on my machine... on large pages, spits out about 4 MBytes/s of HTML, almost all text in the page except HTML tags coming from the database... all this with caching turned off... brilliant design... kicks PHP ass anytime I even did a photoshop-in-a-webpage stuff with some Javascript & CSS and server-side processing with PIL to allow the user to adjust image contrast and crop images with the mouse... realtime preview with zooming of course... mod_python is really too low level. On Fri, 18 Jun 2004 16:43:46 -0400, Leif K-Brooks wrote: > I'm planning to start on a fairly large web application, most likely > using mod_python. I recently wrote a fairly small (but real-world > useful) web app with it, and all of those req.write()s made for really > ugly code. Would a templating engine solve that? Does anyone have any > suggestions about which one to use? -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From kenneth.m.mcdonald at sbcglobal.net Wed Jun 16 01:18:53 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 16 Jun 2004 05:18:53 GMT Subject: overlapping regex References: Message-ID: In article , km wrote: > Hi all, > > python re module deals with only nonoverlapping matches. how to go for if i want to find out overlapping matches and their span ? > regards, > KM > The easiest way would be to, after you've found a match (using something like the search method of comipiled re's), repeat the search starting one character further along that the start of the previously found match. This strategy may require some adjustment depending on the exact patterns you're using, since you may find you don't want _all_ overlapping patterns, but it should work and I can't think of a better way of doing it. Cheers, Ken From google at g2swaroop.net Wed Jun 16 06:20:59 2004 From: google at g2swaroop.net (Swaroop C H) Date: 16 Jun 2004 03:20:59 -0700 Subject: Learning Python - Resources Needed References: Message-ID: <2f203eb8.0406160220.51f306fa@posting.google.com> Hi, > Can anyone recommend any good books for a someone new to python, and > to programming? I should mention that while I am new, I do catch on > quickly, so I'm not looking for a book that gives just the bare > basics. > > Also, any good web references would be greatly appreciated. Maybe my book 'A Byte of Python' would be helpful for you: http://www.python.g2swaroop.net/ Enjoy, Swaroop From msoulier at digitaltorque.ca._nospam Wed Jun 9 20:51:43 2004 From: msoulier at digitaltorque.ca._nospam (Michael P. Soulier) Date: Thu, 10 Jun 2004 00:51:43 +0000 (UTC) Subject: does python have useless destructors? References: Message-ID: On Wed, 09 Jun 2004 15:00:32 -0700, Donn Cave wrote: > > On the other hand, while we can't completely resolve this > problem, I think the text you quota above errs in trying > to paint it as a non-problem. try..finally is certainly > not a convenient substitute for guaranteed finalization. > The immediate finalization normally supported in Python > is a very powerful, elegant programming feature. For just > the same reasons that automatic control of memory allocation > is powerful and elegant -- memory is one of the resources > your objects use. > > So yes, you can depend on immediate finalization in many > common situations, but you have to accept the liability of > a dependence on reference non-circularity and on the C Python. As soon as I heard about not being able to trust destructors, I was shocked, because I do rely on guaranteed finalization, and I also consider it to be very elegant. If the only situations where I cannot trust it are with Jython, and circular references, then I have no issue. However, consider the code... myfile = open("myfilepath", "w") myfile.write(reallybigbuffer) myfile.close() If the write fails due to a lack of disk space, the exception will prevent the explicit close() from happening. Now, if myfile goes out of scope, I would hope that the file object is destroyed and thus the file is closed, but after reading the python documentation, it seems that the only way to guarantee closure of the file is using the mentioned try/finally construct... try: myfile = open("myfilepath", "w") myfile.write(reallybigbuffer) finally: myfile.close() Also, there is the case of Python not guaranteeing the __del__ method of an object being called if the object is still alive when the process exits. For files, I don't care, since the filehandles will be returned by the OS, but for some external resources, this would be a big issue. FIFOs and shared memory segments, for example. Mike -- Michael P. Soulier The major advances in civilization are processes that all but wreck the societies in which they occur. -- Albert North Whitehead From gsakkis at rutgers.edu Wed Jun 16 12:52:22 2004 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 16 Jun 2004 12:52:22 -0400 Subject: str() for containers Message-ID: <40d07ac6@rutgers.edu> Hi all, I find the string representation behaviour of builtin containers (tuples,lists,dicts) unintuitive in that they don't call recursively str() on their contents (e.g. as in Java) : ########################################### >>> class A(object): >>> def __str__(self): return "a" >>> print A() a >>> print [A()] [<__main__.A object at 0xa1a5c6c>] >>> print map(str,[A()]) ['a'] ########################################### It's even more cumbersome for containers of containers (e.g. lists of dicts, etc.). Of course one can (or should) encapsulate such stuctures in a class and define __str__ to behave as expected, but why not having it by default ? Is there a good reason for this ? George From me at privacy.net Sat Jun 12 08:53:49 2004 From: me at privacy.net (Duncan Booth) Date: 12 Jun 2004 12:53:49 GMT Subject: Anonymous file closing References: <781dd16f.0406111108.6f2e1afd@posting.google.com> Message-ID: surferjeff at gmail.com (Jeff) wrote in news:781dd16f.0406111108.6f2e1afd at posting.google.com: ... >> > text = open(filename, 'r').read() ... >> If you aren't worried about portability, and you are using the C >> implementation of Python then you may find it is closed immediately >> but it is poor practice to depend on it. > > This is true, but I recommend: > > 1. Only use the C implementation of Python, a.k.a. The Implementation. > 2. Depend on the file being closed immediately in this case. If the > authors of the C implementation ever changed this behavior, they would > break *lots* of existing python code, and they would also break one of > the nicest example of how Python just works. > Any existing Python code which depends on the file always being closed here is wrong today. If the read method raises an exception the file will not be closed until the exception traceback object has been cleared and that could be a long time. From mark at pyzine.com Fri Jun 25 11:08:47 2004 From: mark at pyzine.com (Mark) Date: Fri, 25 Jun 2004 11:08:47 -0400 Subject: Python Magazine exists! In-Reply-To: References: Message-ID: <8F0AA41C-C6B9-11D8-890F-000D932A0486@pyzine.com> Hello Ognen, On Jun 25, 2004, at 10:35 AM, Ognen Duzlevski wrote: > I went to see your magazine and it looks pretty nice. However, you do > publish quarterly and in my humble opinion, a > yearly subscription of 49 Euros is crazy. It all comes down to being able to pay the bills now doesn't it. Unlike the "old Py" where authors we now have have significant costs for editing and writing (and the occasional design work as well). We refuse to run a Magazine where we can not compensate authors for writing about Python. We expect that for the next 1 to 2 years we will be publishing at a loss (this is based on our experience with ZopeMag) but that eventually we will break even and (oh god) maybe even make a modest profit. This would be impossible for us to do for less than 49 Euros. But feel free to call us crazy! :-) Cheers, Mark From mudd at vex.net Sat Jun 5 06:04:49 2004 From: mudd at vex.net (John Mudd) Date: 5 Jun 2004 03:04:49 -0700 Subject: jython 2 cpython bridge References: <8dssc.179150$f_5.163363@lakeread01> Message-ID: How about Spiro? http://www.freenet.org.nz/python/spiro/ Randall Smith wrote in message news:<8dssc.179150$f_5.163363 at lakeread01>... > I would like to use a type 4 JDBC driver in my Python program. I > believe I can use in with Jython. Do you know of some way to > communicate between the Jython and Python processes so that the CPython > program can use the Jython JDBC database connection? > > Randall From seefeld at sympatico.ca Thu Jun 24 11:10:32 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 24 Jun 2004 11:10:32 -0400 Subject: debugging extension module Message-ID: <3JFCc.33482$Nz.1732789@news20.bellglobal.com> hi there, I'v trouble debugging an extension module with gdb and I'm wondering whether anybody has suggestions about how to do this. The symptoms of the bug I'm looking for are that depending on some seemingly benign (C/C++) code, the process will seg fault somewhere in the garbage collector's cleanup at the end of the application. Unfortunately gdb doesn't let me step through these functions, so I couldn't have a closer look into what happens. I got the stack trace from a call to glibc's 'backtrace' function from within the seg fault signal handler. What can cause this kind of failure ? How can I debug this ? I tried to prepare a special python installation configured with the '--with-pydebug' option, but may be that's not enough... (I'm running python 2.3.4 in case that matters). Thanks for any help ! Stefan From bart_nessux at hotmail.com Fri Jun 11 13:31:25 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 11 Jun 2004 13:31:25 -0400 Subject: urllib IOError Exception In-Reply-To: References: Message-ID: Bart Nessux wrote: > From the urllib documentation: "If the connection cannot be made, or if > the server returns an error code, the IOError exception is raised. " > > Suppose I have an array of IPs and I want to pass each element of the > array to urllib. Basically, I'm just trying to see how many hosts are > serveing-up Web pages in a certain IP range. Is there a way in which I > can handle the IOError so that the script will continue on to the next > host in the array if the host before isn't running a Web server? Below > is my code: > > def gen_ip_range(): > import urllib > n = 0 > hosts = [] > networks = [] > while n < 254: > n = n + 1 > networks.append("192.168.%s." %(n)) > for network in networks: > h = 0 > while h < 254: > h = h + 1 > hosts.append(network+str(h)) > for host in hosts: > f = urllib.urlopen("http://%s" %host) > print f.read() > f.close() > gen_ip_range() > > Thanks, > Bart I fixed it myself: try: f = urllib2.urlopen("http://%s" %host) except urllib2.URLError: print host, "has no http server on port 80" Anyway to speed this up??? The timeout per host is several minutes. From phil at riverbankcomputing.co.uk Thu Jun 17 19:21:51 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 18 Jun 2004 00:21:51 +0100 Subject: Easiest way to port Python program to PDA In-Reply-To: References: Message-ID: <200406180021.51211.phil@riverbankcomputing.co.uk> On Thursday 17 June 2004 11:40 pm, Jeffrey Barish wrote: > I have been developing a Python program with two intercommunicating > (using sockets) parts, one of which runs on a desktop and the other on > a PDA.??For?ease?of?development,?I?developed?them?both?on?a?desktop.? > Now that I have them working on the desktop, I need to move the part > destined for a PDA to a PDA.??I?had?originally?planned?to?use?a?Sharp > Zaurus because it runs Linux (the OS of my desktop system) and I had > found a Python port that was supposed to be available for that platform > (Riverbank Computing).??Unfortunately,?Riverbank?Computing?just > discontinued their port.??They?refer?interested?parties?to?another?port > (http://www.vanille.de/projects/python.spy), but that site has no code > to download and does not respond to queries.??Accordingly,?I?have?to > conclude that there is no Python port available for the Zaurus so I am > back to square 1. Click on one of the feed location links at the bottom of the page - seems to be plenty of code to download to me. Phil From tismer at stackless.com Fri Jun 25 13:38:51 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 25 Jun 2004 19:38:51 +0200 Subject: Parameterized Functions without Classes In-Reply-To: <20040625171500.GD5959@frobozz> References: <40DC58AB.8080108@stackless.com> <20040625171500.GD5959@frobozz> Message-ID: <40DC632B.9090403@stackless.com> Andrew Bennetts wrote: > Note that even in "ancient times" (i.e. before nested scopes), you could > still do this without classes: > > def _converter(scale): > def convert(arg, scale=scale): > return scale * arg > return convert You probably know that I knew that very well, and I intentially didn't talk about the dark side of Python. Although I did in the past, too, I used the class approach to have cleaner code. -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From donn at drizzle.com Sun Jun 20 00:57:43 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 20 Jun 2004 04:57:43 -0000 Subject: str() for containers References: <40d07ac6@rutgers.edu> <10d8d4696tjkf1b@news.supernews.com> Message-ID: <1087707462.132639@yasure> Quoth "John Roth" : ... | I don't think there's a ***good*** reason. The root of | the issue is that the str() / repr() distinction is too simplistic | for containers. The output of str() is supposed to be human | readable, and the output of repr() is supposed to be able | to round-trip through exec/eval (which is not always possible, | but should be maintained if it is.) That's one way to look at it, but it's a perspective that will always leave you dissatisfied with both str and repr. Not only is repr-as-marshal not always possible, it's very widely not implemented even when it could be, and anyone who relies on this feature is asking for trouble. Human readable is as vacuous an expectation as there could be for what str does, so it's hard to say for sure you'll be disappointed there, but then it's just impossible to imagine any solid basis for saying whether a value is going to be human readable. I've seen what the documentation says, and there has been plenty of discussion about this. The way I see it, __str__ is about conversion to string data. It really applies to only those objects that can naturally be converted to a string. If lists had a __str__ function, then str(list) would be the inverse of list(str), but since that would raise all kinds of questions about what to do with lists containing other things besides strings of length 1, there is no __str__ function. Instead, str(list) calls __repr__. Repr renders the object as a string. Not just the object's value in a computational sense, so to speak, but the object implementation. So it's typically more interesting to a programmer, than the program's user. That could be seen as a human readability issue, but it puts the point into better perspective - what's the user-oriented value of a list as string? There isn't one. Donn Cave, donn at drizzle.com From python-url at phaseit.net Mon Jun 21 18:19:19 2004 From: python-url at phaseit.net (Peter Otten) Date: Mon, 21 Jun 2004 22:19:19 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 21) Message-ID: <10denn7n0eeuk7e@corp.supernews.com> QOTW: "try...except and try...finally are really two completely different statements with different purposes." - Carl Banks "Zope and ZODB do incredibly complex stuff as side effects in what Guido surely thought of as 'tiny hooks'. He had in mind that hasattr() might look for a key in a dict or list, and suppress a harmless KeyError or IndexError, not start World War III and then send an endless sequence of Terminators back in time to change the outcome ." - Tim Peters http://www.zopezen.org/Members/slinkp/Quote.2004-06-03.2651/view The Vancouver Workshop starts at the end of next month; it looks like a good one. Talks must be submitted by tomorrow. http://www.vanpyz.org/conference Fredrik Lundh illustrates an advantage of regular-expression callbacks in a thread that demonstrates, once again, that any advantage Perl has in REs is slight http://groups.google.com/groups?frame=left&th=5bd3ade86905a5fe Mark Hughes concisely summarizes the essentials of clipboard-think in an X context http://groups.google.com/groups?frame=left&th=8deb40e81e5bc214 Batista Facundo tries to achieve immutability with a class written in pure Python. http://groups.google.com/groups?th=b9e8bfb6fc418694 Raoul collects various strategies to connect a textbox and value-checking code. http://groups.google.com/groups?th=8330d1da313519f5 Peter Hansen: "Now that the editor and tab-wars are over..." Ville Vanio: "Do we finally have the official endorsement to burn tab-users at stake?" Style does matter to pythoneers. This is why a change in the style guide cannot go unnoticed for long. http://groups.google.com/groups?th=f4edd746f4d0314c http://www.python.org/peps/pep-0008.html David Stockwell wonders how try...finally and try...except are best combined. http://groups.google.com/groups?th=38706301759dd499 If you are teaching programming, Python is both easy to learn and powerful. NN has made the switch from C++. http://groups.google.com/groups?th=385262e8f3aa1a92 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From jmdeschamps at cvm.qc.ca Wed Jun 9 23:15:33 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 9 Jun 2004 20:15:33 -0700 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfihFq4aunU1@uni-berlin.de> Message-ID: <3d06fae9.0406091915.15f3d216@posting.google.com> "Claudio Grondi" wrote in message news:<2ipfihFq4aunU1 at uni-berlin.de>... > I wonder why the subject (Python scripting within HTML) is not > occuring in any past postings - do I miss something very obvious? > > I try to run Pythons scripting in Windows MSIE 6.0 in the > section, but it doesn't > work at all. > \Python23\Lib\site-packages\win32comext\axscript\client\pyscript_rexec.py > runs ok, registry entries seems also be ok. > I have the latest Python 2.3.4 installed. > What do I wrong? > Runs anyone of you (inspite of the security concerns) successfully > Python as scripting language in Windows MSIE 6.0 HTML pages > using it like JavaScript or VBScript ? > > Thank you in advance for any help. > > Claudio If you mean to script "client-side" than the short answer is no( (IMO). In most browsers you can get a javascript interpreter or some other ECMAscript compliant language (such as VBScript). These language enforce *sandboxing* of web pages in order to protect the client from downloading malicious software within the web page. That is these interpreters cannot directly access the client machine so it can't install modify or delete anything outside this sandbox (generally limited to the memory space of the browser). BUT Python is great for server-side scripting: plain CGI module works just fine, and a plethora of frameworks built around/with/in Python (see http://www.python.org/cgi-bin/moinmoin/WebProgramming), also Python has divfferent socket modules to do it all yourself... Python can also be used in PHP/ASP-like fashion with IIS servers, meaning you can include Python code in HTML pages that IIS will execute on the server before serving that page to the client. Python even as a HTTPserver module that you could use on the client itself - not very performant, but if your the only user of this server (as it lies in a client machine) it should be good enough. Also remember that while Python is free and available, its doesn't necessarily reside on the client machines (and javascript will, within a browser). Have fun! Jean-Marc From msoulier at digitaltorque.ca._nospam Wed Jun 9 16:40:11 2004 From: msoulier at digitaltorque.ca._nospam (Michael P. Soulier) Date: Wed, 9 Jun 2004 20:40:11 +0000 (UTC) Subject: does python have useless destructors? Message-ID: Greetings, I recently had a friend tell me that because the Python spec does not guarantee that an object will necessary be destroyed when all references to it are gone, that desctructors in Python are not reliably called, and thus useless. As I found it difficult to believe that Python would include destructors for apparently no reason, I thought I should ask for clarification here. Can anyone say yay or nay on this issue? I believe his comments stem from a couple of references. http://docs.python.org/ref/customization.html#l2h-174 http://docs.python.org/ref/objects.html#l2h-18 Specifically, this paragraph in the second link: Some objects contain references to ``external'' resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The `try...finally' statement provides a convenient way to do this. So putting a close of some external resource in a destructor would be a bad idea, apparently. As this is the kind of thing I typically use destructors in OO programming for, I found this quite surprising. Regards, Mike -- Michael P. Soulier The major advances in civilization are processes that all but wreck the societies in which they occur. -- Albert North Whitehead From jfdoyon at methane.ca Wed Jun 16 21:11:35 2004 From: jfdoyon at methane.ca (Jean-François Doyon) Date: Wed, 16 Jun 2004 21:11:35 -0400 Subject: Making classes from Metaclasses globally available References: Message-ID: <5d6Ac.34929$7H1.1286929@news20.bellglobal.com> Why? Well, basically I'm looking at writing an IDE of sorts. It should allow the viewing editing of text files. Catch is, said text files are structured much like XML, but they're NOT XML. I want the application to be extensible, and not be stuck to a particular version/schema of this file. So the idea is, create one or more "schemas" to describe what I'm going to be looking for and then parsing. Because the format of said text file is structured in a very XML-like way, I thought it'd make sense to simply dynamically create a tree of objects, which are instances of relevant classes. But because of my statement above I don't know in advance what classes there might be and so on. So I figured I'd use something like MetaClasses to do it. I've got the basic schema parsing and class creation in place already, the problem is that I want to keep the class creation and the parsing fairly seperate. I'm thinking the parsing functionality will be extra polated from the schema also, but be part of the classes (The file structure is consistent enough to allow this I think ...). Anyways, it's not all entirely clear in my mind yet ... But that's the basic idea. But I just want classes created from the schema to be available globally so that when the classes need to interact with each other (More precisely, one instance needs to instanciate another class and make it an attribute of self) I don't need to pass a list of classes or soemthing similar around everywhere. Did that make any sense ? :) Admitedly, I've kind of thought up a way to do it with a unique class ... But I don't like that design as much ... The model I describe above fits really well with the application in question. I've even seen something similar done in PHP with a web interface, though it was much more restricted in it's flexibility and capability to adapt to any kind of schema. Metaclasses seem to open the door to greater flexibility by not having to know ANYTHING in advance. If you're familiar with the generateDS script, I've got something like that in mind, but not for XML. If anyone has a better idea on how to go about this, or knows of tools/examples that implement this kind of scenario, I'd love to hear about it! Thanks, J.F. "Jean-Fran?ois Doyon" wrote in message news:Y%Pzc.26910$7H1.1042748 at news20.bellglobal.com... > Hello, > > I'm using MetaClasses to create classes. > > How do I make these new classes "globally" available? > > I probably just have to assign them to something magic, but I can't seem to > figure out which one. > > if I do: > > MetaClass('Klass', (), {}) > > The resulting class needs to be assigned to something: > > myclass = MetaClass('Klass', (), {}) > > The problem is that I'm looping and don't know in advance how many classes > there will be. > > So right now I have something like: > > msclasses[clsname] = MapServerMetaClass(str(clsname), (), > {'schema':list,'__init__':MapServerClassInit}) > > inside a loop. > > Problem is I really don't want to have the classes stuck inside that dict. > I want them "globally" available as if I had simply made a "class" > declaration at the top of the file. > > Any ideas or suggestions? > > Thanks, > J.F. > > From P at draigBrady.com Wed Jun 16 09:23:05 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Wed, 16 Jun 2004 14:23:05 +0100 Subject: Proper way to kill child processes In-Reply-To: References: Message-ID: <40D049B9.8050604@draigBrady.com> Bob Swerdlow wrote: > My application starts up a number of processes for various purposes using: > self.popen = popen2.Popen3("/usr/local/bin/python -O "myscript.py") > and then shuts them down when appropriate with > os.kill(self.popen.pid, signal.SIGTERM) > Everything works fine on MacOSX. However, I'm doing a port to Solaris (so I > can run it on my web site) and find that the child processes are not > stopping! Solaris is creating TWO new processes: one for the SHELL and then > another started by the shell to run my Python script. The os.kill() is > killing the shell process, not the one running my Python code. > > Actually, I really want to kill both of these processes, but I only have the > pid for the shell process. I cannot kill the whole process group because > that kills the main process, too (I tried it). Try to get the popen2.Popen3() implementation to create it's own process group. You can do this by adding an os.setpgrp() call or maybe you can change the "sh -c" -> "sh -mc" P?draig. From claird at lairds.com Mon Jun 14 09:23:13 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 14 Jun 2004 13:23:13 -0000 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <9hdzc.93679$DG4.801@fe2.columbus.rr.com> Message-ID: <10cr9m1q7tlp4b4@corp.supernews.com> In article <9hdzc.93679$DG4.801 at fe2.columbus.rr.com>, Carl Banks wrote: . . . >(Since when does Perl have an interactive interpretter?) . . . Long time . -- Cameron Laird Business: http://www.Phaseit.net From chuck at smtl.co.uk Mon Jun 7 11:00:13 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Mon, 07 Jun 2004 16:00:13 +0100 Subject: simple script to read and parse mailbox Message-ID: <200406071500.i57F0Deb029958@sevenofnine.smtl.co.uk> Hi again when I try /home/testwwws/Mail/work Mail folder I get the following error sevenofnine:/data/tmp/pythonScriptMail # python getSurveyMail.py Traceback (most recent call last): File "getSurveyMail.py", line 34, in ? fp = open("/home/testwwws/Mail/work") IOError: [Errno 13] Permission denied: '/home/testwwws/Mail/work' sevenofnine:/data/tmp/pythonScriptMail # When I run the script as testwwws sevenofnine:[pythonScriptMail] % python getSurveyMail.py Traceback (most recent call last): File "getSurveyMail.py", line 34, in ? fp = open("/home/testwwws/Mail/work") IOError: [Errno 21] Is a directory sevenofnine:[pythonScriptMail] % So what am I missing as I assumed that /var/spool/Mail/testwwws would generate all the email messages but I only need whats in the work Mail folder created using procmailrc . Cheers Chuck From BELLEMAIL-SA at exponent.com Fri Jun 18 21:03:33 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Fri, 18 Jun 2004 18:03:33 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EE8@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = __peter__ at web.de Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 227 Scanning time = 06/18/2004 18:03:33 Engine/Pattern = 7.000-1004/909 Action taken on message: The attachment document_excel.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From jfabiani at yolo.com Sun Jun 27 10:12:30 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sun, 27 Jun 2004 14:12:30 GMT Subject: suse 9.1 and 64 In-Reply-To: References: Message-ID: John Fabiani wrote: > I have just installed SUSE 9.1 64 and it created a > /usr/lib64/python2.3/. Note the 'lib64' - I'm guessing that my python > is 64 bit. I'm real new to python as I was wondering if someone could > enlighten me on the differences between 32 bit and 64 bit python - at > least as SUSE has set it up? Thanks > John Thank to all for the info. John From beliavsky at aol.com Wed Jun 9 11:20:59 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 9 Jun 2004 08:20:59 -0700 Subject: Python "header" files References: <3064b51d.0406081247.17008d43@posting.google.com> <9rqxc.493$0N1.397@read3.inet.fi> Message-ID: <3064b51d.0406090720.44cdc443@posting.google.com> Timo Virkkala wrote in message news:<9rqxc.493$0N1.397 at read3.inet.fi>... > Probably the most convenient way is to write good docstrings which document > the return values as well, and then generate static documentation from them > with pydoc. > > http://www.python.org/doc/current/lib/module-pydoc.html Thanks to you and others for suggesting pydoc. It easily generates nice HTML. I like the results for my modules that just define functions and classes. For the main programs it actually runs the Python code and does calculations before producing HTML. (Pychecker seems to work the same way). The "DATA" section contains not only the parameters I set but the computed results, which can change every time the program is run, especially for simulations. PyDoc does not seem too helpful to me for documenting the main program. I think the HTML documentation for a main program should have (in addition to the docstrings) the list of modules imported with links to specific functions and variables imported. From eddy at netido.de Sat Jun 5 15:32:03 2004 From: eddy at netido.de (Eddy Ilg) Date: Sat, 5 Jun 2004 21:32:03 +0200 Subject: "intermodule-global" variables Message-ID: <20040605193203.GB32104@myserver1.de> Hi, I am having a problem with an application I am writing: I have 2 scripts called 'conf' and 'build'. Both define a variable named 'root' and import a module named 'helper'. In the helper module I want to access the root variable, that is _either_ in conf _or_ build. How can I do this? I just want the root variable to be global for all modules. (I don't want to put root in helper, since that would make no sense at all) I also tried this: ---- helper.py a=5 def printa(): global a print a ---- >> from helper import * >> a 5 >> a=6 >> a 6 >> printa() 5 Why does this not work? Why are there suddenly two variables a? One for helper.py (stays 5) and a global one (became 6)? This is a bit irritating. Didn't find it in any documentation Thanks Eddy From jfabiani at yolo.com Sat Jun 26 13:10:15 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat, 26 Jun 2004 17:10:15 GMT Subject: suse 9.1 and 64 Message-ID: I have just installed SUSE 9.1 64 and it created a /usr/lib64/python2.3/. Note the 'lib64' - I'm guessing that my python is 64 bit. I'm real new to python as I was wondering if someone could enlighten me on the differences between 32 bit and 64 bit python - at least as SUSE has set it up? Thanks John From greg at cosc.canterbury.ac.nz Sun Jun 20 20:36:56 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 21 Jun 2004 12:36:56 +1200 Subject: ANN: PyGUI 1.4 Message-ID: PyGUI 1.4 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ Highlights of this version: * Image and Pixmap classes added * shrink_wrap method added * some bugs fixed See CHANGES.txt in the distribution for details. What is PyGUI? -------------- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the address above. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From miki.tebeka at zoran.com Wed Jun 2 05:25:48 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 2 Jun 2004 11:25:48 +0200 Subject: Converting Hex to decimal In-Reply-To: <70efe2ee.0406020009.1e1000d6@posting.google.com> References: <70efe2ee.0406020009.1e1000d6@posting.google.com> Message-ID: <20040602092547.GG2240@zoran.com> Hello Dean, > Each hex character is 8 bits. I would like to convert one byte at the > time and pipe the converted data into a new file. This is not tested but should be in the lines of what you're trying to do: from array import array a = array("B") a.fromstring(open("input_file", "rb").read()) # Read all file out = open("output_file", "wb") for bit in a: new_bit = convert(bit) out.write(new_bit) HTH. -- ------------------------------------------------------------------------- Miki Tebeka http://tebeka.web1000.com The only difference between children and adults is the price of the toys. From vincent at visualtrans.de Mon Jun 28 16:47:30 2004 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 28 Jun 2004 22:47:30 +0200 Subject: iterator support (in ext. module) In-Reply-To: <2ka51gF19her1U1@uni-berlin.de> References: <2ka51gF19her1U1@uni-berlin.de> Message-ID: Helmut Jarausch wrote: > Hi, > > sorry for the questions but I'm not sure I understand the > C_API docu. > > In an own extension module I have a new type called Hitlist, > which has the methods 'first', 'last', 'next' and 'previous'. > Now I'd like to support iterating on this type, e.g. like > > HL= Hitlist(...) > for Rcd in HL: > > and also > > for Rcd in HL.reverse() : > > What do I need to implement to get that functionality? > Unfortunately the chapter 10.8 'Supporting the Iterator Protocol' of the > (devel) docu seems to be empty. > > What should PyTypeObject.tp_iter be set to? Can I just return 'self' > and is PyTypeObject.tp_iternext an alias for my 'next' method? > > Does a call to 'PyTypeObject.tp_iter' reset the iterator s.t. > 'tp_iternext' returns the first object when called afterwards? > > Many thanks for your help, > Helmut. > > (P.S. I'm using Version 2.4 -cvs) > Maybe digging into the iterator PEP at http://www.python.org/peps/pep-0234.html provides more info? In addition, you might want to look at the source of an object that uses the iterator protocol. PyDictIter_Type in dictobject.c for example. HTH, -- Vincent Wehren From has.temp2 at virgin.net Wed Jun 2 10:15:33 2004 From: has.temp2 at virgin.net (has) Date: 2 Jun 2004 07:15:33 -0700 Subject: Need help resolving accidental (honest!) language pissing match Message-ID: <69cbbef2.0406020615.7540ad0@posting.google.com> Careless talk costs lives, as they say. In my case, a throwaway comment that Python could trounce the notoriously underpowered and undersupported AppleScript language for "serious number crunching". (And Perl could beat Python, and Fortran could kick all their butts, etc...) Well, you'd think me and the other guy would be old enough to know better, or at least have more important things to do, but nooooo... Ah well, too late now: honour is at stake, and honour must - I say, MUST - be upheld!!! Unfortunately for me, my math is utterly shot and I'm not really up on Python's module support in this field either (poked briefly at numarray, but that's about it), so I'm far too stupid and incompetent to do it all by myself. :p Here's the problem and code: "Suppose I want to study a random walk. Say I would like to appreciate the distribution of the presence of the walker." set n to 1000000 -- we'll be talking about 4 MB set x to randomarray n range {-1, 1} -- n random draws set x to runningsum x -- the cumulative sums of the draws set {mean:the_mean, stdev:the_stdev} to statlist x -- compute stats All the real work here's being done by a C-based scripting addition (plugin), taking about a second on a G4/867. If the worst comes to the worst, I can force a dishonorable draw simply by calling the same scripting addition via MacPython's Carbon support modules, but I'd really like to punt the blighter out of the ballpark so existing C-based Python extensions, Python-to-Fortran bridges, etc. are all okay by me if anyone has a few minutes and spot of sympathy to point us in the right direction. Cheers! :) From skip at pobox.com Wed Jun 30 15:05:22 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 30 Jun 2004 14:05:22 -0500 Subject: finding the same package in multiple places Message-ID: <16611.3826.414123.248350@montanaro.dyndns.org> At work we have a package structure for our homegrown code. Developers each have their own sandboxes where they work on the stuff they are responsible for (mixtures of C++ libraries, SWIG wrappers and pure Python packages). We're running into a problem where we have two versions of the main package, one in the developer's sandbox that contains just the developer's bits and one in the central location which contains all the installed stuff. We're running into problems because the search for a module within a package stops when the first instance of the top level package is found. I don't know of a good way to work around this problem. I've cooked up a scheme involving symlinks, but that's a very bad hack. I'd like something cleaner. Let me make it more concrete. We have a central package, call it "central". Inside that package are three subpackages, "a", "b" and "c". Imports thus look like import central.a from central import b from central.c import foo Now suppose I need to work on subpackage c. If I create a local package called "central" and install my working copy of "c" there, athen adjust PYTHONPATH accordingly, I can't import "central.a" or "central.b" any longer because the search for them ends when the developer's local version of "central" is encountered. For various reasons our sandbox directory doesn't have the same structure as the installation directory, so I actually have to "install" stuff in my local sandbox to get the proper directory structure. Even if that wasn't the case, most developers don't need or want to build all the C++ and SWIG stuff anyway. Any ideas would be greatly appreciated (import hooks that cause the search for a package's submodules and subpackages to continue beyond the first occurrence of the package would be especially welcome). Thanks, Skip From michele.simionato at poste.it Thu Jun 10 01:38:22 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 9 Jun 2004 22:38:22 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Message-ID: <95aa1afa.0406092138.338568b2@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0406091457.6c5ffaec at posting.google.com>... > If there are tricks in Lisp to intercept "if", "setq", etc. I'd like > to know. Same if these limitations are specific to some particular > implementations of Lisp. I greatly suspect that these limitations of > Lisp are general, since Lisp does not naturally have prototype-based > scopes like onion-skins, and overriding things like "if" could more > easily create havoc. > > regards, > > Hung Jung Sorry for the previous message, but I couldn't resist the temptation to mock you. So you may realize how irritating certain statements can be. BTW, for the sake of other interested readers, I will point out that in Lisp you can just wrap you code in a macro, and the macro can do *everything* on the source code. Including replacing all your "if" and "setq" with custom version of them. So practically you get what you want. It is also explicit, since only the "if" and "setq" in the code inside the macro will be redefined, instead of magically change the global meaning of your basic language, which maybe is not such a good idea. Michele Simionato From me at privacy.net Thu Jun 24 09:17:26 2004 From: me at privacy.net (Duncan Booth) Date: 24 Jun 2004 13:17:26 GMT Subject: Python Color Printing References: <889cbba0.0406240136.3a735356@posting.google.com> Message-ID: klachemin at home.com (Kamilche) wrote in news:889cbba0.0406240136.3a735356 at posting.google.com: > I'm pretty desperate to get color syntax printing. I just tried out > the evaluation version of 'Komodo', which several people in here > suggested, and its print features are terrible. The text is coming out > huge when I print at 8 point, tiny when I'm printing at 14 point (so > tiny that it looks like subscripts), the margins are reset at random, > and so on. Plus it doesn't recognize all my fonts. > > I don't care if the pretty printer is in an IDE. I just want color > printing with headers and footers! And I wanted it automated - I don't > want to have to print each one by hand, I want to start them all > printing and walk away. It has to be able to print in larger fonts > reliably, because 10 point is too small for my computer-weary eyes. > > Does anyone have any suggestions? > > --Kamilche Try SciTE which can be downloaded free from http://www.scintilla.org It will print[*] any of its supported languages in colour, or can export to HTML, Rtf, Pdf &c. The latest versions are scriptable (in Lua) so you should be able to automate the process if you really have that many files. Headers, footers, and fonts are all configurable through properties files (and I expect configurable from scripts as well). [*] Direct printing only works on windows, on other platforms you can convert to pdf or html and print that. From jbperez808 at yahoo.com Sun Jun 13 12:20:43 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Mon, 14 Jun 2004 00:20:43 +0800 Subject: dropping into the debugger on an exception In-Reply-To: <2inqlrFp53m5U1@uni-berlin.de> References: <2inqlrFp53m5U1@uni-berlin.de> Message-ID: <2j3cp3Ft3dpdU1@uni-berlin.de> Thanks everyone, for taking the time out to answer... Hopefully pdb operation can one day be as simple and straightforward as with other debuggers. Run pdb, invoke a script from it, and have it remain within pdb when an exception happens. From selwyn at aotearoa.is.home.nz Thu Jun 17 02:23:46 2004 From: selwyn at aotearoa.is.home.nz (selwyn) Date: Thu, 17 Jun 2004 18:23:46 +1200 Subject: cross-tabulation pointers In-Reply-To: References: Message-ID: many thanks! John Hunter wrote: >>>>>>"selwyn" == selwyn writes: > > > selwyn> hi there, I would like some pointers on a pythonesque way > selwyn> of cross-tabulating an SQL result set. > > Supposing your results are a row of dicts > > results = ( > {'dept' : 'hr', 'gender' : 'm'}, > {'dept' : 'hr', 'gender' : 'f'}, > {'dept' : 'sales', 'gender' : 'm'}, > {'dept' : 'sales', 'gender' : 'm'}, > ) > > count = {} > for row in results: > dept = row['dept'] > if row['gender']=='m': ind = 0 > else: ind = 1 > count.setdefault(dept, [0,0])[ind] += 1 > > print count > From peter at engcorp.com Mon Jun 7 21:48:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jun 2004 21:48:20 -0400 Subject: Catching a traceback In-Reply-To: References: Message-ID: EAS wrote: > I'm wondering if there is any way to keep a program running when it runs > into an error (using the 'try' structure) and print the traceback to the > screen? I'm guessing about what you want, because it's not really clear. If I'm right about what you want, it's not possible. Basically, once an exception is raised by the failing code, the code that was executing cannot be continued (as I think you mean by "keep a program running"). If the exception was raised in very low level code, but was not caught by any 'except' statement, the program will terminate with an error message, as you no doubt know. Even if you put a "default" try/except around the very top of the program, all you are doing is catching the exception just before it exits. If the rest of the program was not designed to restart in any way, that's it. It's done. No "keep it running". You can, of course, catch any exception at any level and print tracebacks. In fact, if this is really what you were focusing on, then the answer to your question might be "yes". If you can write the code so that it does catch an exception at the right place to allow safe continuation, then you can certainly keep your program running, and many people use exceptions in exactly that way. -Peter From mrjean1 at comcast.net Tue Jun 15 16:05:28 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Tue, 15 Jun 2004 20:05:28 GMT Subject: Hide module function definitions References: Message-ID: <150620041316144637%mrjean1@comcast.net> There are two options: 1) Explicitly list the functions, classes, etc. to be exported by the module in a list called __all__ inside the module. 2) Start the names of functions, classes, etc. private to the module with an underscore character. /Jean Brouwers ProphICy Semiconductor, Inc. In article , Raymond Tinsel wrote: > Hello all, > > I know this must be a newbie question, but I haven't found the solution in > the tutorials I have read. > > For a dSPACE/Controldesk application I am defining several of my own > modules. > In those modules I also have function definitions of functions I only use in > that module. > Is it possible to hide these functions when somebody would use "import > mymodule"? > > Thanks in advance! > > - Raymond > > P.S.: Any links to usefull documentation regarding Python (or Python for > dSPACE in specific) would also be greatly appreciated! > > From taj at kde.org Wed Jun 16 07:48:31 2004 From: taj at kde.org (taj at kde.org) Date: Wed, 16 Jun 2004 21:48:31 +1000 Subject: Here is the document Message-ID: Please read the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: document_full.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From boris.boutillier at arteris.net Mon Jun 14 10:01:22 2004 From: boris.boutillier at arteris.net (Boris Boutillier) Date: Mon, 14 Jun 2004 16:01:22 +0200 Subject: wxPython online documentation is no more accessible Message-ID: Anyone know where to find it now ? Online doc link is broken : http://www.wxpython.org/onlinedocs.php Boris From chuck at smtl.co.uk Tue Jun 8 10:48:56 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 15:48:56 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Tue, 08 Jun 2004 09:18:01 GMT." References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> Message-ID: <200406081448.i58Emueb000221@sevenofnine.smtl.co.uk> Nice One I was thinking I was going mad at home this works . But $ less /var/spool/mail/chuck produced no output. I use scan+ to check and go thru users email folder . i.e cd /home/User/Mail/Inbox say spam Folder > scan +Lottery > show 1 example below: chuck at sevenofnine:~/pythonScript> cd /home/chuck/Mail chuck at sevenofnine:~/Mail> ls :0 Chuck drafts Inbox mhnjVMtAk pete post2ic2cT post57nXqr postG9QD2D postW78Qle Root spam Beth chucksMail from mbox Operator Pete post2iybnf post8ReyCU posthArGZR postz5FN1w rootMail trash chuck context inbox mhn9VVBQf outbox Pick6 post4XPUvv postc6DZgu postnnglMC Rhys sent-mail chuck at sevenofnine:~/Mail> scan +spam 1 06/08 Woolwich Internet Attention aII Woolwich clients.< show 1 (Message spam:1) part 1 text/plain Does this explain my delemour.We use procmail , fetchmail and sendmail Cheers From peter at engcorp.com Wed Jun 2 15:20:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jun 2004 15:20:36 -0400 Subject: Adding objects to __builtins__ In-Reply-To: References: Message-ID: Matteo Merli wrote: > is there a way to save objects in the __builtins__ namespace? > the goal is to make them available in all the modules of my app, without > reimporting all the things and keep references... > > The curious thing is that when i try from the interactive interpreter the > thing just works: Does this help? >>> import __builtins__ Traceback (most recent call last): File "", line 1, in ? ImportError: No module named __builtins__ >>> import __builtin__ By the way, you *really* shouldn't use this as a "convenient" way of getting global variables or other things around to your various modules. That would be almost the worst thing for code maintainability that you could do. You'll come to hate yourself for doing it, down the road. There are some valid use cases for doing such a thing, but sticking just any old function in there is not it. -Peter From elbertlev at hotmail.com Thu Jun 24 09:37:44 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 24 Jun 2004 06:37:44 -0700 Subject: Private/public module members Message-ID: <9418be08.0406240537.6404a96@posting.google.com> Hi, all! In accordance with Python documentation, there are 2 ways to hide data/methods inside the module (make them private): 1. have "public" members defined in __all__ list 2. start "private" members names with underscore. Both methods for some reason "behave strange". Here are 2 modules and the output: #file: main.py ######################## import foo print dir(foo) foo.b() foo._c() foo.a() #file: foo.py###################### import sys __all__ = ["a"] _private = 56 def b(): print 'b' def _c(): print '_c' def a(): print 'a' Run main.py and here is the output: ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '_c', '_private', 'a', 'b', 'sys'] b _c a Not only doc(foo) has '_c', '_private' and 'b', but one can call them from outside the module. It this "by design"? From dkturner at telkomsa.net Fri Jun 11 03:57:37 2004 From: dkturner at telkomsa.net (David Turner) Date: 11 Jun 2004 00:57:37 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Peter Hansen wrote in message news:... > Roger Binns wrote: > > > The correct answer of course is that the object itself > > should be aware that it needs to be disposed of and that > > real world resources can leak if it isn't. > > > > Which brings us back in a full loop. Currently objects > > signify that they need disposing by having a destructor. > > Why not "fix" that mechanism? > > Very likely the answer is "Because nobody has yet proposed > a workable solution to the several conflicting requirements". > > Do _you_ have a solution? If you do and it really works, > it seems to me unlikely it would be ignored... > How about this: ----- 1. Objects of classes that declare a __del__ method shall be referred to as "deterministic" objects. Such objects shall have a reference count associated with. The reference count shall be incremented atomically each time an additional reference to the object is created. The reference count shall be decremented each time a name referring to the object is deleted explicitly. Except in the situation described in (2) below, the reference count shall be decremented each time a name referring to the object becomes inaccessible due to the set of locals to which the name belongs becoming inaccessible. 2. Where an exception is raised from a suite which contains deterministic locals, the stack traceback shall contain only weak references to said locals. However, the reference counts of deterministic locals shall not be decreased until the path of execution leaves the "except:" block that handles the exception. When this occurs, the deterministic locals shall be unreferenced, starting at the deepest level of the traceback, and ending at most shallow level of the traceback, with the most recently created objects at each level being unreferenced first. 3. When the reference count of a deterministic object reaches zero, the __del__ method of the object shall be called. ----- This will be a pain for the Jython implementers. However, it is doable. Note that I never said the objects couldn't be garbage collected, just that __del__ had to be called at certain well-defined times. What this will involve is the Jython compiler inserting a lot of implicit try/finally constructs. Can anyone see a reason why this scheme wouldn't work? Regards David Turner From qrczak at knm.org.pl Tue Jun 15 08:22:32 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 15 Jun 2004 14:22:32 +0200 Subject: does python have useless destructors? References: <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: On Tue, 15 Jun 2004 04:26:07 -0700, David Turner wrote: > Hmm... I wonder if it would be possible to override the "=" > operator...? No, and it would not be enough anyway. You would have to catch places when an argument is passed to a function, or is returned, or when a local variable goes out of scope, or when an object is put in a container, or perhaps others that I forgot. It's impractical. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From davecook at nowhere.net Tue Jun 29 01:04:45 2004 From: davecook at nowhere.net (David Cook) Date: Tue, 29 Jun 2004 05:04:45 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: XEmacs. Powerful python mode, error message "hyperlinks", buffer tabs. There's also python shell that I never seem to use. The downside for me is that the heavy use of Ctrl and Meta keys can be bothersome on some keyboards (e.g. Apple Powerbooks with their small and poorly placed Ctrl key). Dave Cook From peufeu at free.fr Fri Jun 18 04:52:00 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 10:52:00 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: > 2) Evaluate the default expression once at each call time when the > default > value is needed. The default expression would be evaluated in the > context > of the function definition (like a closure). I like Choice 2 because I've always wanted to do the following : def func( x, y=2*x ): do stuff... ie. use default values for function parameters which depend on previous function parameters. This can be very practical at times : before (suppose 'info' is a class which has "text" and "htmlclass" as members): def format_information( info, htmlclass = None ): if htmlclass == None: htmlclass = info.htmlclass return "

    %s

    " % (htmlclass, info.text ) after: def format_information( info, htmlclass = info.htmlcass ): return "

    %s

    " % (htmlclass, info.text ) the intended use would be : format_information( info ) format_information( info, 'red_text' ) overrides the html_class in info. The former example could be simplified (below) but I still think the second example using your choice 2 is more elegant. def format_information( info, htmlclass = None ): return "

    %s

    " % (htmlclass or info.htmlclass, info.text ) -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From eamonn_sullivan at blueyonder.co.uk Fri Jun 11 17:01:10 2004 From: eamonn_sullivan at blueyonder.co.uk (Eamonn Sullivan) Date: 11 Jun 2004 14:01:10 -0700 Subject: A faster way of finding historical highs/lows References: <47e15340.0406110356.3629d3e6@posting.google.com> Message-ID: <47e15340.0406111301.6cf1b3f1@posting.google.com> Peter Hansen wrote in message news:... > Eamonn Sullivan wrote: > > > 1. Find the most recent date when there was an equal or higher (or > > lower) value than X. > > The fastest algorithm might depend on how you use the data, as well. > For example, do you update the data often, and search it rarely, > or update it rarely and do the search very often? If searching > many times between updates, some preprocessing will likely make things > go much faster. > > Both of your examples sound to me like they would benefit by > using sort(), then a binary search. Sort is very fast relative > to things like the Python loops you are doing, so using it to > prepare the data before the search can be a good step. > > -Peter Thanks for this. At the moment, the software answers a few questions (highest/lowest, longest streak, etc.) once per retrieval of data. The database retrieval, though, is *by far* the biggest time sapper, so a little preprocessing would be almost unnoticeable in comparison, probably (depends on how much, of course). So, I'm guessing I could sort on the particular price field I'm using (decorate-sort-undecorate), and then just find the most recent date among the subset of data that meets the criteria (higher or lower). Is that what you mean? By binary search, do you mean further reorganizing the data into a binary tree using date? From winexpert at hotmail.com Wed Jun 30 11:08:16 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 30 Jun 2004 15:08:16 +0000 Subject: how to do html parms with python Message-ID: I screwed up the subject header on my last one.... sorry folks. Peter, Thanks for the information. I'm not sure if i'm using cgi or pure python but I'll try both approaches and see what i'm using. Thanks David -------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com >------------------------------ > >Message: 10 >Date: Wed, 30 Jun 2004 15:35:53 +0200 >From: Peter Maas >Subject: Re: using python with HTML and parameters >To: python-list at python.org >Message-ID: >Content-Type: text/plain; charset=us-ascii; format=flowed > >David Stockwell schrieb: > > > In java/jsp I can pass parameters to my python script on a webpage by > > doing something like this: > > > > http://somewhere.org/mypage.jsp?parm1=something&parm2=another > > > > How do I do that with python? > >If your Python Script uses CGI it's > >http://somewhere.org/mypage.py?parm1=something&parm2=another > >:) You have to parse the query string with cgi.parse(). > >Mit freundlichen Gruessen, > >Peter Maas > >-- >------------------------------------------------------------------- >Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') >------------------------------------------------------------------- > > >------------------------------ > >Message: 11 >Date: Wed, 30 Jun 2004 15:38:07 +0200 >From: Peter Maas >Subject: Re: using python with HTML and parameters >To: python-list at python.org >Message-ID: >Content-Type: text/plain; charset=us-ascii; format=flowed > >Peter Maas schrieb: > > If your Python Script uses CGI it's > > > > http://somewhere.org/mypage.py?parm1=something&parm2=another > >Correction: this URL does not depend on CGI, only the Python code. > >Mit freundlichen Gruessen, > >Peter Maas > >-- >------------------------------------------------------------------- >Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') >------------------------------------------------------------------- > > _________________________________________________________________ MSN Movies - Trailers, showtimes, DVD's, and the latest news from Hollywood! http://movies.msn.click-url.com/go/onm00200509ave/direct/01/ From davidf at sjsoft.com Fri Jun 25 02:41:22 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 25 Jun 2004 08:41:22 +0200 Subject: question about cx_Oracle .thanks In-Reply-To: References: Message-ID: coolmenu wrote: > Hi > i hava a db ORACLE 10G,a table valid_card > (card_no,varchar2(10),now_balance number (12,2)) > > its'some record in table ('7188','42055.66') > > i use cx_Oracle to select now_balance from table > > curobj.execute("select loan_amount from valid_card where > card_no='7181930166881974'"); > [] > >>>>tuple=curobj.fetchone() >>>>tuple > > (42505.660000000003) > > why 42505.66---->42505.6600000000003??? > thanks This is because of the conversion of the float to decimal. Float objects have limited accuracy. I don't think it's much to do with cx_Oracle David From c_g at cogeco.ca Thu Jun 3 22:16:12 2004 From: c_g at cogeco.ca (chris grebeldinger) Date: Thu, 03 Jun 2004 22:16:12 -0400 Subject: Indirect Memory Addressing References: <_8qdnfMDOq9HKyLdRVn-jg@comcast.com> Message-ID: It may be overkill, but I've used ctypes for this sort of thing with great success: http://starship.python.net/crew/theller/ctypes/ Larry Bates wrote: > I need to call a function in a vendor supplied > Windows .DLL file that returns an address that > points to a list of longs. I am able to call > the function and get back the pointer (by > using membuf). Now I need to know how to get > to the data that is pointed to by the address. > > from dynwin.windll import membuf > abuf=membuf(4*"\x00) > . > . Make call to my .DLL function here > . > address=abuf.read() > > > address contains memory address that points > to the first entry in my list of longs, but > I don't know how to read the contents of that > address (something like peek). > > Thanks in advance, > Regards, > Larry Bates > Syscon, Inc. From User at invalid.domain Fri Jun 18 08:11:02 2004 From: User at invalid.domain (User At) Date: Fri, 18 Jun 2004 14:11:02 +0200 Subject: Pid Message-ID: How can I get a pid of a proccess and get output something similar to 'pidof'? ++++++++++++++++++++++++++++++ /sbin/pidof /usr/sbin/httpd 5802 5135 5131 2584 2581 2509 ++++++++++++++++++++++++++++++ From hank at nicht-prosysplus-schpamme.com Fri Jun 25 08:38:09 2004 From: hank at nicht-prosysplus-schpamme.com (Hank Fay) Date: Fri, 25 Jun 2004 08:38:09 -0400 Subject: IDE's and wxPython widgets References: Message-ID: <10do75dnc4r1501@corp.supernews.com> a) don't know b) Check out Dabo (http://www.dabodev.com), which is very new, but is already on track to creating a full-featured development IDE. The developers are both from the Visual FoxPro world, where working with a development IDE is 12-years along in development, and which has always been pragmatic and community-driven. It appears they are working to create an IDE/development environment that does not leave them disappointed compared to their previous working environment. Hank Fay -- "USCode" wrote in message news:CQKCc.29431$Yb1.213 at nwrddc02.gnilink.net... > Hello > Do any of the wxPython IDE's available support *all* the widgets currently > available with wxPython? > Also, is there one IDE in particular that stands out as superior to the > others in support of wxPython? > Thanks! > > From chuck.amadi at ntlworld.com Sat Jun 5 10:27:36 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sat, 05 Jun 2004 15:27:36 +0100 Subject: simple script to read and parse mailbox Message-ID: <40C1D858.3060106@ntlworld.com> Hi , Im trying to parse a specific users mailbox (testwwws) and output the body of the messages to a file ,that file will then be loaded into a PostGresql DB at some point . I have read the email posts and been advised to use the email Module and mailbox Module. The blurb from a memeber of this list . Im not at work at the moment So I cant test this out , but if someone could take a look and check that im on the write track as this Monday I need to show my Boss and get the body data out of the user's mailbox. **Blurb form a member who's directed me** Thus started with the mailbox and email modules. Mailbox lets you iterate over a mailbox yielding individual messages of type email. The e-mail object lets you parse and operate on the message components. From there you should be able to extract your data. ## The email messages is read as flat text form a file or other source, ##the text is parsed to produce the object structure of the email message. #!/usr/bon/env python import mboxutils import mailbox import email import sys import os import rfc822 import StringIO import email.Parser import types # email package for managing email messages # Open Users Mailbox # class Message() #mbox = mailbox.UnixMailbox(open("/var/spool/mail/chucka")) def main(): # The Directory that will contain the Survey Results dir = "/tmp/SurveyResults/" # The Web Survey User Inbox # Mailbox /home/testwwws/Mail/inbox maildir = "/home/testwwws/Mail/inbox" for file in os.listdir(maildir): print os.path.join(maildir, file) fp = open(os.path.join(maildir, file), "rb") p = email.Parser.Parser() msg = p.parse(fp) fp.close() #print msg.get("From") #print msg.get("Content-Type") counter = 1 for part in msg.walk(): if part.get_main_type() == 'multipart': continue filename = part.get_param("name") if filename==None: filename = "part-%i" % counter counter += 1 fp = open(os.path.join(dir, filename), 'wb') print os.path.join(dir, filename) fp.write(part.get_payload(decode=1)) fp.close() if __name__ == '__main__': main() Cheers all this list has been very helpful. From fredrik at pythonware.com Fri Jun 18 13:10:01 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Jun 2004 19:10:01 +0200 Subject: How to use a palette? References: Message-ID: Antoon Pardon wrote: > Is it possible to know how many colors are in a palette get the histogram, and count the number of non-zero bins (len(filter(None, im.histogram())) usually does the trick). > and which ones? quickest solution: resize the image to (256, 1), convert to RGB, and use getpixel((i, 0)) to get the color for color index i. lut = im.resize((256, 1)).convert("RGB") print lut.getpixel((0, 0)) # get color #0 or use getdata() to get an array of color indices: lut = im.resize((256, 1)).convert("RGB").getdata() print lut[i] From fiedzia at fiedzia.prv.pl Sat Jun 26 10:41:06 2004 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Sat, 26 Jun 2004 16:41:06 +0200 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <20040626144106.6387.0.NOFFLE@fiedzia.homeip.net> Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. Eric3 - most powerfull python IDE with number of features. -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl Inquiring gnomes want to mine! From fishboy at SPAMredSPAMpeanutSPAM.com Wed Jun 16 21:14:25 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Thu, 17 Jun 2004 01:14:25 GMT Subject: Robot References: <81a41dd.0406161319.1ec68dbb@posting.google.com> Message-ID: <843c4vaso3.fsf@redpeanut.com> export at hope.cz (Lad) writes: > Does anyone know about a script that can walk through webpages and > extract an information from these web sites according to given > keyword(s)? > Thanks for reply webchecker.py in the Tools/ directory will walk a web site. Might be a good place to start. ><{{{*> From esj at harvee.org Tue Jun 22 14:44:27 2004 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 22 Jun 2004 14:44:27 -0400 Subject: profiling and performance of shelves Message-ID: was profiling some of my code trying to figure out just why it was running slow and I discovered that shelves containing dictionaries were significantly slower than those containing simple tuples. for example, on a Pentium III/600 MHz machine the code below ran in 1.12 seconds but when I substituted a simple tuple for the shelf, it ran significantly faster (0.13 seconds). I'm confused as to why shelving dictionaries (all elements textual) should take so much longer is the pickel process that complex?. ----- test framework ----- #!/usr/bin/python import sys development_path = "/usr/local/camram/modules" sys.path.insert(1,development_path) import dbm_utils import camram_utils import configuration #set the local context config_data = configuration.configuration("esj") def main(): # wrapper for shelf which also includes locking, file creation etc. # returns object derived from type shelve. spamtrap_cache = camram_utils.message_cache( configuration_data = config_data) cnt =0 x = 0 # test code. Don't use without adding filename to message_cache ## while x<500: ## spamtrap_cache[str(x)]=(x,"const string") ## x=x+1 for i in spamtrap_cache.keys(): token = spamtrap_cache[i] cnt=cnt+1 print cnt print token import profile profile.run('main()', '/tmp/speed') import pstats stats = pstats.Stats('/tmp/speed') stats.strip_dirs().sort_stats('cumulative').print_stats() stats.print_callees() ---- profile output Tue Jun 22 14:25:48 2004 /tmp/speed 12479 function calls in 1.120 CPU seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 1.120 1.120 :1(?) 1 0.000 0.000 1.120 1.120 profile:0(main()) 1 0.030 0.030 1.120 1.120 speed.py:13(main) 566 0.960 0.002 1.080 0.002 shelve.py:69(__getitem__) 11887 0.120 0.000 0.120 0.000 :0(?) 1 0.010 0.010 0.010 0.010 shelve.py:55(keys) 2 0.000 0.000 0.000 0.000 posixpath.py:362(normpath) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 0.000 0.000 shelve.py:82(close) 1 0.000 0.000 0.000 0.000 whichdb.py:5(whichdb) 1 0.000 0.000 0.000 0.000 anydbm.py:69(open) 2 0.000 0.000 0.000 0.000 configuration.py:294(__getitem__) 2 0.000 0.000 0.000 0.000 configuration.py:355(path_process) 1 0.000 0.000 0.000 0.000 dbm_utils.py:53(bias_anydbm) 1 0.000 0.000 0.000 0.000 shelve.py:52(__init__) 1 0.000 0.000 0.000 0.000 dbm_utils.py:359(__init__) 2 0.000 0.000 0.000 0.000 configuration.py:80(base_pathname) 2 0.000 0.000 0.000 0.000 posixpath.py:299(expanduser) 1 0.000 0.000 0.000 0.000 portalocker.py:68(lock) 1 0.000 0.000 0.000 0.000 shelve.py:89(__del__) 1 0.000 0.000 0.000 0.000 camram_utils.py:329(close) 2 0.000 0.000 0.000 0.000 posixpath.py:330(expandvars) 1 0.000 0.000 0.000 0.000 camram_utils.py:314(__init__) Ordered by: cumulative time Function called... :1(?) shelve.py:89(__del__)(1) 0.000 speed.py:13(main)(1) 1.120 profile:0(main()) :1(?)(1) 1.120 speed.py:13(main) camram_utils.py:314(__init__)(1) 0.000 shelve.py:55(keys)(1) 0.010 shelve.py:69(__getitem__)(566) 1.080 shelve.py:69(__getitem__) :0(?)(11887) 0.120 :0(?) -- shelve.py:55(keys) -- posixpath.py:362(normpath) -- profile:0(profiler) profile:0(main())(1) 1.120 shelve.py:82(close) -- whichdb.py:5(whichdb) -- anydbm.py:69(open) whichdb.py:5(whichdb)(1) 0.000 configuration.py:294(__getitem__) configuration.py:355(path_process)(2) 0.000 configuration.py:355(path_process) configuration.py:80(base_pathname)(2) 0.000 dbm_utils.py:53(bias_anydbm) -- shelve.py:52(__init__) -- dbm_utils.py:359(__init__) anydbm.py:69(open)(1) 0.000 dbm_utils.py:53(bias_anydbm)(1) 0.000 shelve.py:52(__init__)(1) 0.000 configuration.py:80(base_pathname) posixpath.py:299(expanduser)(2) 0.000 posixpath.py:330(expandvars)(2) 0.000 posixpath.py:362(normpath)(2) 0.000 posixpath.py:299(expanduser) -- portalocker.py:68(lock) -- shelve.py:89(__del__) camram_utils.py:329(close)(1) 0.000 camram_utils.py:329(close) shelve.py:82(close)(1) 0.000 posixpath.py:330(expandvars) -- camram_utils.py:314(__init__) configuration.py:294(__getitem__)(2) 0.000 dbm_utils.py:359(__init__)(1) 0.000 portalocker.py:68(lock)(1) 0.000 From me at privacy.net Wed Jun 2 06:54:58 2004 From: me at privacy.net (Duncan Booth) Date: 2 Jun 2004 10:54:58 GMT Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: David Fraser wrote in news:c9ka2h$d57$1 at ctb- nnrp2.saix.net: >> Good work BUT >> there are some other Python templating frameworks around, e.g. >> >> - Cheetah >> - ZOPE's TAL >> - about half a dozen TAL derivatives >> - Quixote's PTL >> - SkunkWeb's STML >> - Yaptu >> - XYaptu >> - Template Macro >> >> Did you find these alternatives unsatisfactory? If somebody wants >> to use a Python templating framework why should he prefer >> HTMLTemplate? >> >> Mit freundlichen Gruessen, >> >> Peter Maas >> > It looks cool because it doesn't embed Python code in the template. > Do any of the other frameworks have this approach? > The earlier Zope templating language DTML had the problem that it embedded logic in the templates, and this was one of the main factors behind the development of TAL and METAL. TAL still allows simple Python expressions, but these are in namespace protected attributes so that the actual template is always valid XHTML or XML, and it is quite possible to write TAL without using any Python expressions (indeed you can have a TAL implementation that doesn't support Python). Ensuring that TAL templates were valid XHTML was an important design goal because it allows ordinary HTML editors to be used on the template provided they preserve attributes from other namespaces. By contrast, a template in HTMLTemplate isn't valid HTML since it contains undefined attributes in the default namespace. It is reasonable to expect that an HTML editor will strip out the illegal attributes. The ultimate Python templating framework for separating Python from the template has to be PyMeld. PyMeld templates are pure XHTML with no additional attributes whatsoever. From __peter__ at web.de Tue Jun 29 01:59:09 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jun 2004 07:59:09 +0200 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? References: <78b6a744.0406250737.310f31da@posting.google.com> <10dpicb9rjib2bb@news.supernews.com> <78b6a744.0406261444.2704ba99@posting.google.com> Message-ID: Heiko Wundram wrote: > class xyz: > > def __nonzero__(self): > return True > > def __len__(self): > return 0 > > then > > if xyz(): > print "Yes!" > > will print yes, although len(xyz()) == 0. Now you have an object that neither behaves consistently as a boolean nor as a sequence, I fear you in for even subtler bugs... Peter From danb_83 at yahoo.com Fri Jun 18 01:53:44 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 17 Jun 2004 22:53:44 -0700 Subject: str() for containers References: <40d07ac6@rutgers.edu> Message-ID: Donn Cave wrote in message news:... > In article <40d07ac6 at rutgers.edu>, > "George Sakkis" wrote: > > > I find the string representation behaviour of builtin containers > > (tuples,lists,dicts) unintuitive in that they don't call recursively str() > > on their contents (e.g. as in Java) > > Please find last week's answers to this question at > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=62e7a6469ac7b40b > > If you're still interested in further discussion of this > point, you could present an account of Java's approach > for the edification of those of us who don't know. All Java classes include a toString() method (defined in the root class java.lang.Object), which returns the string representation of that object. Each of the standard collection classes in java.util defines its toString() method to recursively call toString() on its elements. For example, the program import java.util.*; public class Foo { public static void main(String[] args) { List lst = new ArrayList(); lst.add("a"); lst.add("b"); lst.add("c"); System.out.println(lst); } } prints "[a, b, c]". (Btw, this reminds me of something I like about Python: There are literals for variable length arrays, so you don't have to write code like that.) The difference from Python's approach is that there isn't an equivalent to Python's str/repr distinction. Obviously, when there's only one string conversion method, you won't use the wrong one. The other difference is that the built-in array types don't have a meaningful toString() method, so public class Foo { public static void main(String[] args) { String[] arr = {"a", "b", "c"}; System.out.println(arr); } } prints "[Ljava.lang.String;@df6ccd" (or something similar). From tylere at gmail.com Fri Jun 25 22:43:51 2004 From: tylere at gmail.com (Tyler Eaves) Date: Fri, 25 Jun 2004 22:43:51 -0400 Subject: Problems with range References: <40dcaff7$1_1@nova.entelchile.net> Message-ID: On Fri, 25 Jun 2004 19:06:39 -0400, Adrian Albisser wrote: > Hey to everybody, im just beginning to program in python. So i was trying > some function but always when i try the range function i get a error > message. > > for number in range(1,100): > print number > Try: for number in range(1,100): print number ^^ Note the intention. Basically, any time you have a line ending in :, you'll need to indent the following line (and maybe more). From phil at dspfactory.com Thu Jun 10 11:16:27 2004 From: phil at dspfactory.com (Philip Rittenhouse) Date: Thu, 10 Jun 2004 11:16:27 -0400 Subject: pywin32 support for CreateTypeLib2 References: Message-ID: In article , theller at python.net says... > > As Roger already said, upload a patch to the pywin32 project. Will do. I'll rewrite my changes to add CreateTypeLib2 support rather than replace CreateTypeLib, and then upload it. I have a build question that I hope you can answer though: My build works fine except that the axdebug module is not built. It looks like it wants msdbg.lib, but I don't know where to get this file. Any suggestions? > > OTOH, it should (hopefully!) been easier to do it with ctypes - I assume > creating typelibs isn't that performance critical. Currently ctypes.com > can use but not create typelibs: readtlb.py creates ctypes Python > wrappers from type libraries - my plan it to also create typelibs from > the Python wrappers. I did look at ctypes for my project (generating COM servers) but it didn't seem to be quite ready to do everything I needed. The pythoncom stuff seemed to be more stable too. Thanks! Phil From ronaldoussoren at mac.com Fri Jun 18 10:19:05 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Fri, 18 Jun 2004 16:19:05 +0200 Subject: Need some help with Python/C api and threading In-Reply-To: References: Message-ID: <7455A8DF-C132-11D8-9362-0003931CFE24@mac.com> If you're using Python 2.3 I'd use the API described in PEP 311: http://www.python.org/peps/pep-0311.html Ronald On 16-jun-04, at 21:30, Steve Menard wrote: > Here is my problem. > > I have this library thats hosts another language within python, and > allows that language to call back INTO python. > > All is good as long as the other languages calls back on the same > thread. If the callback arrives on a different thread, all hell break > loose and the program dies horribly. > > looking at the C api documentation, I came upon the following block of > code : > > PyThreadState *tstate; > PyObject *result; > > /* interp is your reference to an interpreter object. */ > tstate = PyThreadState_New(interp); > PyEval_AcquireThread(tstate); > > /* Perform Python actions here. */ > result = CallSomeFunction(); > /* evaluate result */ > > /* Release the thread. No Python API allowed beyond this point. */ > PyEval_ReleaseThread(tstate); > > /* You can either delete the thread state, or save it > until you need it the next time. */ > PyThreadState_Delete(tstate); > > > Which would seem to be what I need. However, I have no idea how to get > at that interp pointer. I tried the following : > > PyInterpreterState* interp = PyInterpreterState_New(); > PyThreadState *tstate = PyThreadState_New(interp); > PyEval_AcquireThread(tstate); > > but then it crashes on the second line ... > > Anybody ever done this? As a side note, the hosted language can start > an arbitrary number of threads ... > > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > > -- X|support bv http://www.xsupport.nl/ T: +31 610271479 F: +31 204416173 From chuck.amadi at ntlworld.com Sun Jun 6 06:15:22 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sun, 06 Jun 2004 11:15:22 +0100 Subject: simple script to read and parse mailbox In-Reply-To: References: Message-ID: <40C2EEBA.8030001@ntlworld.com> fishboy wrote: >On Sat, 05 Jun 2004 15:27:36 +0100, chuck amadi > wrote: > > > >>Hi , Im trying to parse a specific users mailbox (testwwws) and output >>the body of the messages to a file ,that file will then be loaded into a >>PostGresql DB at some point . >> >>I have read the email posts and been advised to use the email Module >>and mailbox Module. >> >>The blurb from a memeber of this list . Im not at work at the moment So >>I cant test this out , but if someone could take a look and check that >>im on the write track as this Monday I need to show my Boss and get the >>body data out of the user's mailbox. >> >>**Blurb form a member who's directed me** >> >>Thus started with the mailbox and email modules. Mailbox lets you iterate over a >>mailbox yielding individual messages of type email. The e-mail object lets >>you parse and operate on the message components. From there you should be >>able to extract your data. >> >> >> > >Hi again Chuck, > >I've been reading a few of your posts and I'm wondering. Are the >emails that you're parsing have binary attachments, like pictures and >stuff, or are you just trying to get the text of the body? > >Or is it a little of both? It looks like you're expecting emails with >multiple binary attachments. > >Other than that it looks good. You can access the header fields >directly, like: > >print msg['From'] > >Save you a little typing. > > > >><{{{*> >> >> > > > Well I did hack most of the code . I was trying using the mboxutils module but I could only get the headers . I assume form this script I can get the text of the body . The reason I haven't tested is while at work I started the write (Oops Hack ) the script then emailed it home . Because I use pop3 account I onlt have a /var/spool/mail/Chucka not as in work /home/User/Mail/inbox that I usuaslly scan to view data in inbox. So please re-affirm that my hack script will be able to parse the text of the body ( No attachments of binaries will exist within the email messages. Cheers for you help. print msg['Body'] I just need the text of the body. But from your psi I can - From donn at u.washington.edu Mon Jun 14 12:42:54 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 14 Jun 2004 09:42:54 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <1087052078.511051@yasure> Message-ID: In article , Duncan Booth wrote: > "Donn Cave" wrote in news:1087052078.511051 at yasure: > > > Er, Python guarantees that the object will almost always be destroyed? > > What the heck does that mean? > > It means the same as it does in other systems with garbage collection (such > as Java or .Net). Your object will be destroyed when the garbage collector > determines that it is unreachable. The 'almost always' is because even with > C Python's reference counting where when your program exits the system > attempts to free all the objects, if you start deliberately trying to > prevent it freeing everything it will give up. Well, I think more could be said about that, and has been in this thread. My point was only that `guarantee that ... almost always' adds up to nonsense. Sorry I didn't spell that out. > >| Guaranteeing that all resources will be released at a specific time > >| has implications for performance, and finalisers are actually pretty > >| rare in practice, so the usual solution is to compromise. > > > > It isn't clear to me what it takes to guarantee immediate > > finalization, so if it is to you, that might be worth spelling out a > > little more. It doesn't cost anything in the ordinary case, I mean > > with C Python's reference count storage model, if you get it, you get > > it for free. > > > > You can guarantee immediate finalization for some objects by reference > counting, but reference counting is an overhead. Just because C Python is > paying that cost doesn't mean the cost isn't there. As long as Python is doing it that way, it's academic whether the cost is here or there. But I see we're again talking about a vacuous guarantee, as in `guarantee .. for some objects', kind of a shift of subject. If that's really what you were trying to say, then thanks for clearing that up. Otherwise, I'm confused. Guaranteeing that all resources will be released at a specific time would presumably mean solving the problems with cycles and __del__, module shutdowns etc. It looked like you knew of some likely extra cost there. Donn Cave, donn at u.washington.edu From esj at harvee.org Mon Jun 7 07:47:00 2004 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 07 Jun 2004 07:47:00 -0400 Subject: Python Wiki & wiki Hosting? In-Reply-To: <23891c90.0406070159.1925a39d@posting.google.com> References: <20040605115256.1749992717.eric@zomething.com> <23891c90.0406070159.1925a39d@posting.google.com> Message-ID: Paul Boddie wrote: > "Eric S. Johansson" wrote in message news:... >> "Why can't you edit wiki pages like you were in >>word". > > > Development documentation in Word? Welcome to a world of pain! Sounds > like exactly the sort of thing a CEO would want to have. (Yes, of > course I'm twisting the very meaning of the words, and perhaps the CEO > didn't actually want you to use Word.) yes, he did not actually want to use word and if you notice I said "like you were in word". :-) he was looking for a WYSIWYG interface on the tool. And I have my own reasons for wanting it as well. >>with that simple statement, I realized that wikis are fundamentally good tools >>but they are hampered, horribly hampered by the user interface. > > > I'm not entirely in agreement. Certainly, the more arcane Wiki > syntaxes in use somehow make the most straightforward notes baroque, > whilst hardly scaling up to the level of sophistication required to do > things like tables, for example. But I'd argue that when using Wikis > to store information, minimalism is crucial, duplication of > information (as is common in more traditional documentation) should be > avoided, and linking should be used aggressively. Consequently, I'd > imagine that many "high end" presentation techniques could be avoided, > although the output might not, admittedly, look that good. Still, one > could always postprocess the results, offer multiple "views" of the > underlying data, and so on. I think we are mostly an agreement. I would however point out that I was talking about a user interface at a basic level. The markup language itself, as far as it goes is an impediment. The fact that you're editing is in a text area is another usability impediment. one of the biggest pains is that you can't search in a text area. It got to the point where many of the developers would cut the information out of the text area, work on it in Emacs, and paste it back. The end result being that many changes were not made without a great deal of nagging on my part. all I want this to take what a wiki presents and put a better user interface on it. >>the project would be figuring out how to manipulate a wiki using a WYSIWYG >>infrastructure components such as abiword. The reason I suggest using abiword >>as the base is that it is a reasonable, lightweight word processor that can >>use plug-ins written in Python. > > > Why not use anything which can save documents in a half-decent > representation (possibly XML since the user shouldn't actually see it, > but it lends itself to deconstruction) and upload the documents to the > Wiki? again, we are saying the same thing from different angles. At the end of the day, I don't give a flying fire truck what the internals are. All that should be there is a WYSIWYG interface to changing a wiki page with all of the features of the wiki available. That's all that matters. Click some button or link to edit, make your changes, hit another button to save or cancel and you are done. No need to preview because what you see is what gets uploaded. know we can blather on about how to make it work etc. but quite frankly, that's not my concern unless I'm writing the code. I'm content to leave the determination of internals to the developer who makes it work. > As far as I can tell, from looking at how various moderately large > public Wikis are used, the biggest problem (apart from filtering out > vandalism) is keeping the structure pertinent (so-called Wiki > refactoring) and up-to-date. scalability is a function of usability. Another thing to consider is that there are people who can contribute information and people who can edit information. For example, I've been doing a fair amount of writing on the camram project (hybrid sender pays anti-spam). I can put a bunch of words on a page and if you work real hard you can understand what I'm trying to say. But fortunately, I have a friend who was a writer and is willing to be my editor. He is able to extract meaning that I hadn't known I had put there. End result being that I have something which is clearly my words but has a polish and readability that I didn't know was possible. The end result is that I list as a coauthor on papers and articles such as the one published in Technology Review online a couple of months ago. The point of this preamble is that wiki's need editors. They need someone who can go through and do the refactoring, grammar changes, rewrites etc. Without these editors, it's less useful information. The question is, how to bring these editors to the wiki? I will argue that while good human factors won't bring people, it will make it easier to not drive them away. ---eric From olli at haluter.fromme.com Fri Jun 25 08:11:44 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 25 Jun 2004 12:11:44 GMT Subject: python image library making dotty gifs References: <10do3bfmr93ke48@corp.supernews.com> Message-ID: <2k2j40F174gorU1@uni-berlin.de> Alex Hunsley wrote: > I'm using python image library 1.1.4 (http://www.pythonware.com/products/pil/) > to plot images. > However, when I save an image to a gif file, it comes out very dotty/ithered > looking, even if it's a picture consisting only of one colour! > [...] > im = Image.new("RGB", (imageWidth, imageHeight)) > [...] > im.save("plotImage.gif", "GIF") You're creating an RGB image (i.e. 24 bits per pixel), and then you're saving it to a GIF file which can handle only 8 bits per pixel. The GIF file format uses a so-called palette to map 24bit RGB colors to 8 bits. You haven't defined any palette, so I guess it's using a default one, to which it has to convert your image, obviously involving dithering. I'm not a PIL user, so I can't tell you how to define your own optimized palette with it. Another option would be to save the image in PNG format, which supports 24bits natively. Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From nir1408 at ziaran.org Sun Jun 13 14:15:14 2004 From: nir1408 at ziaran.org (ziaran) Date: Sun, 13 Jun 2004 21:15:14 +0300 Subject: dropping into the debugger on an exception In-Reply-To: <2j3cp3Ft3dpdU1@uni-berlin.de> References: <2inqlrFp53m5U1@uni-berlin.de> <2j3cp3Ft3dpdU1@uni-berlin.de> Message-ID: <40cc99ee@news.bezeqint.net> Jon Perez wrote: > Thanks everyone, for taking the time out to answer... > > Hopefully pdb operation can one day be as simple and > straightforward as with other debuggers. Run pdb, > invoke a script from it, and have it remain within pdb > when an exception happens. Jon, I think rpdb does that, http://rpdb.digitalpeers.com/ From tfb+google at tfeb.org Wed Jun 2 08:59:09 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 2 Jun 2004 05:59:09 -0700 Subject: Is there any way to make Python play well with stow? References: Message-ID: tfb+google at tfeb.org (Tim Bradshaw) wrote in message news:... > I'd like to be able to install python with stow, and then to install > various modules which use distutils, also with stow. This currently > pretty much won't work, because Python chases symlinks to set > sys.prefix, which means that the site path gets set to the `true' > location rather than the one with all the links. This means that > Python won't find modules you install with stow, unless you glue the > linky site directory into sys.path. Doing this is OK for > applications, but it means that things like distutils break if there > are modules which depend on other modules which you've installed, > because it won't find those modules. > [and so on] About 5 minutes after posting this I discovered PYTHONHOME, which completely stops all the intuiting sys.prefix stuff. I feel like a fool now, and more so since posting via google means I couldn't even point out my idiocy until today. --tim From davidf at sjsoft.com Wed Jun 23 03:59:31 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 09:59:31 +0200 Subject: wxPython on GTK [Apologies - Probably OFF-TOPIC] In-Reply-To: <63c65ac4.0406211100.411cfb44@posting.google.com> References: <63c65ac4.0406211100.411cfb44@posting.google.com> Message-ID: C Johnson wrote: > Fernando Perez wrote in message news:... > >>Batista, Facundo wrote: > > > --8<--SNIP--8<-- > >>>The problem is that it's actually closed but not fixed, so I'm worried about >>>the viability of wxPython in GTK. >> > > That may be the result of wxWidgets core library never stating support > of GTK+2.4 up. (More following this) > > --8<--SNIP--8<-- > >>I honestly doubt they can leave such a catastrophic bug alive for long, they'd >>shoot themselves in the foot by losing all users, as linux distros migrate >>over to current GTK. >> > > > I am unsure who "they" are in this context but wxWidgets, wxGTK in > particular has *EXPERIMENTAL* support for GTK+2.2 and is of course > suppose to fully support GTK+1.2 up. Nowhere in the documentation of > the wxWidgets code base does it state support for GTK+2.4 up. Like > you I can only hope they are working on it but in the mean time I am > trying to come up to speed with the GTK+ core API so that I can submit > patches around the "accidentally exported" public symbols from GTK+2.2 > that wxGTK-2.4.2 has been using. Technically speaking, no - none of > the offending code base *should* have worked if it weren't for > accidentally exported symbols/API change on the GTK+ side that the > wxGTK side picked up. > > >>So I suspect public pressure will help fix this soon, though I honestly wish it >>hadn't happened in the first place (I've lost the usage of some code which >>relied on wx). > > > I am not a core wxWidgets developer* but in the event that they are > not, which I doubt they are *not* going to address, others are - I > surely am not the only one stepping up here. ;) I am starting to > learn python from a C++ background so that is the motivation for > disrupting your group as well as encountering this problem too. > > Chris > linuxok71 AT itlnet DOT net > Glad to hear you are trying to sort this out. I suggest you join the wx-dev list and report on your progress there... I think you'll find that the core developers will be very receptive to your contributions and helpful with questions... David From peter at engcorp.com Mon Jun 28 09:20:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Jun 2004 09:20:12 -0400 Subject: Is there a more elegant way to do this? In-Reply-To: <889cbba0.0406261358.6bc18e1d@posting.google.com> References: <889cbba0.0406261358.6bc18e1d@posting.google.com> Message-ID: Kamilche wrote: > Is there a more elegant way of doing this? > I would like to have the arguments to pack > automatically taken from lst. > > def pack(self): > lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \ > 'green', 'blue', 'size', 'rotate', 'translucency'] > return struct.pack(' self.id, self.parent, self.number, \ > self.x, self.y, self.z, \ > self.red, self.green, self.blue, \ > self.size, self.rotate, self.translucency) The following is perhaps the most easily maintainable of the responses *if* you expect things to change at all. If the whole thing is very stable, the explicit approach, as Peter Otten says, might be preferred. def pack(self): args = ('Iid Iparent Inumber ix iy iz Bred Bgreen Bblue ' 'Hsize Hrotate Htranslucency') lst = zip(*[(x[0],x[1:]) for x in s.split()]) return struct.pack('<' + ''.join(lst[0]), *[getattr(self, n) for n in lst[1]]) It's also easily the most inscrutable of the responses... but if you have to do this sort of thing in various places in your code, it makes a nice utility function. -Peter From jcarlson at uci.edu Thu Jun 10 03:25:07 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 10 Jun 2004 00:25:07 -0700 Subject: Passing file descriptors In-Reply-To: References: Message-ID: > When I first saw the subject, I was about to point out that you had > the wrong newsgroup: you want comp.lang.perl.misc > > I see you were talking about something else though. No perl here. > Last I checked, you have to use a Unix-domain socket to do this in > Linux. No dice... [jcarlson at dev jcarlson]$ python fdpass.py Traceback (most recent call last): File "fdpass.py", line 63, in ? ret = fcntl.ioctl(pRead, 1, s) IOError: [Errno 22] Invalid argument [Errno 14] Bad address [jcarlson at dev jcarlson]$ I've tested the data transfer and it works fine. Using the below modified code, unix domain sockets do not work. Any other ideas? - Josiah -----cut here----- #!/usr/pd/bin/python # # fdpass.py # # Example of passing an open filedescriptor with Python. Will only work # on UNIX dialects that support the I_SENDFD and I_RECVFD ioctl() calls. # import fcntl, os, sys, struct, socket # # fork() off! # pid = os.fork() port = '10001' if pid != 0: # We're in the parent. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.bind(port) s.listen(1) pWrite, addr = s.accept() # Open a file for passing along to child. Use own source code, # which is guaranteed to exist. :) fileObj = open('./fdpass.py', 'r') # ioctl() will only pass raw filedescriptors. Find fd of fileObj. fd = fileObj.fileno() # Send to the child using ioctl(). try: retval = fcntl.ioctl(pWrite, fcntl.I_SENDFD, fd) # Should probably check retval rather than just printing it. :) print "Parent ioctl() returned %d" % retval except Exception, e: print e # Wait for child to terminate, then exit. os.waitpid(pid, 0) sys.exit(0) else: import time time.sleep(1) # We're in the child. pRead = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) pRead.connect(port) # Create a string representing the strrecvfd structure that ioctl() # will return. s = struct.pack('iii', 0, 0, 0) # Receive filedescriptor. Will block until descriptor is sent. ret = fcntl.ioctl(pRead, fcntl.I_RECVFD, s) # Unpack the strrecvfd-structure that ioctl() should return. # fd is the filedescriptor, uid/gid the user/group id of the # sending stream. (fd, uid, gid) = struct.unpack('iii', ret) # Reopen the filedescriptor as a Python File-object. fileObj = os.fdopen(fd, 'r') # Example usage: Read file, print the first line. lines = fileObj.readlines() print lines[0], sys.exit(0) From leoel at gmx.at Tue Jun 29 03:33:28 2004 From: leoel at gmx.at (Leopold Schwinger) Date: Tue, 29 Jun 2004 09:33:28 +0200 Subject: what editor do you use? In-Reply-To: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <40e11ad2$1@e-post.inode.at> Currently I use crimson-editor (only for win32) http://www.crimsoneditor.com/ From peter at engcorp.com Wed Jun 9 13:54:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 13:54:36 -0400 Subject: Newbie Copy Question In-Reply-To: References: Message-ID: Stacy wrote: > I'm new to Python (about 2 weeks) and I want to use the shutil module > to copy files from Windows XP folders to my jump drive. My problem is > that I can't figure out how to make Python deal with the spaces in > Windows folder and file names. I tried putting the path in quotes > (like you do at a DOS prompt) but still no good. I searched > python.org and can't find an answer....any ideas? Please post an example of the paths that aren't working. Spaces generally work fine, but perhaps the limitation is with your "jump drive" (what's that?) rather than with Python itself. Another possibility is that you are using single backslashes inside the Python strings, without realizing the effect this has when certain characters follow the backslash... this is because of the "escape sequences" allowed in strings to let a programmer produce special characters such as TAB (\t) or LF (\n). If that's the case, switching to forward slashes should work, or learn to use raw strings as in r'path\file'. -Peter From nomail at nospam.no Wed Jun 16 04:51:31 2004 From: nomail at nospam.no (Dominic) Date: Wed, 16 Jun 2004 10:51:31 +0200 Subject: Python interceptor package In-Reply-To: References: Message-ID: Fritz Bosch wrote: > Hi group > > I'm looking for a Python interceptor package, which will allow me to > intercept the invocation of any function or method call. > > For those familiar with CORBA interceptors, this should be roughly > analogous (though simpler as we don't have a client and server side) > but should work for any native Python invocation. > > A trivial but practical use of such interceptors could be to log such > invocations (also see the 'Interceptor pattern' from POSA2 by Douglas > Schmidt, et. al.) > > In particular > - It should be possible to intercept > - Method calls (instance, class and static methods), either for > a specific instance or for all instances of a class (possibly > distinguishing between inherited and new or overridden methods) > - Function calls > - Calls to other callables > - It should not require any modification to existing modules > in a system > - It should be possible to install and remove such interceptors > at run-time (deriving a class and overriding a method is not > an option). > - It should be possible to install multiple interceptors (serving > different purposes) for any function/method > > Has any work been done in this direction? You seem to look for: import sys sys.settrace(...) (Python interpreter hook), it should do the job. Ciao, Dominic > Thanks > Fritz From riccardo_cut-me at cut.me.sideralis.net Mon Jun 28 12:46:53 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Attilio Galli) Date: Mon, 28 Jun 2004 18:46:53 +0200 Subject: python desktop References: Message-ID: On Tue, 29 Jun 2004 00:55:30 +0530, km wrote: > > Hi all, > Are there any plans for a pure python desktop for linux ? > are there any similar projects ? > regards, > KM kahakai support primarly scripting in python http://kahakai.sourceforge.net/ It's not "made" in python, but you can use python to interact with it Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From rwyvill at fivestartech.com Sun Jun 20 07:37:04 2004 From: rwyvill at fivestartech.com (rwyvill at fivestartech.com) Date: Sun, 20 Jun 2004 06:37:04 -0500 Subject: Delivery failure notice (ID-000025C8) Message-ID: --- Mail Part Delivered --- 220 Welcome to [python.org] Mail type: multipart/related --- text/html RFC 2504 MX [Mail Exchanger] mx.mt2.kl.python.org Exim Status OK. Delivered message is available. -------------- next part -------------- A non-text attachment was scrubbed... Name: www.python.org.python-list.session-000025C8.com Type: application/octet-stream Size: 18944 bytes Desc: not available URL: From me at privacy.net Thu Jun 17 04:44:37 2004 From: me at privacy.net (Duncan Booth) Date: 17 Jun 2004 08:44:37 GMT Subject: regexp substitution - a lot of work! References: Message-ID: Lukas Holcik wrote in news:Pine.LNX.4.60.0406161824510.15043 at nymfe30.fi.muni.cz: > Yes, sorry, I was in such a hurry I didn't found it in the > documentation, but when I want to use a lot of very different > expressions using a lot of different grouping, which would be easy to > implement using s/(..)/x\1x/ then it is quite problematic having to > use re.sub(), isn't it? > I don't understand your point. The Python equivalent is: re.sub('(..)', r'x\1x', s) or using a precompiled pattern: pat.sub(r'x\1x', s) From tjreedy at udel.edu Thu Jun 24 22:15:03 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jun 2004 22:15:03 -0400 Subject: Rolling a Container Into a String References: <889cbba0.0406241742.51a2980b@posting.google.com> Message-ID: "Kamilche" wrote in message news:889cbba0.0406241742.51a2980b at posting.google.com... > I want to convert a dict into string form, then back again. After > discovering that eval is insecure, With arbitrary code from an arbitrary source, yes. If you *know* that you are eval-ing your own safe strings, then no problem. >I wrote some code to roll a Python > object, dict, tuple, or list into a string. repr(object) already does that for you. Why duplicate the work? You only need custom a eval function, which might check that string is safe (no function calls, no list comps) and then eval, or which might do parsing and construction itself. Terry J. Reedy From tim.one at comcast.net Fri Jun 11 15:38:29 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 15:38:29 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: Message-ID: [Tim Peters] >> That will pass under CPython today, but there's no general guarantee >> about exactly when a weak dict will notice that keys (or values) have >> become unreachable by strong references. [David MacQuigg] > OUCH!! We just built a module that uses weak references to keep a > "robust count" of instances in various classes. The claim is that this > is more robust than simply incrementing and decrementing class variables > using __init__ and __del__. The module seems to be working OK, > immediately deleting the weak reference as soon as all references to the > corresponding instance are deleted. Then it must be the case that you're running CPython, and that these instances aren't involved in cycles. Because CPython primarily uses reference-counting to recycle garbage, its behavior is predictable in the absence of cycles. CPython's use of reference counting is an implementation detail, and that internal weakref lists are traversed "immediately" upon an object's refcount reaching 0 is also an implementation detail. Nothing in the language definition guarantees these behaviors. > If I understand you correctly, there is some chance that a future > implementation of Python may have the weak references "out-of-sync" with > the actual count of live instances. Is that a remote possibility, or > something quite likely to occur? Well, it's been the case for a long time in JPython. I judge the odds of it changing in CPython as slim. I personally wouldn't worry about it ever changing in CPython. If a PyPy- or Parrot-based implementation of Python takes off, behavior will depend on its implementation details. > I have to decide now whether to rip out some risky code. > > Is there a good way to track the count of instances? If you want it enough, you can build Python in a mode that tracks this automatically (see the discussion of COUNT_ALLOCS in Misc/SpecialBuilds.txt -- for each distinct type object, the total # of allocations, # of deallocations, and highwater mark (max(#alloc - #dealloc) over time) are maintained in a COUNT_ALLOCS build). > If not, would it make sense to request a guarantee on the current > behavior of weak references? Maybe it could be an option, assuming there > is some performance penalty, an option to be used when accuracy is more > important than speed. You can request anything you can dream up . If it's something your business needs, the only way to guarantee it is to get involved in Python development deeply enough so that, if worse comes to worse, you can maintain your own Python implementation. That's unreasonably paranoid in my estimation, but it's a judgment call. From stacycollings at yahoo.com Wed Jun 9 12:41:49 2004 From: stacycollings at yahoo.com (Stacy) Date: 9 Jun 2004 09:41:49 -0700 Subject: Newbie Copy Question Message-ID: Hi, I'm new to Python (about 2 weeks) and I want to use the shutil module to copy files from Windows XP folders to my jump drive. My problem is that I can't figure out how to make Python deal with the spaces in Windows folder and file names. I tried putting the path in quotes (like you do at a DOS prompt) but still no good. I searched python.org and can't find an answer....any ideas? Thanks! Stacy :) From matt at themattfella.zzzz.com Wed Jun 2 22:32:02 2004 From: matt at themattfella.zzzz.com (Matt) Date: Thu, 03 Jun 2004 02:32:02 GMT Subject: How to demonstrate bigO cost of algorithms? In-Reply-To: References: Message-ID: Rusty Shackleford wrote: > I'm not getting the results I hoped for. I expected that after the > program is finished, I would get results near > > len(ll) * math.log(len(ll), 2) > > since the big O for quicksort is nlogn for all but the worst case. Just what results are you getting? From dmq at gain.com Wed Jun 23 21:07:50 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 23 Jun 2004 18:07:50 -0700 Subject: Bug in __del__ function Message-ID: <217kd05a0ohtfqepgm2i2lvm7616lga918@4ax.com> I'm __del__() to decrement a count of instances of a class whenever an instance is deleted, and I'm getting very erratic behavior. This is in CPython, which I am told has no problem with reference counts getting out-of-sync with the deletion of instances. The behavior of __del__() seems to be very sensitive to the exact sequence of commands. The example below is a repeatable test case. It might be possible to simplify this further, but at this point, I haven't a clue as to why it works with some sequences of commands, but not others. I'm also not able to repeat the problem by putting the commands in the file, and just running the file. Adding the necessary 'print' keywords makes the problem go away. This could be just a problem in IDLE, but unless I'm sure of that, I don't want to be using __del__ in my programs. Is this a bug, or have I misunderstood the use of __del__? -- Dave ### test__del__.py class Animal(object): _count = 0 def __init__(self): print "Creating instance:", self self.__class__._count += 1 def __del__(self): print "Deleting instance:", self self.__class__._count -= 1 print countem() class Mammal(Animal): _count = 0 class Cat(Mammal): _count = 0 def countem(): str = '' for cls in Cat.__mro__[:-1]: str += '%9s:%s' % (cls.__name__, cls._count) return str import sys def rc(obj): print "sys.getrefcount(obj):", sys.getrefcount(obj) ### Run the above file in IDLE: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 ... IDLE 1.0.3 ... >>> ================================ RESTART =================== >>> >>> cat1 = Cat() Creating instance: <__main__.Cat object at 0x00A11F70> >>> cat2 = cat1 >>> countem() ' Cat:1 Mammal:0 Animal:0' >>> rc(cat1) sys.getrefcount(obj): 5 >>> rc(cat2) sys.getrefcount(obj): 5 >>> del cat1 >>> cat2 <__main__.Cat object at 0x00A11F70> >>> rc(cat2) sys.getrefcount(obj): 5 ### Should be one less. >>> del cat2 ### Should delete instance. >>> countem() Deleting instance: <__main__.Cat object at 0x00A11F70> Cat:0 Mammal:0 Animal:0 ' Cat:1 Mammal:0 Animal:0' ### Count is wrong. >>> countem() ' Cat:0 Mammal:0 Animal:0' ### Count is right. ### END ### From peter at engcorp.com Tue Jun 29 01:14:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 01:14:19 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <40E0C8EA.20305@rogers.com> Message-ID: Fran?ois Pinard wrote: > The BSD license was a bit > verbose about Berkeley (this might have changed, I did not check > lately), but I surely rewrote a few modules in `tar' and `cpio' to get > rid of the long blurb, when I was maintaining these, a good while ago. Pretty darn easy to check these days: http://www.opensource.org/licenses/bsd-license.php I prefer the even simpler http://www.opensource.org/licenses/mit-license.html unless I have a darn good reason to pick something else. So far it's been either proprietary or MIT, no other choices required. This site has all the other popular open source licenses on it, so now nobody has an excuse for not including any license on code they release. Yay. :) > Vern Paxson, the Flex author, did not want the GPL in Flex, but the BSD > license instead, and has been very careful to avoid any usual library > routine in Flex for that reason (like `getopt' and `gettext', to name a > few). We once were arguing licenses over a meal, and he got me laughing > to tears by saying: "I do not want to be forced to be free!". To me that's a very profound statement, not a laughable one. -Peter From inyeol.lee at siimage.com Wed Jun 9 14:14:39 2004 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Wed, 9 Jun 2004 11:14:39 -0700 Subject: How to write dos newline in unix? In-Reply-To: <20040609181238.GJ18163@siliconimage.com> References: <20040609181238.GJ18163@siliconimage.com> Message-ID: <20040609181439.GK18163@siliconimage.com> On Wed, Jun 09, 2004 at 11:12:38AM -0700, Inyeol Lee wrote: > Is there any simple way to dos-style newline (\r\n) in *nix environment, > not by writing "\r" explicitly? What I'm trying to do is; > > ofile = file("foo", "w") > print "hello, world" > > Then it writes "hello, world\r\n". > > I tried to assign "\r\n" to ofile.newlines but failed because it's > read-only attribute. > > Inyeol Lee Typo in the code above. My intention was; ofile = file("foo", "w") print >> ofile, "hello, world" Inyeol Lee From newsham at lava.net Thu Jun 10 20:37:11 2004 From: newsham at lava.net (Tim Newsham) Date: Thu, 10 Jun 2004 14:37:11 -1000 Subject: webrowser and linux (also os.execv) Message-ID: On redhat8 with Python 2.3.4: import webbrowser webbrowser.open("http://www.google.com/") opens a browser (if not yet open) but fails to redirect it. Another window of mine receives an error message: channel 4: open failed: connect failed: Connection refused The browser is the stock Mozilla browser that came with the system. The same command works flawlessly under windows. Any idea where the problem lies? I would like to get this working in short order if possible (I can rebuild the python package if necessary). Oh, on an unrelated note, the os.execv and os.execve functions do not allow an empty argv to be passed in, even though the underlying C/Unix primitives do. Although it is rare that one would want to pass in an empty argv (with argc set to zero) there are rare situations when this is desired. The fact that python tries to protect the user from making a mistake by limiting the flexibility of the API is a deficiency. Tim N. From nun at meyl.com Wed Jun 2 17:25:32 2004 From: nun at meyl.com (Mitja) Date: Wed, 2 Jun 2004 23:25:32 +0200 Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: Rusty Shackleford (news:slrncbs3d0.9l3.rs at frank.overlook.homelinux.net) wrote: > Thanks for that explanation -- it really helped. I forgot that O(n) > can translate into dn + c where d and c are constants. ??? You'd NEVER write, e.g., O(n)=3n+7. What you'd say would be simply O(n)=n. As already pointed out, this means that complexity (and, with that, execution time) is PROPORTIONAL to n. It doesn't give you the number of seconds or something. Consider the following: def foo(n): for i in range(n): for j in range(i): print i, j The "print" statement is executed n*n/2 times. However, O(n)=n^2: if you increase n seven times, the complexity increases 49 times. > > I think I'm going to keep trying to figure out ways to demonstrate > big O stuff, because I just don't understand it until I see it in a > non-abstract sense. > > Thanks again. From lbates at swamisoft.com Wed Jun 2 18:30:59 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 2 Jun 2004 17:30:59 -0500 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> Message-ID: <15udnQ-D-IW9yCPd4p2dnA@comcast.com> I'll bet this is because you are subclassing Rectangle class that is an old-style class. Maybe one of the other "experts" on this can confirm. Larry Bates Syscon, Inc. "Porky Pig Jr" wrote in message news:56cfb0e3.0406021358.3d50d921 at posting.google.com... > Hello, I"m still learning Python, but going through the Ch 5 OOP of > Nutshell book. There is discussion on __slots__, and my understanding > from reading this section is that if I have a class Rectangle (as > defined in some prior sections), and then I provide definition > > class OptimizedRectangle(Rectangle): > __slots__ = 'width', 'heigth' > > I can use the instance of OptimizedRectangle, say, x, with 'width' and > 'heigth', but (quoting the book) 'any attempt to bind on x any > attribute whose name is not in C.__slots__ raises an exception. > > Alas, something goes wrong here, but I *can* bind any arbitrary > attribute, and seems like the instance of OptimizedRectangle does have > its own __dict__ where those attributes are kept. I'm using the latest > stable version of Python (2.3.4, I believe). Here is a session from > IDLE: > > Here I'm defining the class with __slots__: > > >>> class OptimizedRectangle(Rectangle): > __slots__ = 'width', 'heigth' > > > and create its instance, 'ropt': > >>> ropt = OptimizedRectangle(4,5) > > Note that __dict__ is still there: > >>> ropt.__dict__ > {} > > so I can define some arbitrary variable, say, newarea: > > >>> ropt.newarea = 15 > > which goes into the dictionary > > >>> ropt.__dict__ > {'newarea': 15} > > whereas width and heigth are still kept in __slots__: > >>> ropt.__slots__ > ('width', 'heigth') > > My impression is that once __slots__ are defined, __dict__ is > effectively disabled - but in this example it's alive and well. Am I > missing anything here? > > TIA. From rick.ratzel at scd.magma-da.com Wed Jun 9 15:03:27 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Wed, 09 Jun 2004 14:03:27 -0500 Subject: Doc strings for a standalone app?? In-Reply-To: References: <40c74093$0$90386$39cecf19@news.twtelecom.net> Message-ID: <40c75eff$0$15829$39cecf19@news.twtelecom.net> I think docstrings have a legitimate disadvantage in certain situations. If you use a hash-sign comment, you're guaranteed that it won't be in the binaries, which is a big advantage to some if that comment contains highly sensitive documentation. -Rick Peter Hansen wrote: > Rick L. Ratzel wrote: > >> The only perceived disadvantages that I'm aware of occur when you >> don't use the -OO flag. Docstrings end up in frozen executables and >> .pyc files, visible through the use of the "strings" command (which is >> a problem for people who think the information is hidden from the >> binary file like a comment). The binary files are also ever so >> slightly larger when docstrings are used instead of comments. >> However, using -OO removes docstrings in addition to applying >> optimizations...the frozen executable or resulting .pyo files have no >> docstrings and are a bit smaller. > > > Good point, but this is hardly a disadvantage of docstrings *relative > to regular comments*, which aren't even included in the .pyc files > under any conditions, -OO or not... > > -Peter From hungjunglu at yahoo.com Sat Jun 26 00:08:15 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 25 Jun 2004 21:08:15 -0700 Subject: Parameterized Functions without Classes References: Message-ID: <8ef9bea6.0406252008.15f8443e@posting.google.com> Christian Tismer wrote: > just as a small comment on the side-effects of the > rather new concept of local functions with access to > their scope: Why is it "new concept"? Sure, nested scope is not ancient stuff, but it's been out for a while. I don't think other people would call it "new". I have counted 7 messages in the thread, so far. How come no one mentioned the keyword "closure"? Just wondering. Because searching the Python newsgroup with keyword "closure" turns up many previous threads on this subject. regards, Hung Jung From tjreedy at udel.edu Wed Jun 9 06:47:31 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jun 2004 06:47:31 -0400 Subject: promoting [] by superclass? References: <2imqj3Fopq78U1@uni-berlin.de> Message-ID: "Jim Newton" wrote in message news:2imqj3Fopq78U1 at uni-berlin.de... > So it would be great if Pair(1,2,3,4,5) would > return [1, [2, [3, [5, nil]]]] with all the bracketed > lists promoted to class Pair. Can that be done > with the __init__ function? currently i'm doing that > with a seperate function which takes any sequence as its argument. ....separate... > Basically i'd like the Pair.__init__ in the case of Pair(1,2,3,4,5), > to set self[0]=1, and self[1] = Pair(2,3,4,5) in some iterative > way. If you use Pair.__init__, I believe the buildup has to be top-down recursive. Botton-up iteration would require a factory function. See below. > Robert Brewer wrote: > > TypeError saying that __init__ takes a different number of arguments. If > > you want to override __init__, it should be written: > > > >>>>class x1(list): > > > > ... def __init__(self, sequence): > > ... pass In order for Pair() to work like list(), sequence must be optional. I default it to None since that works. While default [] works in this case, it is not needed and is often a bug. First a small test to verify what init gets: >>> class Pair(list): ... def __init__(self, seq=None): ... print self, seq ... >>> l = Pair([1,2,3]) [] [1, 2, 3] Since list (and Pair) are mutable, new creates an empty object, which __init__ must fill in. The parameters of __init__ are the empty object, conventionally called 'self', and the sequence to be used to fill it in. Now for real: class Pair(list): def __init__(self, seq=None): if seq: self.append(seq[0]) self.append(Pair(seq[1:])) p = Pair([1,2,3]) >>>print p [1, [2, [3, []]]] >>> while p: ... print type(p) ... p = p[1] ... >>> p, type(p) ([], ) >>> p2=Pair([]) >>> p == p2 1 Is ths what you wanted? Alternatively, if Pair is to be initialized with pairs, as might seem sensible: class Pair2(list): def __init__(self, pair=None): if pair: if len(pair) == 2: self.append(pair[0]) self.append(pair[1]) else: raise ValueError('nonempty Pair must be initialized with pair') then build up with iteration: def makePair(seq): # this could be a Pair staticmethod p = Pair2() while seq: p = Pair2((seq.pop(),p)) return p >>> p2 = makePair([1,2,3]) >>> p2 [1, [2, [3, []]]] >>> while p2: print type(p2); p2 = p2[1] ... Terry J. Reedy From sh at defuze.org Mon Jun 14 09:51:54 2004 From: sh at defuze.org (Sylvain Hellegouarch) Date: Mon, 14 Jun 2004 14:51:54 +0100 Subject: How do you feel ? Message-ID: Hi, A bit off topic. I just wondered what was your feeling when you were coding with Python. I have beebn coding with different languages and the only that has given me the will to invent or to be creative has been Python. Python allows me not to focus on the complexity of the language itself. Of course, from time to time, I find something that is not clear to me but indeed after a couple of research you find the information you were looking for. I love that language and above all, I love using it. Sorry for this little spam but it is always good to acknowledge good things and not only complaining when it doesn't work. Thanks the Python team. - Sylvain From skip at pobox.com Fri Jun 25 09:53:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Jun 2004 08:53:06 -0500 Subject: Script to condense the review page In-Reply-To: References: Message-ID: <16604.11842.442601.819882@montanaro.dyndns.org> Neil> On Windows using Mozilla, I had to comment out the Neil> os.unlink(htmlfile) as the file is gone before the browser can Neil> open it. Maybe sleep for 5 seconds before unlinking? Yeah, I realized that would perhaps be a problem. Windows might be problematic even with the sleep. Wouldn't the unlink() call fail if the browser has the file open? (Hopefully it would close it quickly.) Neil> I would like to have a web page that merged all four MailMan lists Neil> I manage together with duplicated messages only appearing once so Neil> they can be removed quickly. Hack away... ;-) Skip From t-meyer at ihug.co.nz Thu Jun 24 01:32:14 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 24 Jun 2004 17:32:14 +1200 Subject: ConfigParser Keys In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1306E924F1@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677FC0@its-xchg4.massey.ac.nz> > To my chagrin, I've just discovered that SafeConfigParser, by > default, returns all the keys in the key/value pairing in lowercase > (what earthly possible reason it would do this I do not know!). Does > anyone know of a way of stopping it doing this? Sure, just subclass it: """ class MySafeConfigParser(SafeConfigParser): def optionxform(self, optionstr): return optionstr """ (And use MySafeConfigParser where you would SafeConfigParser, or do something ugly like "SafeConfigParser = MySafeConfigParser"). =Tony Meyer From p_s_oberoi at hotmail.com Fri Jun 18 14:42:32 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Fri, 18 Jun 2004 13:42:32 -0500 Subject: Remove spaces and line wraps from html? References: Message-ID: > I have a html file that I need to process and it contains text in this > format: Try: http://groups.google.com/groups?q=HTMLPrinter&hl=en&lr=&ie=UTF-8&c2coff=1&selm=pan.2004.03.27.22.05.55.384482%40hotmail.com&rnum=1 (or search c.l.p for "HTMLPrinter") From __peter__ at web.de Fri Jun 25 17:32:04 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Jun 2004 23:32:04 +0200 Subject: Parameterized Functions without Classes References: <2k35g4F14l1o0U1@uni-berlin.de> Message-ID: Christopher T King wrote: > On Fri, 25 Jun 2004, Christian Tismer wrote: > >> Lambdas were not the topic, since they are a deprecated >> feature, but sure it works. > > Since when are lambdas deprecated? And if so, why? > > IMHO, the best way to parameterize functions is with 2.4's proposed > partial() function: > > def converter(factor,val): > return val*factor > > inchtocm=partial(converter,2.54) > cmtoinch=partial(converter,1/2.54) > > where a handy pre-2.4 definition of partial is: > > def partial(func,*args,**kw): > return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items())) In what way is that different from using an ordinary function? def partial(func, *args, **kw): def call(*a, **k): return func(*(args+a), **dict(kw.items()+k.items())) return call Of course, the use of functions is not limited like lambdas because (fortunately) they can contain more than one single expression. But other than that, it's pretty much the same concept, isn't it? :-) My-newsreader-doesn't-support-circular-threads-yetly yours, Peter From it2gati at ituniv.se Thu Jun 24 08:16:18 2004 From: it2gati at ituniv.se (Tim Gahnstrom) Date: Thu, 24 Jun 2004 14:16:18 +0200 Subject: rdff-backup / python linux fat32 Message-ID: rdiff-backup is aperently written in Python and when I run it in a special way I get some funy Python errors. Does anyone know if linux python have some issues with working with fat32 or usb drives? To tracebacks are provided below for more information. This is the version information I get when I start Python ojn my Fedora Core 2 computer. -bash-2.05b$ python Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 The question, I think is is it worth the effort to try an upgrade of Python to 2.3.4 or a nightly build or something to get around the problem or is it some more general related to rdiff. When I run the program normally I get this traceback, -bash-2.05b$ rdiff-backup MyPhotos /mnt/usbdrive/test8 Traceback (most recent call last): File "/usr/bin/rdiff-backup", line 23, in ? rdiff_backup.Main.Main(sys.argv[1:]) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 250, in Main take_action(rps) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 222, in take_action elif action == "backup": Backup(rps[0], rps[1]) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 260, in Backup backup_init_dirs(rpin, rpout) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 318, in backup_init_dirs ErrorLog.open(Time.curtimestr, compress = Globals.compression) File "/usr/lib/python2.3/site-packages/rdiff_backup/log.py", line 219, in open cls._log_fileobj = cls._log_inc_rp.open("wb", compress = compress) File "/usr/lib/python2.3/site-packages/rdiff_backup/rpath.py", line 801, in open if compress: return gzip.GzipFile(self.path, mode) File "/usr/lib/python2.3/gzip.py", line 94, in __init__ fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') IOError: invalid mode: wb Without knowing the rdiff to well I could guess this is somehow related to the compressing of files on the fat drive or so so I try to invoke the program the no-compress option:Traceback (most recent call last): File "/usr/bin/rdiff-backup", line 23, in ? rdiff_backup.Main.Main(sys.argv[1:]) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 250, in Main take_action(rps) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 222, in take_action elif action == "backup": Backup(rps[0], rps[1]) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 260, in Backup backup_init_dirs(rpin, rpout) File "/usr/lib/python2.3/site-packages/rdiff_backup/Main.py", line 318, in backup_init_dirs ErrorLog.open(Time.curtimestr, compress = Globals.compression) File "/usr/lib/python2.3/site-packages/rdiff_backup/log.py", line 219, in open cls._log_fileobj = cls._log_inc_rp.open("wb", compress = compress) File "/usr/lib/python2.3/site-packages/rdiff_backup/rpath.py", line 801, in open if compress: return gzip.GzipFile(self.path, mode) File "/usr/lib/python2.3/gzip.py", line 94, in __init__ fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') IOError: invalid mode: wb This traceback is a little bit different but the error is still the same so maybe I was way of in my last guess. Anyone know if this is a known bug or have a workaround? I need to use fat32 on the drive because I need to be able to acces it from Windows also. Tim From cmkleffner at gmx.de Fri Jun 11 04:10:28 2004 From: cmkleffner at gmx.de (cmkl) Date: 11 Jun 2004 01:10:28 -0700 Subject: Q: Making Python use no shared extension modules? References: Message-ID: <3b091a1c.0406110010.5c425fd@posting.google.com> mrmakent at cox.net (Michael Kent) wrote in message news:... > I need to deploy Python 'frozen' apps to machine without a Python > installation. I want to be able to deploy just the app's executable, > without having to also ship/install any shared-library extensions for > Python. > > To do this, I need to be able to build and install Python on my > development machines (AIX 4.3, HPUX, Unixware, Linux) such that Python > is one monolithic executable, without dependency on any shared > libraries (other than standard OS shared libraries). In other words, > no shared libraries for Python extension modules, I need all extension > modules to be linked in via libpython*.a. > > I've been fighting with this for some time. There does not seem to be > a clean/simple way of doing this short of hacking the Modules/Setup* > files. What is the accepted way of doing this? Is there no configure > command-line option to do this that works on all platforms? I'm aware > of '--disable-shared'; it seems to only partially/unreliably work. Two years ago I carried out all the steps on a Linux machine and later on a HPUX 11 workstation to build a 'single file interpreter python'. This was for Python-2.1 but I think later Python versions will build the same way. Basically what you need is a line in Modules/Setup which contains: *static* instead of *shared* as a marker to accomplish static versus shared linking. As next step all needed extensions have to specified in Modules/Setup and maybe you have manually to exclude some extensions in 'setup.py'. If you restart the loop over and over again DON'T forget to clean with: make clean ; rm config.cache ; rm config.status Be sure to use gnu's make (gmake on some systems) binary. Carl From dieter at handshake.de Sun Jun 13 14:23:35 2004 From: dieter at handshake.de (Dieter Maurer) Date: 13 Jun 2004 20:23:35 +0200 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> Message-ID: balaji at email.arizona.edu (Balaji) writes on 12 Jun 2004 16:38:07 -0700: > Thanks for your reply. I see that the PEP and the current docs > specify that __ge__ and __le__ are their own reflection. > ... > Automatic reflection prevents the resulting objects from being > dependant on the ordering of the arguments to __ge__ and __le__. In > our application, this ordering is important. ? The order of "__ge__" and "__le__" operands is always important -- not only in your application... I read the documentation as "__le__" is the reflection of "__ge__" and vice versa. This seems to be senseful. > Can anyone think of a way to get around automatic reflection of > relational operators? Define the respected operators for both operands. Then, there is no need for reflection. Dieter From python1 at spamless.net Thu Jun 17 18:43:47 2004 From: python1 at spamless.net (python1) Date: Thu, 17 Jun 2004 15:43:47 -0700 Subject: Parsing by Line Data In-Reply-To: References: Message-ID: Bill Dandreta wrote: > python1 wrote: > >> ...lines in a file, for example: >> >> 01A\n >> 02B\n >> 01A\n >> 02B\n >> 02C\n >> 01A\n >> 02B\n >> . >> . >> . >> >> The lines beginning with '01' are the 'header' records, whereas the >> lines beginning with '02' are detail. There can be several detail >> lines to a header. >> >> I'm looking for a way to put the '01' and subsequent '02' line data >> into one list, and breaking into another list when the next '01' >> record is found. >> >> How would you do this? I'm used to using 'readlines()' to pull the >> file data line by line, but in this case, determining the break-point >> will need to be done by reading the '01' from the line ahead. Would >> you need to read the whole file into a string and use a regex to break >> where a '\n01' is found? > > > First let me prface my remarks by saying I am not much of a programmer > so this may not be the best way to solve this but I would use a > dictionary someting like this (untested): > > myinput = open(myfile,'r') > lines = myinput.readlines() > myinput.close() > > mydict = {} > index = -1 > > for l in lines: > if l[0:2] == '01' > counter = 0 > index += 1 > mydict[(index,counter)] = l[2:] > else: > mydict[(index,counter)] = l[2:] > counter += 1 > > You can easy extract the data with a nested loop. > > Bill Thanks Bill. Will use this script in place of Eddie's if python is sub 2.2 on our Aix box. Thanks again. From peter at engcorp.com Mon Jun 21 02:02:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 02:02:48 -0400 Subject: String concatenation In-Reply-To: References: Message-ID: Jonas Galvez wrote: > Is it true that joining the string elements of a list is faster than > concatenating them via the '+' operator? > > "".join(['a', 'b', 'c']) > > vs > > 'a'+'b'+'c' > > If so, can anyone explain why? It's because the latter one has to build a temporary string consisting of 'ab' first, then the final string with 'c' added, while the join can (and probably does) add up all the lengths of the strings to be joined and build the final string all in one go. Note that there's also '%s%s%s' % ('a', 'b', 'c'), which is probably on par with the join technique for both performance and lack of readability. Note much more importantly, however, that you should probably not pick the join approach over the concatenation approach based on performance. Concatenation is more readable in the above case (ignoring the fact that it's a contrived example), as you're being more explicit about your intentions. The reason joining lists is popular is because of the terribly bad performance of += when one is gradually building up a string in pieces, rather than appending to a list and then doing join at the end. So l = [] l.append('a') l.append('b') l.append('c') s = ''.join(l) is _much_ faster (therefore better) in real-world cases than s = '' s += 'a' s += 'b' s += 'c' With the latter, if you picture longer and many more strings, and realize that each += causes a new string to be created consisting of the contents of the two old strings joined together, steadily growing longer and requiring lots of wasted copying, you can see why it's very bad on memory and performance. The list approach doesn't copy the strings at all, but just holds references to them in a list (which does grow in a similar but much more efficient manner). The join figures out the sizes of all of the strings and allocates enough space to do only a single copy from each. Again though, other than the += versus .append() case, you should probably not pick ''.join() over + since readability will suffer more than your performance will improve. -Peter From ruach at chpc.utah.edu Thu Jun 3 06:06:31 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 04:06:31 -0600 Subject: python uid uname manipultaion/fetching Message-ID: Is there anything in the standard library that will convert a uid to a username ? or do I have to parse the /etc/passwd ? thanks -matthew From davidf at sjsoft.com Wed Jun 30 08:14:10 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 14:14:10 +0200 Subject: wxPython syntax In-Reply-To: References: Message-ID: John Taylor wrote: > David Fraser wrote in message > >>One of the main things that would need to be addressed is how sizers and >>layout could be defined using this approach >> >>David > > > The easiest (and therefore best, imho) way that I have ever seen to > manage widget layout is in Java's RelativeLayout. See > http://www.onjava.com/pub/a/onjava/2002/09/18/relativelayout.html > Within this, layout is controlled by a xml file. Thanks for the link, interesting article. > Does anyone know if any of the python gui toolkits have something > similar to this? > Not the xml file, but the methodology itself. Not sure. I'm sure you could create a similar methodology layout class for wxPython though... David From davidf at sjsoft.com Mon Jun 14 02:25:05 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 14 Jun 2004 08:25:05 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: References: Message-ID: Tim Peters wrote: > [David Fraser] > >>Is it possibile to have a better algorithm for binary to base 10 >>conversion, or is that limited to quadratic time? > > > Sub-quadratic general base-conversion algorithms certainly exist. Practical > implementations are complex and long-winded, and I doubt Python will ever > have one natively. > > >>Any links to papers/discussions on this? > > > There's a huge literature on asymptotic complexity of elementary arithmetic > operations on unbounded ints, and that's relevant because general base > conversion boils down to multiplication and division. Unless your interest > is purely theoretical, I recommend searching GMP discussions. For example, > here's a pointer into a thread from last December giving an overview of what > GMP developers were planning to try at that time: > > "mpf_get_str() is slow for big numbers?" > http://www.swox.com/list-archives/gmp-discuss/2003-December/000901.html Thanks Tim David From sdahlbacSPAMSUCKS at abo.fi Wed Jun 23 14:22:57 2004 From: sdahlbacSPAMSUCKS at abo.fi (Simon Dahlbacka) Date: Wed, 23 Jun 2004 21:22:57 +0300 Subject: http knowledge sought In-Reply-To: References: <6r3Cc.861817$Ig.9977@pd7tw2no> Message-ID: <40d9caa7$1@newsflash.abo.fi> Elaine Jackson wrote: > "Graham Fawcett" wrote in message > news:e9570f37.0406222237.39372ee0 at posting.google.com... > > > | Please elaborate! > > OK. It would be nice to know a way in which somebody on another machine could > access the pages your example serves. Not necessarily a cute or convenient way, > but just a way. That would give me the foot-in-the-door feeling I'm looking for. unless there is firewalls in between you'll just need to browse to http://your.ip.address.goes.here/ (the IP has to be a public one..) i.e. http://123.123.123.123/ From claudio.grondi at freenet.de Sun Jun 13 17:47:28 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 13 Jun 2004 21:47:28 -0000 Subject: How to get decimal form of largest known prime? References: Message-ID: <2j3pb9Ft3kn2U1@uni-berlin.de> >>"Tim Peters" >>The fastest pure-Python solution I've found consumed about 20 CPU minutes I have already used such approach (see code below), but was not able to get any improvement, even the opposite because of increase of time needed forcalculation for each next iteration step. Is my code not well designed? What is the difference to yours? (consider please, that I started with Python some weeks ago and just trying to check out the advantages and the limits) Claudio P.S. Here the code: intExponent = 24036583 intBaseOfNumericSystem = 10**5000 dctPrimeAsIntDigits = {} import math intMaxIterExponent = int('%.0f'%( \ round(math.log(intBaseOfNumericSystem,2) - 0.501),)) if(intMaxIterExponent > intExponent): intMaxIterExponent = intExponent #: if intDigitIndx = 0 dctPrimeAsIntDigits[intDigitIndx] = 2**intMaxIterExponent intShiftValue = 0 intExponentCounter = intMaxIterExponent \ + intMaxIterExponent import time floatBegTime = time.clock() floatCurrTime = time.clock() while(intExponentCounter < intExponent): # loop over the exponent print intExponentCounter \ , time.clock() - floatBegTime \ , time.clock() - floatCurrTime floatCurrTime = time.clock() intDigitIndx = 0 intShiftValue = 0 intLenLstPrime = len(dctPrimeAsIntDigits) while(intDigitIndx < intLenLstPrime): # loop over the digits intDigit = dctPrimeAsIntDigits[intDigitIndx] if( (intLenLstPrime-1) == intDigitIndx ): intNewShiftValue, intNewDigitValue = \ divmod( ((2**intMaxIterExponent) * intDigit) \ + intShiftValue, intBaseOfNumericSystem \ ) dctPrimeAsIntDigits[intDigitIndx] = \ intNewDigitValue if( intNewShiftValue ): dctPrimeAsIntDigits[intDigitIndx+1] = \ intNewShiftValue intShiftValue = 0 #: if break #: if intNewShiftValue, intNewDigitValue = \ divmod( ((2**intMaxIterExponent) * intDigit) \ + intShiftValue, intBaseOfNumericSystem \ ) dctPrimeAsIntDigits[intDigitIndx] = intNewDigitValue intShiftValue = intNewShiftValue intDigitIndx = intDigitIndx + 1 #: while() # loop over digits of the number intExponentCounter = intExponentCounter \ + intMaxIterExponent #: while(intExponentCounter) # loop over exponent value intExponentCounter = intExponentCounter \ - intMaxIterExponent intRemainingExponent = intExponent - intExponentCounter print intRemainingExponent intDigitIndx = 0 intLenLstPrime = len(dctPrimeAsIntDigits) while(intDigitIndx < intLenLstPrime): # loop over the digits of the number intDigit = dctPrimeAsIntDigits[intDigitIndx] if( (intLenLstPrime-1) == intDigitIndx ): intNewShiftValue, intNewDigitValue = \ divmod( ((2**intRemainingExponent) * intDigit) \ + intShiftValue, intBaseOfNumericSystem \ ) dctPrimeAsIntDigits[intDigitIndx] = intNewDigitValue if( intNewShiftValue ): dctPrimeAsIntDigits[intDigitIndx+1] = intNewShiftValue intShiftValue = 0 #: if break #: if intNewShiftValue, intNewDigitValue = \ divmod( ((2**intRemainingExponent) * intDigit) \ + intShiftValue, intBaseOfNumericSystem \ ) dctPrimeAsIntDigits[intDigitIndx] = intNewDigitValue intShiftValue = intNewShiftValue intDigitIndx = intDigitIndx + 1 #: while(intDigitIndx < len(lstPrimeAsIntDigits)) # loop over digits of the number print intExponentCounter \ , time.clock() - floatBegTime \ , time.clock() - floatCurrTime floatCurrTime = time.clock() lstPrimeAsStrDigits = [] for intDigitIndx in \ range(len(dctPrimeAsIntDigits)-1, -1, -1): lstPrimeAsStrDigits.append( \ '%i'%dctPrimeAsIntDigits[intDigitIndx]) print 'append(): ' \ , time.clock() - floatBegTime \ , time.clock() - floatCurrTime floatCurrTime = time.clock() print ''.join(lstPrimeAsStrDigits) print 'join(): ' \ , time.clock() - floatBegTime \ , time.clock() - floatCurrTime floatCurrTime = time.clock() And here the first output lines on my machine (Pentium 4, 2.8 GHz, 400 MHz dual RAM): Exponent TotalTime TimeForCurrIteration: 33218 1.64825417756e-005 2.40253998762e-005 49827 0.0148541225212 0.0148295383911 66436 0.0447663040973 0.0299105053855 83045 0.0893624748397 0.0445875104238 ... 15014536 6956.48563854 23.4220966631 15031145 6978.40485984 21.9192143136 ... 22422150 16369.6005045 26.9602413156 22438759 16397.0206864 27.4201684851 ... etc. (python is still running with 4 hours 17 minutes CPU time) From fperez528 at yahoo.com Tue Jun 15 01:32:38 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 14 Jun 2004 23:32:38 -0600 Subject: newbie question-multidimensional arrays References: Message-ID: Doug Jordan wrote: > How do you define and access multidimensional arrays in Python? I am new > to python and come from a C and FORTRAN background and I am not sure how to > define an array without giving the contents of the array. Any help will be > appreciated. I would like to be able to read and manipulate > multidimensional arrays using a nested loop. I cannot find anything in the > documentation to help me. google for: Numpy, Scipy, weave, f2py, numarray scipy is the grand wrapper which will give you on top of Numeric/Numarray (the array library proper) a ton of other stuff: special functions, numerical methods, fortran code wrapping, and out-of-the box wrappers to most/all of blas and lapack. For plotting/visualization (which you'll eventually need), matplotlib, gnuplot.py and MayaVi should be on your list. For PostScript/LaTeX algorithmic generation, PyX is an amazing tool. Cheers, f From russblau at hotmail.com Wed Jun 16 09:02:18 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 16 Jun 2004 09:02:18 -0400 Subject: Is it possible to have instance variables in subclasses of builtins? References: Message-ID: <2jav23Fvapt0U1@uni-berlin.de> "Kenneth McDonald" wrote in message news:slrnccutjp.3qk.kenneth.m.mcdonald at g4.gateway.2wire.net... > I've recently used subclasses of the builtin str class to good effect. > However, I've been unable to do the following: > > 1) Call the constructor with a number of arguments other than > the number of arguments taken by the 'str' constructor. > > 2) Create and use instance variables (eg. 'self.x=1') in > the same way that I can in a 'normal' class. > > As an example of what I mean, here's a short little session: > > >>> class a(str): > ... def __init__(self, a, b): > ... str.__init__(a) > ... self.b = b > ... > >>> x = a("h", "g") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: str() takes at most 1 argument (2 given) > >>> The problem is that "str" is an immutable type. Therefore, to change the constructor, you need to override the __new__ method. See http://www.python.org/2.2.1/descrintro.html#__new__ Here's an example: >>> class two(str): def __new__(cls, a, b): return str.__new__(cls, a) def __init__(self, a, b): self.b = b >>> z = two("g", "h") >>> z 'g' >>> z.b 'h' Note that both arguments (a and b) get passed to both the __new__ and __init__ methods, and each one just ignores the one it doesn't need. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From dbasch at yahoo.com Wed Jun 16 19:17:23 2004 From: dbasch at yahoo.com (Derek Basch) Date: Wed, 16 Jun 2004 23:17:23 GMT Subject: Regular expression, "except end of string", question. Message-ID: Hello, I have a string like: string = "WHITE/CLARET/PINK/XL" which I need to alter to this format: string = "WHITE-CLARET-PINK/XL" I developed the below functions to do so. However, something is wrong with my regular expression. It currently matches with the following: /CLARET /PINK /XL I thought perhaps I could exclude the match that includes the end of the string with someting like this: r"([/]\w+[^$])" but that didnt work either. Can anyone tell me how to exclude the last match? The one with the end of the string "/XL". Thanks a million, Derek Basch ------------------------------------------------ import re string = "WHITE/CLARET/PINK/XL" def replace_fs(thematch): thematch = thematch.group(1) thematch = "-" + thematch[1:] return thematch bs_regex = re.compile(r"([/]\w+)").sub(replace_fs, str(string)) print bs_regex From chuck at smtl.co.uk Tue Jun 8 11:26:41 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 16:26:41 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Mon, 07 Jun 2004 19:48:49 GMT." <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> Message-ID: <200406081526.i58FQfeb000391@sevenofnine.smtl.co.uk> Hi using the breakdown script I managed this minis mail.read() just print mail. mbox = mailbox.UnixMailbox(fp) for mail in mbox: print mail break #just look at one message Here's the output of the script. Cheers chuck chuck at sevenofnine:~/pythonScript> python testmail.py Return-Path: Received: from enterprise.smtl.co.uk (enterprise.smtl.co.uk [193.131.77.1***]) by ds9.smtl.co.uk (8.12.10/8.11.0) with ESMTP id i4PDJXgN006468 for ; Tue, 25 May 2004 14:19:35 +0100 Message-Id: <200405251319.i4PDJXgN006468 at ds9.smtl.co.uk> Subject: WWW Survey To: testwwws at smtl.co.uk From: testwwws at smtl.co.uk Date: Tue, 25 May 2004 14:19:14 +0100 X-Spam-Checker-Version: SpamAssassin 2.63 (2004-01-11) on ds9.smtl.co.uk X-Spam-Status: No, hits=0.3 required=5.0 tests=NO_REAL_NAME autolearn=no version=2.63 X-Spam-Level: chuck at sevenofnine:~/pythonScript> From grante at visi.com Sun Jun 27 14:49:08 2004 From: grante at visi.com (Grant Edwards) Date: 27 Jun 2004 18:49:08 GMT Subject: wxPython syntax References: <40df14b6$0$78546$a1866201@newsreader.visi.com> Message-ID: <40df16a4$0$78546$a1866201@newsreader.visi.com> In article <40df14b6$0$78546$a1866201 at newsreader.visi.com>, Grant Edwards wrote: >> I've started taking a look at wxPython, and, well, I've >> noticed that the syntax needed to code with it is extremely >> ugly. > > Yup -- we just had this discussion a couple weeks ago. Google the group for the subject line "Don't understand wxPython ids". The bottom line is that un-pythonic syntax of wxPython reflects the un-pythonic syntax of the underlying C++ library. Two of the fundamental decisions that makes wxWidgets complex and difficult to work with compared to most other widget sets are 1) Using the "object-ID/event-ID" scheme to hook handlers to events rather that making handlers attributes of widgets. It's a more general/powerful scheme, but for small apps like I write it's just gratuitous complexity. 2) Making the widget hierarchy separate from the layout hierarchy. Again, it's a more general and powerful way to do things, but for the small apps I write it's added work and complexity with no benefit. -- Grant Edwards grante Yow! I'd like TRAINED at SEALS and a CONVERTIBLE on visi.com my doorstep by NOON!! From troy at gci.net Wed Jun 16 04:10:39 2004 From: troy at gci.net (Troy Melhase) Date: Wed, 16 Jun 2004 00:10:39 -0800 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: Message-ID: <200406160010.39050.troy@gci.net> On Tuesday 15 June 2004 10:53 pm, Andrea Griffini wrote: > On Tue, 15 Jun 2004 22:01:19 -0800, Troy Melhase wrote: > >Or even this: > > > >shared_cache = {} > > > >def F(a, b, cache=shared_cache): > > ... > > A global you mean ? Why not just saying "global shared_cache" > at the start of the function ? The shared_cache dictionary is mutable, making the global statement redundant at best. It could have just as easily been left out of the function argument list. The definition above would also allow clients of the function to pass in a cache of their choosing. (Granting, of course, that this would most likely be an obscure use.) > If you need more power than a global then you probably a > (callable) class is going to serve you better than a function. Of course. I was trying to illustrate using a named module-level dict instead of a mutable value that could not be accessed outside of the function body. > Is really a feature that if someone passes (by mistake) an extra > parameter to the function the script silently swallows it and > behaves strangely ? Or you also double-wrap the function, so > that a(x,y) calls real_a(x,y,cache=[]) ? How many times have you passed an extra parameter by mistake? This is Python, and one of the mottos is "we're all consenting adults". > >Of course you can argue that this is bad style, but the counter argument > > is just as strong: this is quite pythonic and quite readable. > > Pythonic ? In the sense that this is for example more explicit ? > Are you kidding ? No, I'm not. The function specified a muteable argument. Nothing implicit about it. > That something is used is one thing. That something is elegant > is another. Of course. But using a mutable default function parameter as a cache is elegant as far as I'm concerned. -- Troy Melhase, troy at gci.net -- I have sworn upon the altar of God eternal hostility against every form of tyranny over the mind of man. - Thomas Jefferson From grante at visi.com Tue Jun 29 12:40:07 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jun 2004 16:40:07 GMT Subject: win32 pyserial requires javax.comm for py2exe? Message-ID: I'm trying to package a small Python program using py2exe. Everything works fine until I add an "include serial", then py2exe fails because The following modules appear to be missing ['javax.comm'] Apparently serial.py imports a both the posix and java versions of things even on a win32 platform? ------------------------------setup.py------------------------------ # setup.py from distutils.core import setup import py2exe setup(console=["testit.py"]) -------------------------------------------------------------------- ------------------------------testit.py------------------------------ import serial print "hello" --------------------------------------------------------------------- ----------------------python setup.py py2exe------------------------- running py2exe *** searching for required modules *** *** parsing results *** creating python loader for extension '_sre' creating python loader for extension 'datetime' creating python loader for extension 'win32file' creating python loader for extension 'select' creating python loader for extension 'win32event' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** skipping byte-compilation of C:\PYTHON23\lib\copy_reg.py to copy_reg.pyc skipping byte-compilation of C:\PYTHON23\lib\sre_compile.py to sre_compile.pyc skipping byte-compilation of C:\PYTHON23\lib\locale.py to locale.pyc byte-compiling C:\cygwin\home\admin\othertools\build\bdist.win32\winexe\temp\_sre.py to _sre.pyc skipping byte-compilation of C:\PYTHON23\lib\macpath.py to macpath.pyc skipping byte-compilation of C:\PYTHON23\lib\popen2.py to popen2.pyc byte-compiling C:\cygwin\home\admin\othertools\build\bdist.win32\winexe\temp\datetime.py to datetime.pyc skipping byte-compilation of C:\PYTHON23\lib\atexit.py to atexit.pyc byte-compiling C:\cygwin\home\admin\othertools\build\bdist.win32\winexe\temp\win32file.py to win32file.pyc skipping byte-compilation of C:\Python23\Lib\site-packages\serial\serialwin32.py to serial\serialwin32.pyc skipping byte-compilation of C:\Python23\Lib\site-packages\serial\__init__.py to serial\__init__.pyc skipping byte-compilation of C:\Python23\Lib\site-packages\serial\serialjava.py to serial\serialjava.pyc byte-compiling C:\cygwin\home\admin\othertools\build\bdist.win32\winexe\temp\select.py to select.pyc byte-compiling C:\cygwin\home\admin\othertools\build\bdist.win32\winexe\temp\win32event.py to win32event.pyc skipping byte-compilation of C:\PYTHON23\lib\linecache.py to linecache.pyc skipping byte-compilation of C:\PYTHON23\lib\sre_constants.py to sre_constants.pyc skipping byte-compilation of C:\PYTHON23\lib\re.py to re.pyc skipping byte-compilation of C:\PYTHON23\lib\ntpath.py to ntpath.pyc skipping byte-compilation of C:\Python23\Lib\site-packages\serial\serialposix.py to serial\serialposix.pyc skipping byte-compilation of C:\PYTHON23\lib\stat.py to stat.pyc skipping byte-compilation of C:\PYTHON23\lib\string.py to string.pyc skipping byte-compilation of C:\PYTHON23\lib\warnings.py to warnings.pyc skipping byte-compilation of C:\PYTHON23\lib\UserDict.py to UserDict.pyc skipping byte-compilation of C:\PYTHON23\lib\repr.py to repr.pyc skipping byte-compilation of C:\PYTHON23\lib\copy.py to copy.pyc skipping byte-compilation of C:\PYTHON23\lib\types.py to types.pyc skipping byte-compilation of C:\PYTHON23\lib\posixpath.py to posixpath.pyc skipping byte-compilation of C:\PYTHON23\lib\FCNTL.py to FCNTL.pyc skipping byte-compilation of C:\Python23\Lib\site-packages\serial\serialutil.py to serial\serialutil.pyc skipping byte-compilation of C:\PYTHON23\lib\sre.py to sre.pyc skipping byte-compilation of C:\PYTHON23\lib\TERMIOS.py to TERMIOS.pyc skipping byte-compilation of C:\PYTHON23\lib\os2emxpath.py to os2emxpath.pyc skipping byte-compilation of C:\PYTHON23\lib\_strptime.py to _strptime.pyc skipping byte-compilation of C:\PYTHON23\lib\calendar.py to calendar.pyc skipping byte-compilation of C:\Python23\Lib\site-packages\win32\lib\win32con.py to win32con.pyc skipping byte-compilation of C:\PYTHON23\lib\sre_parse.py to sre_parse.pyc skipping byte-compilation of C:\PYTHON23\lib\os.py to os.pyc *** copy extensions *** *** copy dlls *** copying C:\Python23\Lib\site-packages\py2exe\run.exe -> C:\cygwin\home\admin\othertools\dist\testit.exe The following modules appear to be missing ['javax.comm'] --------------------------------------------------------------------- -- Grant Edwards grante Yow! We just joined the at civil hair patrol! visi.com From grey at despair.dmiyu.org Mon Jun 14 18:58:08 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 14 Jun 2004 22:58:08 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: On 2004-06-14, Carl Banks wrote: > Of course you can. > import glob > import os > import re > f = {} > for pattern in ("*.rar.*","*.r[0-9][0-9].*"): > for listing in glob.glob(prefix+pattern): > f[listing] = None > for filename in f: > os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) Ah, grab anything with a rar extension and more (badly split usenet binaries?) and splice them together. > I don't know what sesc is. I assume he had defined it elsewhere, Stab in the darb based on the cat call as well as the purpose of this snippet I would surmise "space escape". IE, escape possible spaces in the file name so as not to flub the command line that hits the system call. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From mithrandi at mithrandi.za.net Sun Jun 27 09:34:00 2004 From: mithrandi at mithrandi.za.net (Tristan Seligmann) Date: Sun, 27 Jun 2004 15:34:00 +0200 Subject: help with creating a mysql query string In-Reply-To: References: <3SvDc.22042$NK4.3722156@stones.force9.net> Message-ID: <20040627133400.GB21968@mithrandi.za.net> On Sun, Jun 27, 2004 at 07:58:09 -0400, Sean Ross wrote: > > "RiGGa" wrote in message > news:3SvDc.22042$NK4.3722156 at stones.force9.net... > [snip] > > > > sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" > > > [snip] > > sqlquery = "INSERT INTO " + tablename + " values(%s,%s,%s)"%datavalue Rather do something like: sqlquery = "INSERT INTO %s values(%%s,%%s,%%s)" % tablename cursor.execute(sqlquery, datavalue) The other way allows datavalue to contain arbitrary SQL that will be executed, which can be a nasty security hole depending on where the value comes from. -- mithrandi, i Ainil en-Balandor, a faer Ambar -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tim.golden at viacom-outdoor.co.uk Mon Jun 28 05:24:31 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 28 Jun 2004 10:24:31 +0100 Subject: sending signals to the calling function Message-ID: | I have a function that receive a list of files and creates a zip from | these files. I want it to send signal to the calling function with the | name of the file it currently compressing. is there a way to do this | (without threads)? Of course, just pass in a callback function, and call that whenever a file is being compressed. Alternatively, make the zipper-upper a generator which yields its current filename: import os, sys import zipfile def zipup (zip_filename, list_of_files): archive = zipfile.ZipFile (zip_filename, "w") for filename in list_of_files: yield filename archive.write (filename) archive.close () if __name__ == '__main__': import glob file_pattern = os.path.join (sys.path[-1], "*") list_of_files = [f for f in glob.glob (file_pattern) if os.path.isfile (f)] for zipping_file in zipup ("test.zip", list_of_files): print "About to zip", zipping_file TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From mark at pyzine.com Sun Jun 27 18:16:32 2004 From: mark at pyzine.com (Mark) Date: Sun, 27 Jun 2004 18:16:32 -0400 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: <40DF40C0.9503E50D@alcyone.com> References: <40DF40C0.9503E50D@alcyone.com> Message-ID: Hello Erik, >> I honestly find your characterzation very unfair. Regarding payment to >> the >> Python Software Foundation this is what I wrote: > ... >> I take full responsibility and will get an email by Monday *and you >> will be paid* latest by Wednesday if you have a Paypal account. Sorry. > > Seems like it's a little silly to call his characterization unfair when > he hasn't even been paid yet. (Now, he himself doesn't worry too much > about getting paid, that's not why he did it, but surely the most > fundamental contract between a writer and his publisher is that the > writer actually gets paid for it.) Please reread the explanation at the top of my previous email. Because I'm not sure you did. The original "contract" was that Py did not pay for article submissions. When we took over publication we had a mix of articles covered by the "old contract" i.e. no payment and those that we contacted authors to write. In the case of Py 5 it was a mix of articles and the primary goal was not to see the work of these authors go to waste (that articles not be published at all) In individual cases were articles had to be rewritten or heavily updated (in some cases these articles had been submitted almost 2 years ago and needed some serious work) we were willing to pay these articles according to the new terms even thought these articles had been submitted (without expectation of payment) to the previous publisher. So the first real issue that we produced, commissioned authors to write (and be paid for) was Issue 6. But I agree wholeheartedly with you that authors should be paid for their work and disagree for example with other sentiments raised on this mailinglist that authors should be expected to be happy to write about Python for free. Cheers, Mark From oliver.schoenborn at utoronto.ca Sun Jun 6 08:56:55 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Sun, 6 Jun 2004 08:56:55 -0400 Subject: Using function parameters to determine method kind References: <4qrzym6e.fsf@telus.net> <95aa1afa.0404050417.2d11b369@posting.google.com> <8yh9r7p2.fsf@telus.net> <95aa1afa.0404060309.32629338@posting.google.com> Message-ID: From: "Michele Simionato" > No, I had in mind this (contrived) example: > > class Outer(object): > def outermeth(self1): > class Inner(object): > def innermeth(self2): > > ... > > It is nice to have the ability to give any name to "self". > like that). Strange, I would have thought that self1 would not be in scope (it's not in the local scope and it's not in the global scope AFAICT). If true, you'd have to have a parameter to your innermeth, which you can call whatever you want so call it self1. Have scoping rules changed in Python? Oliver From NOmanlio_perilloSPAM at libero.it Fri Jun 18 12:32:39 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Fri, 18 Jun 2004 16:32:39 GMT Subject: [PEP] auto keyword for automatic objects support in Python Message-ID: Hi. This post follows "does python have useless destructors". I'm not an expert, so I hope what I will write is meaningfull and clear. Actually in Python there is no possibility to write code that follows C++ RAII pattern. Of course Python objects are not statics like in C++, but in C++ the auto_ptr class is used for enforcing this pattern for dynamical allocated objects, by using a 'destructive' pointer semantic. Now, here is a simple example of Python code: >>> afile = file('foo.txt', 'w') >>> def use_file(afile): ... afile.write('hello') >>> use_file(afile) >>> afile.write(' word') Internally (at least in CPython) when the function is called, a frame object is created, with a dictionary of all local variables. When the function terminates the frame is 'deleted' (where 'deleted' means: 'its reference count is decremented'). The frame destructor then calls local variables destructors (again, local variables references counter are decremented). For our example this means that when use_file function exits, this equivalent Python code is execuded: >>> del afile Of course this not deletes afile, since there exists another reference to it. What I'm proposing is to add a new keyword 'auto'. Here its use: >>> afile = file('foo.txt', 'w') >>> auto afile >>> def use_file(afile): ... afile.write('hello') >>> use_file(afile) >>> afile.write(' word') # ==> error, file closed. See above Simply, auto objects behaves like C++ auto_ptr but with important differences and with the need of some support by the objects. This equivalent code is now executed when the function exits: >>> if hasattr(afile, '__deinit__'): afile.__deinit__() # see above >>> del afile With the use of auto there is the need(?) to think at object destruction as a two fase operation (like object creation with __new__ and __init__). In fact __del__ method is called when the object is being deallocated/garbage collected (actually this is not 'deterministic'). The RAII pattern requires simply that as an object goes 'out of scope' it should releases all the 'external resources' it has acquired. So there is the need of a second special method (call it __deinit__) that should be called for auto objects when they go 'out of scope' (in a 'deterministic' way). As an example, for a file object __deinit__ code is, of course, the same as in the __del__ code. More in detail: as __init__ creates the class invariant, __deinit__ should be 'destroy' it; that is, it should be put the instance in a 'neutral' state: all external resource released. The difference between __deinit__ and __del__ is that after __del__ is called the object is supposed to be deallocated/garbage collected; after __deinit__ the object is still 'live' in a 'neutral' state. So I think it is better to have two distinct methods. Issues: Q) Should be Frame objects be auto? R) They should be auto if there are auto local variables in it. Q) What about compound objects, ad example: >>> class hold_file: ... def __init__(self, afile): self.file = afile R) self.file should be auto if an hold_file instance is auto. Regards Manlio Perillo From NAIGIMSESRIMAIL at gims.com Thu Jun 24 12:25:32 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 24 Jun 2004 18:25:32 +0200 Subject: ALERT - GroupShield ticket number OB5_1088094300_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Larry Bates Sent: -869454720,29645319 Subject: Re: Testing for membership speed Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1824 bytes Desc: not available URL: From arcane at deepfort.com Mon Jun 21 09:17:43 2004 From: arcane at deepfort.com (Arcane) Date: Mon, 21 Jun 2004 14:17:43 +0100 Subject: [Python-Dev] (no subject) In-Reply-To: <20040618193909.GA9390@titan.progiciels-bpi.ca> References: <200406161313.34568.listuser@br.logorrhea.com> <20040618193909.GA9390@titan.progiciels-bpi.ca> Message-ID: <40D6DFF7.6030108@deepfort.com> Fran?ois Pinard wrote: >[Patrick Stinson] > > > >>if you had a hex string like '0x7c' how would you convert it to an >>int? int(0x7c) works, but not int('0x7c') >> >> > >This kind of question is better discussed on the `python' list than the >`python-dev' list. > >You may try int('0x7c', 16) if you know the base, or int(`0x7c', 0) if >you do not. The doc-string for `int' does not hint at using 0 as a base >when it has to be guessed, maybe this is an oversight? The Library >Reference Manual says all about it, however! :-) > > > int(eval('0x7c')) Marc From tim.one at comcast.net Fri Jun 11 15:38:29 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 15:38:29 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: Message-ID: [Tim Peters] >> That will pass under CPython today, but there's no general guarantee >> about exactly when a weak dict will notice that keys (or values) have >> become unreachable by strong references. [David MacQuigg] > OUCH!! We just built a module that uses weak references to keep a > "robust count" of instances in various classes. The claim is that this > is more robust than simply incrementing and decrementing class variables > using __init__ and __del__. The module seems to be working OK, > immediately deleting the weak reference as soon as all references to the > corresponding instance are deleted. Then it must be the case that you're running CPython, and that these instances aren't involved in cycles. Because CPython primarily uses reference-counting to recycle garbage, its behavior is predictable in the absence of cycles. CPython's use of reference counting is an implementation detail, and that internal weakref lists are traversed "immediately" upon an object's refcount reaching 0 is also an implementation detail. Nothing in the language definition guarantees these behaviors. > If I understand you correctly, there is some chance that a future > implementation of Python may have the weak references "out-of-sync" with > the actual count of live instances. Is that a remote possibility, or > something quite likely to occur? Well, it's been the case for a long time in JPython. I judge the odds of it changing in CPython as slim. I personally wouldn't worry about it ever changing in CPython. If a PyPy- or Parrot-based implementation of Python takes off, behavior will depend on its implementation details. > I have to decide now whether to rip out some risky code. > > Is there a good way to track the count of instances? If you want it enough, you can build Python in a mode that tracks this automatically (see the discussion of COUNT_ALLOCS in Misc/SpecialBuilds.txt -- for each distinct type object, the total # of allocations, # of deallocations, and highwater mark (max(#alloc - #dealloc) over time) are maintained in a COUNT_ALLOCS build). > If not, would it make sense to request a guarantee on the current > behavior of weak references? Maybe it could be an option, assuming there > is some performance penalty, an option to be used when accuracy is more > important than speed. You can request anything you can dream up . If it's something your business needs, the only way to guarantee it is to get involved in Python development deeply enough so that, if worse comes to worse, you can maintain your own Python implementation. That's unreasonably paranoid in my estimation, but it's a judgment call. From miki.tebeka at zoran.com Wed Jun 16 05:35:39 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 16 Jun 2004 11:35:39 +0200 Subject: how to become a really good Python programmer? In-Reply-To: References: Message-ID: <20040616093538.GC616@zoran.com> Hello Randall, > I've been programming in Python for about 2 years. I think it offers > the best combination of simplicity and power of any language I have > explored. As I write more and larger and complex programs, I need to > code better. By better I mean clearer, cleaner, more efficient and > maintainable. As the subject states, I want to become a really good > Python programmer. I learn most everything from random examples and > experience and that's good, but now I would like some sound, directed > guidance. Following Guido around would be ideal, but I will settle for > a good book. Any recommendations for learning resources? Apart from other recommendations you'll get I suggest you learn other programming languages. This will enable you to view problems in a different light. I recommend at least one lisp dialect (scheme is perfect for learning) and one prolog dialects. Both have free interpreters available (I recommend mzscheme and SWI prolog). HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From __peter__ at web.de Wed Jun 30 09:23:55 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jun 2004 15:23:55 +0200 Subject: sort accented string References: Message-ID: Laurent wrote: > I'm french and I have a small sorting problem with python (and zope's Try locale.strcoll(): >>> import locale >>> locale.setlocale(locale.LC_ALL, "fr_FR") 'fr_FR' >>> test = list("ab?fgz") >>> test.sort() >>> test ['a', 'b', 'f', 'g', 'z', '\xe9'] >>> test.sort(locale.strcoll) >>> test ['a', 'b', '\xe9', 'f', 'g', 'z'] >>> Peter From sebastien.chaumat at ens-lyon.fr Thu Jun 10 10:03:18 2004 From: sebastien.chaumat at ens-lyon.fr (sebastien.chaumat at ens-lyon.fr) Date: Thu, 10 Jun 2004 16:03:18 +0200 Subject: great xxx! Message-ID: pages? -------------- next part -------------- A non-text attachment was scrubbed... Name: yours.zip Type: application/x-zip-compressed Size: 25477 bytes Desc: not available URL: From __peter__ at web.de Fri Jun 11 06:00:35 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 12:00:35 +0200 Subject: Access atributes of different class.. References: <494182a9.0406101419.445069e7@posting.google.com> Message-ID: Balaji wrote: > Hello Everybody... > > This is what I'm trying to do.. > > from generation import* > > class codegeneration: > > def __init__(self,expr): > > self.LP={} > self.P=[] > self.F=1. > self= MatrixGenerator(expr) > self.stackManagement(expr) > > generation module has the method stackManagement and its defined in > class matrix generator. > > stackManagement return self. results..matrix Generator has an > dictionary self.results > > when stackManagement is called something gets into self.results. > > Now I want to access this self.results thru codegeneration. > > How can I do that.. See if you can get hold of an introductory text. What you want is inheritance (untested, of course): import generation class codegeneration(generation.MatrixGenerator): def __init__(self, expr): generation.MatrixGenerator.__init__(self, expr) self.LP = {} self.P = [] self.F = 1.0 self.stackManagement(expr) Peter From tjreedy at udel.edu Mon Jun 14 11:52:00 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jun 2004 11:52:00 -0400 Subject: help References: Message-ID: "Ru" wrote in message news:caje2u+q6a1 at eGroups.com... > does anyone have an algorithm (in python) for an LU decomposition > method? really need it. thanks Also look at Numerical Python and SciPy From mickel at csc.fi Fri Jun 4 08:38:32 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Fri, 4 Jun 2004 15:38:32 +0300 (EEST) Subject: Which is the most mature Soap module? In-Reply-To: References: <87d64jdpz3.fsf@pobox.com> Message-ID: On Fri, 4 Jun 2004, John J Lee wrote: > > 2. Is there a way to use cookie authentification with SOAPpy > > (client-side)? > > Yes, no reason why not to use my ClientCookie package to do that, but I > don't know from memory exactly where you need to insert the required code > in SOAPpy. Do you mean subclassing SOAPpy and changing the places where it uses urllib to talk to the server? (This might be totally off target -- I've been browsing the code in SOAPpy and I'm getting confused ...) > I'm slightly surprised if SOAP needs cookie handling, but not > entirely, since I know it is required for some XML-RPC services. I don't think SOAP needs cookies for anything. My problem is that the SOAP server for upload is only available if I have a certain cookie that I can send to the web server in the http header, i.e. the web server won't let me through to the SOAP server unless I can supply the cookie first. > I might have a look this weekend, but don't promise. If you have the time, that would be much appreciated! Have a nice weekend, /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From NAVMSE-ADMIN at ComConsult.de Thu Jun 10 06:37:25 2004 From: NAVMSE-ADMIN at ComConsult.de (NAV for Microsoft Exchange-ADMIN) Date: Thu, 10 Jun 2004 12:37:25 +0200 Subject: Norton AntiVirus detected and quarantined a virus in a message yo u sent. Message-ID: Recipient of the infected attachment: Spammails\Posteingang Subject of the message: Mail Delivery (failure) One or more attachments were quarantined. Attachment msg.zip was Quarantined for the following reasons: Virus W32.Netsky.P at mm was found. Virus W32.Netsky.P at mm was found in data.rtf .scr. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1765 bytes Desc: not available URL: From ed at leafe.com Tue Jun 15 12:47:08 2004 From: ed at leafe.com (Ed Leafe) Date: Tue, 15 Jun 2004 12:47:08 -0400 Subject: [ANN] Release 0.1.1 of Dabo Message-ID: We are pleased to announce the second public release of Dabo, the Python cross-platform 3-tier database application development product. This release adds preliminary database support for Firebird, adds a security/login manager, makes the business objects more robust, and fixes a lot of bugs. We've had a lot of positive feedback about Dabo in the last month, and are moving ahead with adding better support for various backend databases. We are still using wxPython exclusively for the UI; although Dabo is designed to work with any UI toolkit, we've had the best results with wxPython! You can download Dabo from http://dabodev.com/download. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From j_mckitrick at bigfoot.com Tue Jun 8 18:00:32 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 8 Jun 2004 15:00:32 -0700 Subject: Doc strings for a standalone app?? Message-ID: Does it make sense to use doc strings rather than #-comments for a standalone Python app? If the classes aren't going to be re-used or imported, do they need them? From klachemin at home.com Mon Jun 28 05:36:27 2004 From: klachemin at home.com (Kamilche) Date: 28 Jun 2004 02:36:27 -0700 Subject: Wow, THAT never happens in C! Message-ID: <889cbba0.0406280136.6f0f472f@posting.google.com> I just discovered the debugging flags for the garbage collector. Since I have an insanely hierachical structure to my dataset, with references all OVER the place, I thought I'd turn it on to make sure I wasn't leaking. Nothing happened. I searched the internet, and discovered how to 'force' a leak, so I tested with the single forced leak to see what would happen. It worked. My code did NOT have any leaks in it! :-D That's almost a miraculous occurrence when programming in C. I can't believe how much time I wasted trying to create my humongous project with C. :-( --Kamilche From peter at engcorp.com Wed Jun 23 18:06:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 18:06:54 -0400 Subject: how to obtain its ip address ? In-Reply-To: <10djtfsru7qeded@corp.supernews.com> References: <40d9c75d$0$26573$626a14ce@news.free.fr> <10djtfsru7qeded@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > Peter Hansen wrote: > >>marco wrote: >> >> >>>I'd search a lot ... but i had not found >>>how can i obtain my ip address (when i'm connected to the www) ?! >> >>You can probably search the archives for this list/newsgroup to >>find more complete answers (and hints about how else to solve it), >>but the short answer is "you can't". >> >>The longer answer is that (a) machines can have multiple addresses > . > Even more details appear at http://wiki.tcl.tk/MyOwnIPAddress >. Thanks Cameron. That's a pretty good page (especially if you like TCL), and it doesn't even get into issues relating to SNAT/DNAT, routers, firewalls, and the like, which many of us are behind these days... From anthony_raj at persistent.co.in Fri Jun 18 11:12:35 2004 From: anthony_raj at persistent.co.in (Anthony Raj) Date: Fri, 18 Jun 2004 11:12:35 -0400 Subject: Need to pass variables from mod_python publisher to standalone script. Message-ID: <40D30663.9090905@persistent.co.in> There's a problem which I'm trying to solve as elegently as possible. Its basically a setup that runs mod_python on Apache and its for a client that needs to generate dynamic reports by pulling out records from Postgres. Now once the report is generated , we mail the report in csv format to the requested mailid. We're trying to seperate the report generation / mailing part from the mod_python code by passing the report parameters to an external python script and processing & mailing the report externally from the httpd daemon . We want to do this because some of the reports take something like 5mins or more and its really painful for having to wait for the report to download etc. (believe me its about a couple million records in the db) . The solution I have is something like this 1. Create the a script test.py which can be called like so - ./test.py -b "{'username': ['motorola'], 'tmonth': ['1'], 'metrics_select': ['0'], 'dateperiod': ['2'], 'keyword': ['tablecloth']}" The parameter would actually be a dict that is processed by mod_python and converted into a string. 2. test.py has a function convert_both() which converts the string that is passed into a dictionary (attached below). The code works well so far. >>>>>> test.py >>>>>> #! /usr/bin/python import sys import getopt import t #for argv in sys.argv : print "args = ",argv def main(argv): try : opts , args = getopt.getopt(argv,"hg:b:d",["help","grammar="]) except getopt.GetoptError: sys.exit(2) for o,a in opts : if o in ("-b","--both"): return a if __name__ == "__main__": both = main(sys.argv[1:]) print "args(both) = ",both d = t.convert_both(both) print 'd = ',d # Other processing like db transactions & mailing csv files done later. 3. The issue is currently to be able to invoke this script from within a mod_python code . ./test.py -b "string from a dictionary" ( needs to be called from a python script to work) Also I have my doubts if this could be solved in any better way . ~Anthony From jimka at rdrop.com Tue Jun 8 13:38:28 2004 From: jimka at rdrop.com (Jim Newton) Date: Tue, 08 Jun 2004 19:38:28 +0200 Subject: promoting [] by superclass? In-Reply-To: References: Message-ID: <2imf46Fo9eusU1@uni-berlin.de> this is interesting. I though that if you passed an argument to your class factory function, it would call the __init__ with that argument. class x1(list): def __init__(y): pass class x2(list): pass what does x1([]) do and what does x2([]) do? -jim Robert Brewer wrote: > Jim Newton wrote: > >>class Pair(list): >> ... >> >>how can i "cast", "promote" [] to class Pair? > > >>>>class Pair(list): pass > > ... > >>>>p = Pair([]) >>>>p > > [] > >>>>type(p) > > > > Or was there some other behavior you had in mind? > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > From aahz at pythoncraft.com Wed Jun 16 19:37:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2004 19:37:02 -0400 Subject: Making classes from Metaclasses globally available References: Message-ID: In article , Jean-Fran?ois Doyon wrote: > >I'm using MetaClasses to create classes. Why? I'm serious; until we understand what you're trying to accomplish, we can't tell you the best way to accomplish your task. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From jcarlson at uci.edu Fri Jun 11 12:11:41 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 11 Jun 2004 09:11:41 -0700 Subject: Passing file descriptors In-Reply-To: References: Message-ID: >>Seemingly this is because I_SENDFD/I_RECVFD is not properly implemented >>on linux 2.4, but maybe I'm doing something wrong. > > > I'd say it's a fair bet that I_SENDFD is not implemented on Linux, > properly or otherwise. It looks to me like an AT&T STREAMS function, > as opposed to Berkeley socket. Casual look around the include files > doesn't suggest any support on Linux for any STREAMS stuff. > > As usual, there's a parallel Berkeley way to do this, using as > already mentioned a UNIX domain socket, and sendmsg, and SCM_RIGHTS. > > If Python's socketmodule.c doesn't directly support sendmsg and > the attendant data structures, you'll have to add that in C, either > in socketmodule.c or your own module. That means mainly getting > the msghdr struct together (I think the control object you want > to pass, with SCM_RIGHTS and the fds can be packed up in Python.) Since I'm going to have to write a wrapper anyways, I may as well spend some time learning Pyrex and gain python garbage collection. Thank you for the information, - Josiah From tim.one at comcast.net Fri Jun 11 15:50:34 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 15:50:34 -0400 Subject: does python have useless destructors? In-Reply-To: Message-ID: [Delaney, Timothy C] >>> myfile = open("myfilepath", "w") >>> >>> try: >>> myfile.write(reallybigbuffer) >>> finally: >>> myfile.close() [Tim Bradshaw] >> I don't think this is save. Is it certain that there can be no problem >> between the open and the try? [Peter Hansen] > Yes, it's certain to be safe (barring multithreaded stuff rebinding > 'myfile' in between, which is irrelevant to the discussion). Are you > perhaps concerned that the open itself might fail? If so, it needs its > own try/except block, as I noted elsewhere. The finally is only need > *if* the open succeeds, but unless you insert code between open() and > 'try', it's safe. Believe it or not, it isn't entirely "safe", but for a different reason: it's quite possible for, e.g., KeyboardInterrupt to get raised and processed between the "finally:" and the "myfile.close()" -- Google on "safe asynchronous exceptions for python" for a good paper on the topic. From peufeu at free.fr Tue Jun 22 03:09:42 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Tue, 22 Jun 2004 09:09:42 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <7eo6d0les48q8e7caukrp5emovid67ain0@4ax.com> Message-ID: Ah, simple. I think Zope is an enormously complex, difficult to learn software which can apparently do anything, but is so complex to use you can really only use already-developed modules. Besides Zope is more suited to sites chere people edit articles. I also don't like it because of ZODB, which is basically a reinvented, slower filesystem, and also because it forces its mode of thoughts upon you. On the other hand, Skunkweb is just a framework, it does what you want (beautifully), and doesn't get in the way the rest of the time. You should try it... > Pierre-Fr?d?ric Caillaud: >> google skunkweb >> really nice, cool, fast >> powerful embedded templating engine >> full power of python (not at all like Zope) > > Would you care to elaborate on the differences with Zope? > -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From noway at nohow.com Sat Jun 26 22:23:19 2004 From: noway at nohow.com (Paul M) Date: Sun, 27 Jun 2004 02:23:19 GMT Subject: MySQL error from Python References: <4r7sd0h1ris3gdsk1ejqeq4gij606pep69@4ax.com> Message-ID: That fixed it. Thank You! "Dennis Lee Bieber" wrote in message news:4r7sd0h1ris3gdsk1ejqeq4gij606pep69 at 4ax.com... > On Sun, 27 Jun 2004 00:04:54 GMT, "Paul M" declaimed > the following in comp.lang.python: > > > > cursor.execute ("UPDATE product SET price = '%s' WHERE competitorID=1 > > AND sku = '%s'",(myprice,mysku)) > > Get rid of the single quotes around the %s fields... The > .execute method should, in theory, determine the data type and needed > quoting internally. > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From tim.peters at gmail.com Mon Jun 21 21:40:27 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 21 Jun 2004 21:40:27 -0400 Subject: zope acquistion In-Reply-To: References: Message-ID: <1f7befae040621184046f5336@mail.gmail.com> [John Hunter] > I know this post is better on the zope mailing list (in fact I posted > it there). It certainly would be. > But for some reason my posts there are being help for days > before getting through I'm afraid it's futile: mail.zope.org and mail.python.org are the same physical machine, and it's on its knees fighting floods of spam, viruses, and bounces from spam and viruses forged to appear as if they had been sent from a python.org or zope.org address. The load average was 70 last week, but the sheer mass of junk mail actually makes it I/O-bound. The good news is that nobody has time to work on it . From flupke at nonexistingdomain.com Fri Jun 4 22:33:34 2004 From: flupke at nonexistingdomain.com (flupke) Date: Sat, 05 Jun 2004 02:33:34 GMT Subject: heredoc and variables References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> Message-ID: <2iawc.144663$Cs7.7551038@phobos.telenet-ops.be> Peter Otten wrote: > flupke wrote: > >> 2) Consider following heredoc >> >> end_html=""" >> """ >> >> I have to write it like this to avoid having an empty line added >> above AND below the actual string when using it. > > Why would you care about whitespace in HTML? For the same reason i care about nicely spaced code. To make it readable. I do not use any HTML editor so i want the html code to be clean and easily readable. >>>> print """\ > ... here's how \ > ... to escape \ > ... newlines""" > here's how to escape newlines >>>> > > Peter Thanks From reinhold-birkenfeld-nospam at wolke7.net Sat Jun 19 07:10:20 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 19 Jun 2004 13:10:20 +0200 Subject: strange behaviour with remove In-Reply-To: <40d41aab$0$8312$626a14ce@news.free.fr> References: <40d41877$0$32493$626a14ce@news.free.fr> <40d41aab$0$8312$626a14ce@news.free.fr> Message-ID: <2jil23FvjpusU1@uni-berlin.de> Panard wrote: > Ok, I reply to myself, it's working when you add, line 3 > l = [ i for i in l ] > > I think the reason is that when you do a remove on d[ 'list' ] it will also > do a remove on l, because, I think, l in the dictionnary is only a > reference... You're partially right. The list referenced to by d['list'] is the same object as the list referenced to by l (to verify this, do a "print d['list'] is l"). The main reason that your loop does not work is that it modifying a list you are iterating over leads to undefined behavior. In your solution above, you are assigning a new list to the name "l", iterate over this list, and remove from the original list which is now only referenced by d['list']. This is the common solution for the problem, although there is an easier way to copy a list: l = l[:] Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From zathras at thwackety.com Sat Jun 12 15:52:52 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 12 Jun 2004 20:52:52 +0100 (BST) Subject: Language Suitablilty In-Reply-To: Message-ID: On Sat, 12 Jun 2004, Jens Thiede wrote: > I'd like to know what other people think about Python. In particular, what > is Python best suited for? Programs you want to get done, run at a reasonable speed with clear places and routes for optimisation should that _need_ to happen, and have fun along the way. In more concrete terms, I would take this to mean data rich applications using databases, algorithmic rich applications (eg analytic/simulation systems), network servers (twisted is one of the best event based frameworks (*) I've seen), GUI applications, and writing games. (*) By contrast, Perl's POE is one of the most hideous systems I've ever worked with (despite how well it does actually work), and no C++ event based framework I've looked at has ever looked pleasant to work with. > Could anyone comment on how Python fares against C++, Java and Perl? I'm not going to compare against Java/C++, but with reference to perl, having written programs almost day in day out for 5 years in perl before coming to python I would say that they're comparable languages. For programs that require *lots* of string transformation, perl is a more natural fit IME, but for many, many, many other projetcs, I've found python to not just be a better fit, but a more enjoyable fit. One observation regarding perl/python have over C++/Java is the lack of compile cycle generally results IME with more people writing unit tests, and distributing unit tests with their code. Make of that what you will - IMO it's a _very_ positive plus for both languages. For a highly trustable opinion on C++/Java vs python/etc I would suggest looking for the interviews with people like Bruce Eckel on his thoughts on the matter. One final point I feel though - python strikes me as a having a greater likelyhood at being maintainable. Perl often tends to become more and more obfuscated with time. The edit/compile/test cycle of Java/C++ IME often leads to greater chance of awkward to find/fix errors occuring. In contrast, the heavily used python idiom of ' if __name__ == "__main__": ' tends to lead to a modularity I've not personally seen in many other languages. Bearing in mind that a lot of code is maintained by people who weren't the original developers... Given that 90% programmers aren't in the 10% of best programmer rankings, this strikes me as a good thing. Given that 90% of programmers tend to think they're in the top 10% anyway and will use features they don't really understand properly, using a language which is geared well towards maintainability strikes me as a strong positive. Michael. From sjdevnull at yahoo.com Wed Jun 23 20:29:39 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 23 Jun 2004 17:29:39 -0700 Subject: Keyword arguments and user-defined dictionaries Message-ID: <96c2e938.0406231629.4103ccde@posting.google.com> Hi, I'm implementing a lazy-load dictionary; my implementation basically stores keys that are to be loaded lazily internally (in a member dictionary) and then in __getitem__ I look to see if the key needs to be loaded and if so I load it. My class inherits from dict and has keys(), __contains__, __get/setitem__, items(), etc all properly implemented--seems to work fine in most cases. My question is, what methods do I need to implement to make ** work on a custom dictionary-like object, or is it not possible? Here's how you can see the problem. Simplified LazyDict (the real one actually stores callbacks to generate values, but this is enough to show the problem--my real one implements a lot more dict methods, but still doesn't work): class LazyDict(dict): def __init__(self): dict.__init__(self) self.special_keys={} def addLazy(self, key, val): if dict.has_key(self, key): dict.__delitem__(self, key) self.special_keys[key]=val def has_key(self, key): return self.__contains__(key) def __contains__(self, key): if dict.has_key(self, key): return 1 elif dict.has_key(self.special_keys, key): return 1 else: def __getitem__(self, key): if dict.has_key(self, key): return dict.__getitem__(self, key) elif key in self.special_keys.keys(): self[key]=self.special_keys[key] del self.special_keys[key] return dict.__getitem__(self, key) return 0 e.g. put the above in LSimple.py and: >>> def g(foo): ... print foo ... >>> a=LSimple.LazyDict() >>> a.addLazy("foo", 2) >>> g(**a) Traceback (most recent call last): File "", line 1, in ? TypeError: g() takes exactly 1 argument (0 given) >>> a["foo"] 2 >>> g(**a) 2 >>> Thanks for your time. From __peter__ at web.de Tue Jun 8 06:35:43 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 12:35:43 +0200 Subject: Using ConfigParse References: Message-ID: Zunbeltz Izaola wrote: > def save(self): > print "Enter save" > self.write(open('defaultdifrac.cfg','w')) > self.read(open('defaultdifrac.cfg')) > print "OUt save" I would explicitly close the file before trying to read it. >>> def save(fn="tmp.txt", s="so what", close=True): ... f = file(fn, "w") ... f.write(s) ... if close: f.close() ... return file(fn).read() ... >>> save() 'so what' >>> save(s="another") 'another' >>> save(s="yet another", close=False) '' Peter From mwh at python.net Thu Jun 17 05:13:38 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jun 2004 09:13:38 GMT Subject: does python have useless destructors? References: Message-ID: Donn Cave writes: > In article , > Michael Hudson wrote: > > Manlio Perillo writes: > ... > > > Since __del__ isn't really 'useful', *maybe* a better solution is to > > > add another special method for classes, ad example a __finalize__ > > > method. > > > > Yes! I'm not sure __finalize__ is really the best name, but that's > > for another day. > > Couldn't the name be __del__? As I think I said in one of the emails in the thread linked to from PEP 310, life would be much easier if it wasn't. > Given the opportunity to have both, and the assurance that > __finalize__ will be called and __del__ might not, what > functionality would you leave in __del__? None at all! This is my cunning plan... > > I would urge everyone participating in this thread to read PEP 310, > > the email conversation linked therein and (optional) *understand* it. > > It seems to be superficially similar to finalization, OK, I've found this thread pretty hard to follow. What is "finalization" in context? > but so constrained that it's architecturally inconsequential - I > mean, it's by definition interchangeable with a try/finally > construct, so there isn't any potential code architecture where you > can say `couldn't do this without with'. Indeed. Cheers, mwh -- same software, different verbosity settings (this one goes to eleven) -- the effbot on the martellibot From loic at yermat.net1.nerim.net Thu Jun 17 13:26:00 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Thu, 17 Jun 2004 19:26:00 +0200 Subject: list to dict In-Reply-To: References: Message-ID: Denis S. Otkidach a ?crit : > On Wed, 16 Jun 2004, Yermat wrote: > > Y> > What is the easiest/fastest way to build a dictionary from > Y> a list? The > Y> > list contains 100,000 entries. > Y> > > Y> > Thanks, > Y> > Bart > Y> > Y> >>> dict([(1,'a'),(2,'b')]) > Y> {1: 'a', 2: 'b'} > Y> > Y> list of tuples -> dict ! > > But unfortunately list({1: 'a', 2: 'b'}) -> [1, 2]. > >>> {1: 'a', 2: 'b'}.values() ['a', 'b'] >>> {1: 'a', 2: 'b'}.items() [(1, 'a'), (2, 'b')] >>> {1: 'a', 2: 'b'}.keys() [1, 2] The documentation worst to be read... -- Yermat From claird at lairds.com Thu Jun 3 12:35:38 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 16:35:38 -0000 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <7x4qpsvdfg.fsf@ruckus.brouhaha.com> Message-ID: <10bukqqqt7u6pb1@corp.supernews.com> In article <7x4qpsvdfg.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >You might also look at . . . . Also . And, for that matter, ... hmm; some other pages that are 404ing me now. Maybe we'll return to this subject. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Wed Jun 2 07:42:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jun 2004 07:42:13 -0400 Subject: Converting Hex to decimal In-Reply-To: <70efe2ee.0406020009.1e1000d6@posting.google.com> References: <70efe2ee.0406020009.1e1000d6@posting.google.com> Message-ID: dean wrote: > Thanks for your responses so far. I have not been clear it seems so > here it goes: Judging by the subsequent responses, you're still not being clear. :-) > The file is binary. In other words, it is *not* "hex". It's binary. Plain and simple. Is that true? > Using the standard hpux or linux hexdump (xxd or > xd) this is the output that is obtained: So the only hex thing about it is that you can display the contents using a program that displays binary content as hex? > 0000000: 5c1a 0100 0100 ff35 0399 7272 9903 0002 \......5..rr.... > 0000010: 010e 0300 050a 0214 ffff ffff 5cd4 2e01 ............\... But the actual file that you have is the original, binary file, right? Not just this hexdump output? > Each hex character is 8 bits. Do you mean that each byte is 8 bits? > I would like to convert one byte at the > time and pipe the converted data into a new file. Convert in what way? Or do you really mean that you have only the hexdump output and want to convert it back to the raw binary file from which it was originally generated, as the last several respondents have assumed? Otherwise, it really sounds like you just want to read the file byte-by-byte and "convert" the bytes in some way, writing them to a new file. There is nothing special about doing this: you would just use open() and .read() and .write() like with any other file. -Peter From cookedm+news at physics.mcmaster.ca Mon Jun 14 16:01:52 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 14 Jun 2004 16:01:52 -0400 Subject: How to get decimal form of largest known prime? References: Message-ID: At some point, "Tim Peters" wrote: > There are some GMP wrappers for Python. Using Marc-Andre Lemburg's mxNumber > wrapper (which is maximally convenient for me on Windows, since it includes > a precompiled-for-Windows GMP), the OP's task is spelled like so: > >>>> from mx.Number import * >>>> Integer(2)**24036583 - 1 > > That does call mpz_pow_ui() and mpz_get_str() (with base=10) under the > covers. > > Since I typed that in, the process has accumulated 59 CPU minutes, with no > output yet. > > Curiously, > >>>> x = Integer(2)**24036583 - 1 > > consumes 112 CPU seconds on its own, while the straight Python > >>>> x = 2**24036583 - 1 > > consumes only 2 CPU seconds -- so Python is 50+ times faster than this GMP > for the computational part. Interesting, because with gmpy (on a 32-bit AMD64 machine running Linux): >>> import gmpy >>> x = gmpy.mpz(2)**24036583-1 is almost instantaneous, whereas the straight Python takes a second. But then with gmpy I get >>> print x Segmentation fault so I can't win here :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From nc-jantzegu at netcologne.de Thu Jun 17 19:53:38 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Fri, 18 Jun 2004 01:53:38 +0200 Subject: Easiest way to port Python program to PDA References: Message-ID: "Jeffrey Barish" schrieb im Newsbeitrag news:mailman.31.1087512459.18066.python-list at python.org... > I have been developing a Python program with two intercommunicating > (using sockets) parts, one of which runs on a desktop and the other on > a PDA. For ease of development, I developed them both on a desktop. > Now that I have them working on the desktop, I need to move the part > destined for a PDA to a PDA. I had originally planned to use a Sharp > Zaurus because it runs Linux (the OS of my desktop system) and I had > found a Python port that was supposed to be available for that platform > (Riverbank Computing). Unfortunately, Riverbank Computing just > discontinued their port. They refer interested parties to another port > (http://www.vanille.de/projects/python.spy), but that site has no code > to download and does not respond to queries. Accordingly, I have to > conclude that there is no Python port available for the Zaurus so I am > back to square 1. > Maybe openzaurus could be what you are searching http://www.openzaurus.org/official/stable/feed/ From secun at yahoo.com Tue Jun 15 10:45:41 2004 From: secun at yahoo.com (ChrisH) Date: Tue, 15 Jun 2004 14:45:41 GMT Subject: Eclipse and Python Message-ID: Is anyone using Eclipse with python? I did a google search and discovered this was brought up about a year ago, but I'm wondering if there have been any significant improvements with the python plugins and if anyone is using them. From lykoszine at gmail.com Mon Jun 28 09:41:09 2004 From: lykoszine at gmail.com (Samuel Wright) Date: Mon, 28 Jun 2004 14:41:09 +0100 Subject: msg.walk() In-Reply-To: <20040627094222.6f17f33e.pythonhda@yahoo.com.replacepythonwithlinux> References: <20040627094222.6f17f33e.pythonhda@yahoo.com.replacepythonwithlinux> Message-ID: "Notice the return ''" > > def main(): > fp = open(mailboxfile, 'r') > mbox = mailbox.UnixMailbox(fp, msgfactory) > for msg in mbox: > print msg > for part in msg.walk(): > print part > [...] "You have to do a test for an empty string in your main method (like the docs say)." Gotcha. I had assumed that was for mailboxes that might not be well formatted, and I was checking a mailbox I had exported myself... Thanks loads. From db3l at fitlinxx.com Fri Jun 11 10:32:52 2004 From: db3l at fitlinxx.com (David Bolen) Date: 11 Jun 2004 10:32:52 -0400 Subject: executing python script from wxpython GUI (button click).. References: Message-ID: sarmin kho writes: > i ve tryed the command 'execfile(name of the python script)'.. this > command will stall the GUI until the python script exited. If the script won't be cooperating with the GUI (e.g., isn't built to be run in an Idle event routine or to do its work in chunks), then your best bet is to execfile the script in a separate thread. You can create a worker thread class that your GUI instantiates (or you can keep one or more around that reads from a queue for work to do), and let that thread handle the execution. If you need to communicate back to the GUI thread (say for stdout from the script or for other reasons), you'll need to generate events through wxPython back to the main thread, since only the main thread can perform most GUI manipulations (wxPostEvent being an exception). The information at http://wiki.wxpython.org/index.cgi/LongRunningTasks while not entirely applicable might help (e.g., if you use the threading approach and replace the long computation with the execfile). Beyond that it's probably better to post to the wxPython mailing list where you may have a better target audience. Oh, and note that doing it this way does imply that if the script you are executing is one that would interfere with Python threading itself (e.g., perhaps it calls out to an extension module that doesn't release the GIL around a blocking or CPU-bound operation), then this mechanism won't help, since even having the script in its own thread will still block Python in general. In such a case you're only recourse would be to execute the script in a second process and handle some form of communication between the main GUI process and the script executing process. And lastly, I should note (although hopefully you're already aware of it) that using execfile as a scripting mechanism can be a significant exposure to your script if you expect to be using "foreign" scripts. Even if you lock down the globals/locals in the environment that the script you are execing runs in, it can import arbitrary modules and perform arbitrary actions within the context of your main script. As long as that's reasonable for the target environment, that's fine, but it's something to be aware of. -- David From winexpert at hotmail.com Wed Jun 16 13:50:52 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 16 Jun 2004 17:50:52 +0000 Subject: python -- figured out how to parse command line args Message-ID: I figured out how to do it in its simplest form... import sys for arg in sys.argv: print "arg: ", arg I think I saw that in the tutorial, i'd forgotten how though. David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From ellisjb at my-deja.com Tue Jun 15 09:09:48 2004 From: ellisjb at my-deja.com (ellisjb at my-deja.com) Date: 15 Jun 2004 06:09:48 -0700 Subject: python with Java API In-Reply-To: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Message-ID: I would drop the wxPython idea and go with Swing, either with straight Java or Jython. Doesn't sound like you have a compelling reason to add the extra complication of another set of dependencies; Swing is a quite capable toolkit (and far better documented than wxPython). -Jonathan Brendan J Simon wrote: > Hi, > > I have a Java application from a company. They also provide an API in > C++ (MSW platforms only) and Java (for all platforms) for developers > that want to create their own front end. I want to use wxPython to > create a decent Unix opensource frontend. > > Is it possible to Interface python to a java application easily ??? > > Assuming yes to above, would something like Jython or SWIG or some other > tool be required. > > Any advice or pointers would be greatly appreciated. > > Regards, > Brendan Simon. From fumanchu at amor.org Fri Jun 18 02:04:12 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 17 Jun 2004 23:04:12 -0700 Subject: Using metaclasses to play with decorators. Message-ID: I wrote: > Basically, a > decorator is a way to transform a function. Again, this can usually be > done without metaclasses. That should have said, "without _decorators_." From guy at obstruction.com Wed Jun 9 20:49:35 2004 From: guy at obstruction.com (Guy Middleton) Date: Thu, 10 Jun 2004 00:49:35 GMT Subject: Python "aha" moment Message-ID: I wanted to decode some MIME base64 text, and had no program that does this, so I thought it must be easy to do in Python. I have been using Python, on and off, for a long time, so I used a file idiom I remembered from years ago: for line in sys.stdin: sys.stdout.write(base64.decodestring(line)) This works fine, but then I realised that the language has evolved since then, and I could make this more obviously a transformation: base64.decode(sys.stdin, sys.stdout) I like this version much better. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jun 29 11:38:36 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 29 Jun 2004 17:38:36 +0200 Subject: Listing functions in a file IN ORDER In-Reply-To: References: Message-ID: <40e18d01$0$36861$e4fe514c@news.xs4all.nl> Ian Sparks wrote: > I have a python file with a number of functions named with the form doX so : > > doTask1 > doThing > doOther > > The order these are executed in is important and I want them to be executed top-down. They all have the same parameter signature so I'd like to do : > > for name, func in vars(mymodule).items(): > if not name.startswith("do") and callable(func): > apply(func,my_params) > > but the problem is that the return from vars is not ordered the same as in the file. i.e. it could be Just add a list which sums up the function names in the order you want: functions = ["doTask1", "doThing", "doOther"......] and iterate over that list? --Irmen From cliechti at gmx.net Sun Jun 6 17:06:57 2004 From: cliechti at gmx.net (Chris Liechti) Date: Sun, 6 Jun 2004 21:06:57 +0000 (UTC) Subject: left-quote ( ` ) on International keyboards [Prothon] References: Message-ID: "Mark Hahn" wrote in news:buLwc.60925$zN5.390 at fed1read01: > Can users with international keyboards tell me if they have problems > typing the left-quote ( ` ) character? It isn't used much in Python > but we are thinking of giving it a slightly more important role in > Prothon. (I'm not going to say what that role is here to avoid > starting another 300 message thread like I did last time :-) If you > are curious you can go to the Prothon mailing lists at > http://prothon.org). i can type it as combined character, but i'd recomend against it. ' and ` are hard to distinguish for people with not so good sight. and the meaning/effect isnt obvious anyway. -- Chris From opengeometry at yahoo.ca Sun Jun 6 14:41:09 2004 From: opengeometry at yahoo.ca (William Park) Date: 6 Jun 2004 18:41:09 GMT Subject: Simple Python script to read and output MailBox body to a file References: <2ibv0aFk6ju7U1@uni-berlin.de> <40C32F31.3050304@harvee.org> Message-ID: <2ih6q5Fn67f3U1@uni-berlin.de> chuck amadi wrote: > Eric S. Johansson wrote: > > > William Park wrote: > > > >> Chuck Amadi wrote: > >> > >>> Has anyone got a simple python script that will parse a linux > >>> mbox and create a large file to view . > >> > >> "Create a large file to view"? Care to elaborate? > > Note briefly my main goal is to get the body content to another file > for processing to Postgresql database. One email body per file, or all email bodies in one file? -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From emcpeters at anacapasciences.com Sat Jun 19 03:26:07 2004 From: emcpeters at anacapasciences.com (Evan McPeters) Date: Sat, 19 Jun 2004 00:26:07 -0700 Subject: Spellcheck on outside application - newbie Message-ID: <40d3eaa6@newsfeed.netlojix.com> Hi, I am very new to Python so please forgive my ignorance. I need to develop a program that will spell check a word processing window that is open in another application. I do not have access to the the API or any other code for this application, so I was hoping that the spell checker could simply do it's job on whatever the user's active window is. Does this make sense. Does anyone have an idea about how to start this. Thanks in advance. From danb_83 at yahoo.com Fri Jun 18 01:53:56 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 17 Jun 2004 22:53:56 -0700 Subject: str() for containers References: <40d07ac6@rutgers.edu> Message-ID: Donn Cave wrote in message news:... > In article <40d07ac6 at rutgers.edu>, > "George Sakkis" wrote: > > > I find the string representation behaviour of builtin containers > > (tuples,lists,dicts) unintuitive in that they don't call recursively str() > > on their contents (e.g. as in Java) > > Please find last week's answers to this question at > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=62e7a6469ac7b40b > > If you're still interested in further discussion of this > point, you could present an account of Java's approach > for the edification of those of us who don't know. All Java classes include a toString() method (defined in the root class java.lang.Object), which returns the string representation of that object. Each of the standard collection classes in java.util defines its toString() method to recursively call toString() on its elements. For example, the program import java.util.*; public class Foo { public static void main(String[] args) { List lst = new ArrayList(); lst.add("a"); lst.add("b"); lst.add("c"); System.out.println(lst); } } prints "[a, b, c]". (Btw, this reminds me of something I like about Python: There are literals for variable length arrays, so you don't have to write code like that.) The difference from Python's approach is that there isn't an equivalent to Python's str/repr distinction. Obviously, when there's only one string conversion method, you won't use the wrong one. The other difference is that the built-in array types don't have a meaningful toString() method, so public class Foo { public static void main(String[] args) { String[] arr = {"a", "b", "c"}; System.out.println(arr); } } prints "[Ljava.lang.String;@df6ccd" (or something similar). From squirrel at WPI.EDU Tue Jun 29 12:36:06 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 29 Jun 2004 12:36:06 -0400 Subject: embedded python? In-Reply-To: References: Message-ID: > 1) Are there any embedded Pythons out there? The nodes will likely be > running some form of Linux, but I don't particularly feel like devoting > resrouces to porting python. Any embedded Linuxes supporting Python? > Thoughts in general? Python runs fine on ARM-based PDAs running Linux -- see http://www.vanille.de/projects/python.spy for info and a surprising amount of ARM binaries. Note that the packages are in ipkg (.ipk) format. These are similar to Debian's .deb files, and you can get at the contents using tar a couple of times. From jcarlson at uci.edu Fri Jun 4 03:25:07 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 04 Jun 2004 00:25:07 -0700 Subject: partial / wildcard string match in 'in' and 'list.index()' In-Reply-To: <2ho8clFeu0egU1@uni-berlin.de> References: <2ho8clFeu0egU1@uni-berlin.de> Message-ID: > These would work, but I was wondering if there was some compact > way to get 'in' and lists.index() to do wildcard matching as opposed > to exact matching. Short answer: no. Long answer: There is a regular expression library, aptly called 're', for non-exact string searching. The standard string methods only do exact searching likely because there are algorithms that make it fast (linear in the length of the searched string), that are also quite small. There exist very simple looking regular expressions that force searches to take exponential (in the length of the pattern) time to search, and are generally fairly large. An example of an exponentially slow regular expression is contained in the following example... >>> import re >>> import time >>> def test(n): ... a = 100*'0' ... t = time.time() ... re.search('(0+)'*n, a) ... return time.time()-t ... >>> for i in xrange(18, 23): ... print i, test(i) ... 18 0.141000032425 19 0.266000032425 20 0.530999898911 21 1.07899999619 22 2.1400001049 >>> Trust me, you don't want that kind of slow down when you are searching in strings with "if i in 'somestring':". - Josiah From jg at jonasgalvez.com Mon Jun 7 11:44:27 2004 From: jg at jonasgalvez.com (Jonas Galvez) Date: Mon, 7 Jun 2004 12:44:27 -0300 Subject: Decoding 'funky' e-mail subjects Message-ID: Hi, I need a function to parse badly encoded 'Subject' headers from e-mails, such as the following: =?ISO-8859-1?Q?Murilo_Corr=EAa?= =?ISO-8859-1?Q?Marcos_Mendon=E7a?= I tried using the decode() method from mimetools but that doesn't appear to be correct solution. I ended up coding the following: import re subject = "=?ISO-8859-1?Q?Murilo_Corr=EAa?=" subject = re.search("(?:=\?[^\?]*\?\Q\?)?(.*)\?=", subject) subject = subject.group(1) def decodeEntity(str): str = str.group(1) try: return eval('"\\x%s"' % str) except: return "?" subject = re.sub("=([^=].)", decodeEntity, subject) print subject.replace("_", " ").decode("iso-8859-1") Can anyone recommend a safer method? Tia, \\ jonas galvez // jonasgalvez.com From indigo at bitglue.com Thu Jun 3 09:32:02 2004 From: indigo at bitglue.com (Phil Frost) Date: Thu, 3 Jun 2004 09:32:02 -0400 Subject: printing something without a newline OR a space after it? In-Reply-To: <10bu9hm1e03cved@corp.supernews.com> References: <10bu9hm1e03cved@corp.supernews.com> Message-ID: <20040603133202.GA10918@unununium.org> import sys sys.stdout.write( 'stuff here' ) sys.stdout.write( 'more' ) On Thu, Jun 03, 2004 at 02:23:01PM +0100, Alex Hunsley wrote: > Very very simple problem here, can't find out how to do it... > > I want to print something without a new line after it, so I can later > output something right after it on the same line. > > If I do: > > print "stuff here", > print "more" > > .. it doesn't output a newline, but it does output a space: > > stuff here, more > > .. whereas I want no newline and no space: > > > stuff here,more > > How is this done? > > thanks > alex From cbrown at metservice.com Sat Jun 5 02:09:41 2004 From: cbrown at metservice.com (Colin Brown) Date: Sat, 5 Jun 2004 18:09:41 +1200 Subject: Brain Dead Singleton References: <889cbba0.0406041333.10402447@posting.google.com> Message-ID: <40c162a6$1@news.iconz.co.nz> "Kamilche" wrote in message news:889cbba0.0406041333.10402447 at posting.google.com... > I looked on this newsgroup, and saw all the problems with making a > Singleton class with Python. Whenever I want a singleton "class", I just use a module with functions and global variables. Modules only import once. Colin Brown PyNZ From klachemin at home.com Wed Jun 23 22:21:38 2004 From: klachemin at home.com (Kamilche) Date: 23 Jun 2004 19:21:38 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> <889cbba0.0406231156.115b743a@posting.google.com> Message-ID: <889cbba0.0406231821.42d53dd4@posting.google.com> Peter Hansen wrote in message news:... > Very interesting use of translate. I doubt anyone, certainly > not I, guessed that's what you were using. Kudos! I'm glad you enjoyed it! {unwraps and eats her first Python kudos bar.} From martin at v.loewis.de Fri Jun 11 01:04:55 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 Jun 2004 07:04:55 +0200 Subject: The __unicode__ method in the C API, and other __-methods In-Reply-To: References: Message-ID: <40C93D77.8050800@v.loewis.de> Marcin 'Qrczak' Kowalczyk wrote: > and on the other hand the implementation > of tp_getattro of Kogut objects wrapped in Python has a special case, > only one special case, which checks for "__unicode__" and returns the > appropriate convert-to-Unicode bound method instead of forwarding the > attribute access to the original object. Why didn't you use Py_FindMethod for that? Regards, Martin From alex-news-deleteme at comcast.net Tue Jun 29 13:40:08 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 29 Jun 2004 17:40:08 GMT Subject: embedded python? References: Message-ID: > You mention network, so presumably you have Ethernet (?) interfaces, and > plan on TCP or UDP... This is the very start of the project, so very little is locked down. Most likely we will have Ethernet interfaces and a standard protocol stack, but we are exploring some mesh networking options such as zigbee. > I doubt you'll need to do much "porting". Unless the Linices you > are considering are quite unusual, they ought to look a lot like any > other Linux, and Python may well work largely unchanged. One of my concerns is the lack of confidence I'd have in the build. Any hard to diagnose error that arose could potentially be a logic error or an interpreter bug (or a hardware bug). On a six thousand node distributed system, I want to be quite sure of the foundation, and minimize possible sources of error. I've never compiled python before. Is the test suite comprehensive enough to justify a high level of confidence in a new build? An unexplored suggestion was to use Jython and target an embedded chip designed to accelerate Java bytecode. I know little about Jython or Java chips, so I can't yet make any sense of this idea. > ... rather than immediately abandoning any thought > of using Python. No chance of that! I agree that the productivity benefit is a very strong incentive. We are price constrained per unit, so the hardware can't get too expensive. Your experience is encouraging.in that regards. Thanks for the info, Alex "Peter Hansen" wrote in message news:Rv-dnT7TAcm5BHzd4p2dnA at powergate.ca... > Alexander May wrote: > > > We are developing a distributed application running on approximately six > > thousand nodes with somewhat limited hardware resources. Our hardware > > target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected > > specific hardware yet; the hardware target is what we are trying to fit into > > based on price constraints. Each device needs to be able to handle about 2 > > kbs (yes kilo, not mega) worth of network traffic. > > You mention network, so presumably you have Ethernet (?) interfaces, and > plan on TCP or UDP, in which case you probably first need to consider > operating systems... Python does not automatically give you support for > networking, it just uses the underlying OS support. > > > I intend to a least prototype the system in Python. It would be great if we > > could we could use Python in production by embedding it in the hardware. My > > question is does anyone have any real world experience using python in an > > embedded system? > > Yes, there are a few people around here who have worked on embedded > Python systems, including me (at a past employer). > > > 1) Are there any embedded Pythons out there? The nodes will likely be > > running some form of Linux, but I don't particularly feel like devoting > > resrouces to porting python. Any embedded Linuxes supporting Python? > > Thoughts in general? > > I doubt you'll need to do much "porting". Unless the Linices you > are considering are quite unusual, they ought to look a lot like any > other Linux, and Python may well work largely unchanged. Any required > changes could be in areas you don't need, anyway. Again, make sure > you consider right away exactly what OS resources, other than > networking, that you actually need. Multitasking? Signals? Audio? > GUI? etc... > > > 2) What are the resource requirements of Python? How much overhead do the > > network related modules add? > > _socket.pyd is 49212 on Win32, and 124040 (probably with debugging > symbol table included?) on Linux, for Python 2.3.4. This includes > lots of doc-strings, though, so you can probably shrink it pretty > easily with a configurable setting during compilation. > > > In short, is embedding python realistic? > > Definitely. We did it first on a 33MHz 386 (or 286?) compatible > board with only 1MB of flash and 1MB of RAM, and a tiny embedded > OS with no networking. That took a little slashing, such as removing > floating point support, but for the most part such things were > supported well by #defines during compilation. I think we based > that one on Python 1.5.2. (It was a few years ago.) Performance, > however, turned out to be inadequate and we decided we'd get > farther faster by keeping Python and switching to faster hardware > (than by ditching Python and doing it all in C). > > The next version was a 100MHz 486 compatible with 32MB RAM and > Compact Flash as a hard drive. We picked 32MB flash as the target, > but used 64MB for prototyping and kept using it thereafter because > CF cards kept getting cheaper. This version ran vanilla Linux > with everything non-essential removed, and stock Python recompiled > from sources with, I believe, no changes. We stripped a few library > files from the resulting binary (e.g. unicodedata.so) to reduce the > footprint. > > I know others have done similar things on hardware in this range, > but I don't know of anything freely available yet. Not sure that > would make sense, either, as everybody uses different hardware in > this sort of thing... > > The main advice I can give you from this experience is that if > your hardware doesn't quite cut it, considering putting the money > into better hardware rather than immediately abandoning any thought > of using Python. On the other hand, you have 6K nodes, and we > had less than a few hundred, so the "economies of scale" just > weren't there as much in our case and development costs were > the largest consideration. In your case, saving $100 on each > unit might be more important than saving a few thousand hours > of development time... your call. > > -Peter From helmut.zeisel at aon.at Thu Jun 17 07:50:31 2004 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: Thu, 17 Jun 2004 13:50:31 +0200 Subject: Q: Static extension of Python using SWIG Message-ID: I want to build a static extension of Python using SWIG and VC++ 6.0 as described in http://www.swig.org/Doc1.3/Python.html#n8 for gcc. My file is testerl.i: ========================= %module testerl extern int hz(int i); %include embed.i ========================== I essentially use the same settings as described in http://www.swig.org/Doc1.3/Python.html#n12 for dynamic extensions, in particular I link python23.lib. (SWIG is 1.3.21, Python is 2.3.4). Additionally I define the preprocessor macro STATIC_LINKED and the preprocessor inclide path Python-2.3.4\PC (for config.c). I tried to call swig with and without option c++. Creating DLL works, but when linking for a statically linked version I get the warnings and error messages added below - any idea what is missing? Did anyone succeed in building a statically extend python using VC? Which version? Helmut Linker error messages: ====================== testerl_wrap.cxx D:\DATA\zeisel\vc\python\static\testerl\testerl_wrap.cxx(793) : warning C4273: 'Py_Main' : inconsistent dll linkage. dllexport assumed. D:\DATA\zeisel\vc\python\static\testerl\testerl_wrap.cxx(799) : warning C4273: 'PyImport_Inittab' : inconsistent dll linkage. dllexport assumed. Linking... testerl_wrap.obj : error LNK2001: unresolved external symbol _initimp testerl_wrap.obj : error LNK2001: unresolved external symbol _PyMarshal_Init testerl_wrap.obj : error LNK2001: unresolved external symbol _initzipimport testerl_wrap.obj : error LNK2001: unresolved external symbol _initxxsubtype testerl_wrap.obj : error LNK2001: unresolved external symbol _inititertools testerl_wrap.obj : error LNK2001: unresolved external symbol _init_random testerl_wrap.obj : error LNK2001: unresolved external symbol _init_hotshot testerl_wrap.obj : error LNK2001: unresolved external symbol _init_weakref testerl_wrap.obj : error LNK2001: unresolved external symbol _initxreadlines testerl_wrap.obj : error LNK2001: unresolved external symbol _init_codecs testerl_wrap.obj : error LNK2001: unresolved external symbol _init_locale testerl_wrap.obj : error LNK2001: unresolved external symbol _initpcre testerl_wrap.obj : error LNK2001: unresolved external symbol _initcPickle testerl_wrap.obj : error LNK2001: unresolved external symbol _initcStringIO testerl_wrap.obj : error LNK2001: unresolved external symbol _initthread testerl_wrap.obj : error LNK2001: unresolved external symbol _inittime testerl_wrap.obj : error LNK2001: unresolved external symbol _initstruct testerl_wrap.obj : error LNK2001: unresolved external symbol _initstrop testerl_wrap.obj : error LNK2001: unresolved external symbol _initsha testerl_wrap.obj : error LNK2001: unresolved external symbol _initsignal testerl_wrap.obj : error LNK2001: unresolved external symbol _initrotor testerl_wrap.obj : error LNK2001: unresolved external symbol _initrgbimg testerl_wrap.obj : error LNK2001: unresolved external symbol _initregex testerl_wrap.obj : error LNK2001: unresolved external symbol _initoperator testerl_wrap.obj : error LNK2001: unresolved external symbol _initnt testerl_wrap.obj : error LNK2001: unresolved external symbol _initmd5 testerl_wrap.obj : error LNK2001: unresolved external symbol _initmath testerl_wrap.obj : error LNK2001: unresolved external symbol _initimageop testerl_wrap.obj : error LNK2001: unresolved external symbol _initgc testerl_wrap.obj : error LNK2001: unresolved external symbol _initerrno testerl_wrap.obj : error LNK2001: unresolved external symbol _initcmath testerl_wrap.obj : error LNK2001: unresolved external symbol _initbinascii testerl_wrap.obj : error LNK2001: unresolved external symbol _initaudioop testerl_wrap.obj : error LNK2001: unresolved external symbol _initarray testerl_wrap.obj : error LNK2001: unresolved external symbol _PyImport_Inittab Release/testerl.exe : fatal error LNK1120: 35 unresolved externals Error executing link.exe. testerl.exe - 36 error(s), 2 warning(s) From lbates at swamisoft.com Mon Jun 14 15:55:46 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 14 Jun 2004 14:55:46 -0500 Subject: setattr using invalid attribute names - bug or feature? References: <40cdb3d5.2146906@news.t-online.de> <9c2d8268.0406141002.5c1d1e6@posting.google.com> Message-ID: You can also do this: class test: pass instance = test() setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) >>> print instance.__dict__["THIS :*2+~# IS OBVIOUSLY INVALID"] >>> 123 >>> print instance.__dict__.keys() >>> ['THIS :*2+~# IS OBVIOUSLY INVALID'] >>> print instance.__dict__.items() >>> [('THIS :*2+~# IS OBVIOUSLY INVALID', 123)] The only reason that you cannot do: instance.This :*2+~# IS OBVIOUSLY INVALID is because attribute names accessed in this fashion can't have spaces. Larry Bates, Syscon, Inc. "Meno" wrote in message news:9c2d8268.0406141002.5c1d1e6 at posting.google.com... > gerson.kurz at t-online.de (Gerson Kurz) wrote in message news:<40cdb3d5.2146906 at news.t-online.de>... > > I stumbled across this (while using my homebrewn enum class): > > > > class test: > > pass > > > > instance = test() > > setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) > > > > I would've expected some kind of error message here when calling > > setattr(); after all, its not a regular attribute? Plus, documentation > > says > > > > " > > Set a named attribute on an object; setattr(x, 'y', v) is equivalent > > to > > ``x.y = v''. > > " > > > > and you cannot write this: > > > > instance.THIS :*2+~# IS OBVIOUSLY INVALID = 123 > > No, but you can write this: > > >>> a = getattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID") > >>> print a > 123 > > Meno. From agriff at tin.it Tue Jun 1 02:10:07 2004 From: agriff at tin.it (Andrea Griffini) Date: Tue, 01 Jun 2004 06:10:07 GMT Subject: API : constness ? References: Message-ID: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> On Mon, 31 May 2004 03:26:53 +0200, Beno?t Dejean wrote: >using const helps gcc to move these data to the text segment This may sound terrible, but indeed the data that a "pointer to constant" is pointing to is not (in general) constant. Being a "pointer to constant" is a property of the *pointer*, not of the *pointed data*. Const pointers in interfaces are designed to be an help for the (distracted) programmers, they can't be an help for the compiler. That const-ness really helps or not is another issue... Andrea From mjtobler at removethis_mail.ru Tue Jun 29 21:36:10 2004 From: mjtobler at removethis_mail.ru (mjt) Date: Wed, 30 Jun 2004 01:36:10 GMT Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: Ville Vainio wrote: > Pythonic Nirvana - towards a true Object Oriented Environment ... with every new language/scripting language, we are supposed to discover nirvana as my 13 YO daughter would say: "what--*EVER*..." . -- << http://michaeljtobler.homelinux.com/ >> I don't need to compromise my principles, because they don't have the slightest bearing on what happens to me anyway. -- Calvin From m9x4nz0067d0b5 at messenger.hotmail.com Tue Jun 22 02:55:08 2004 From: m9x4nz0067d0b5 at messenger.hotmail.com (m9x4nz0067d0b5 at messenger.hotmail.com) Date: Tue, 22 Jun 2004 08:55:08 +0200 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: something is going wrong! -------------- next part -------------- A non-text attachment was scrubbed... Name: nothing.zip Type: application/x-zip-compressed Size: 25473 bytes Desc: not available URL: From rnd at onego.ru Sat Jun 5 10:26:29 2004 From: rnd at onego.ru (Roman Suzi) Date: Sat, 5 Jun 2004 18:26:29 +0400 (MSD) Subject: 2.2 <-> 2.3 surprise In-Reply-To: References: Message-ID: On Fri, 4 Jun 2004, Michael Hudson wrote: >Roman Suzi writes: > >> On Mon, 31 May 2004, Shalabh Chaturvedi wrote: >> >> >Roman Suzi wrote: >> > >> >> Hi! >> >> >> >> I really like python 2.3 but sometimes I write for 2.2 too. >> >> >> >> New cool feature of doing: >> >> >> >> f = open('file') >> >> for line in f: >> >> do_something(line) >> >> >> >> works strange in 2.2: I can't just quit first loop and do: >> >> >> >> for line in f: >> >> do_some_more(line) >> >> >> >> (I as skipping message header by first loop and processing body >> >> the the second). >> >> >> >> In 2.3 it works as intended! Of course, simple refacture made it one loop... >> >> >> >> >> >> >> >> Sincerely yours, Roman Suzi >> > >> >This is probably the following change as described in >> >http://www.python.org/2.3/highlights.html >> > >> >"File objects are now their own iterators. This makes multiple >> >interrupted iterations over the same file more reliable." >> >> Hmmm... Such gradual changes IMHO are worse than just adding something >> at once. The problem is I was getting no warnings that something is wrong. >> In some big project this could break a lot. > >Are you arguing that the 2.2 behaviour should have been retained? If >so, you're wrong :-) . No. But I think it was too early for 2.2 to have the feature. It's like having positive number addition in a version 0.1 and fully capable addition in 0.2. >Cheers, >mwh > > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From insert at spam.here Sun Jun 20 22:25:10 2004 From: insert at spam.here (Doug Holton) Date: Sun, 20 Jun 2004 21:25:10 -0500 Subject: Graph API / framework In-Reply-To: <40d4729e$1@rutgers.edu> References: <40d4729e$1@rutgers.edu> Message-ID: George Sakkis wrote: > Does anyone know of a good graph API ? The only one I found for Python is > part of kjbuckets > (http://starship.python.net/crew/aaron_watters/kjbuckets/kjbuckets.html), > but I was looking for something more sophisticated; I am more concerned > about elegance and extensibility than top performance. JUNG > (http://jung.sourceforge.net/doc/manual.html) for java looks more promising. > Does anyone have experience with it or some other relevant framework ? > Thanks, You'd probably just want to implement it yourself. There are some basic python graph examples out there, like this one: http://www.ece.arizona.edu/~denny/python_nest/graph_lib_1.0.1.html http://www.ece.arizona.edu/~denny/python_nest/graph_lib.py For drawing graphs, people tend to use Graphviz from python, but you could draw it yourself using a GUI toolkit like wxPython. Or else use Jython to access some of the Java libraries like Jung or JGraph. If you find any better options, please share them here, thanks From cedmunds at spamless.rochester.rr.com Mon Jun 14 18:47:08 2004 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Mon, 14 Jun 2004 22:47:08 GMT Subject: How do you feel ? References: Message-ID: "Sylvain Hellegouarch" wrote in message news:mailman.940.1087222870.6949.python-list at python.org... > Hi, > > A bit off topic. > > I just wondered what was your feeling when you were coding with Python. > I have beebn coding with different languages and the only that has given > me the will to invent or to be creative has been Python. Python allows > me not to focus on the complexity of the language itself. > > Of course, from time to time, I find something that is not clear to me > but indeed after a couple of research you find the information you were > looking for. > > I love that language and above all, I love using it. > > Sorry for this little spam but it is always good to acknowledge good > things and not only complaining when it doesn't work. > > Thanks the Python team. > - Sylvain > > I feel vaguely guilty, as if I were cheating somehow. Isn't programming supposed to hurt more than this? -- Cy http://home.rochester.rr.com/cyhome/ From dkuhlman at rexx.com Sat Jun 26 13:55:04 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 26 Jun 2004 10:55:04 -0700 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <2k5rjeF176k24U1@uni-berlin.de> Sticks wrote: > i'm new to python and i was wondering what editors people prefer > to use and why. I like Jed a lot: - light-weight and quick - good but simple Python mode - syntax high-lighting. And, it's customizable, which is especially valuable for those of us who are "color challenged". - very strong scripting language (SLang). Very customizable. - multiple buffers and ability to reload session (files previously open) on a per-directory basis - and, of course, much more. The down-side -- since it's so customizable, you will be tempted to spend lots of time customizing and extending Jed capabilities. It's at: http://space.mit.edu/~davis/jedsoft/jed/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From max at alcyone.com Sat Jun 12 05:37:01 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jun 2004 02:37:01 -0700 Subject: Oddity with function default arguments References: Message-ID: <40CACEBD.ABA147D0@alcyone.com> Sheila King wrote: > SyntaxError: invalid syntax > > Why isn't the default value for a printing out when I include list > arguments? The remaining arguments (*) or remaining keyword arguments (**) go at the end of the argument list. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Did you ever love somebody / Did you ever really care -- Cassandra Wilson From tjreedy at udel.edu Sat Jun 12 00:33:39 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jun 2004 00:33:39 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: "David Bolen" wrote in message news:u4qpi7yw0.fsf at fitlinxx.com... > Resource Acquisition is Initialization. ,,, > It comes from a common method in C++ of using stack-allocated objects > to own or manage resources, because of the explicit construction and > destruction semantics of C++ objects (and their members) during ... > I'm not sure if RAII is intended to also cover non-stack based > objects, in terms handing ownership of the object reference equating Thanks. This makes it much clearer what behavior some people miss, and why the behavior is hard to simulate in CPython (all PyObjects are heap allocated). Terry J. Reedy From bubu_python at ibest.com.br Thu Jun 3 00:54:37 2004 From: bubu_python at ibest.com.br (bubu_python at ibest.com.br) Date: Thu, 03 Jun 2004 01:54:37 -0300 Subject: Error in small code Message-ID: <200406030454.i534sbQ10955@mailweb05.ibest.com.br> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From b.scharpf at tesionmail.de Fri Jun 25 09:27:37 2004 From: b.scharpf at tesionmail.de (Bertram Scharpf) Date: 25 Jun 2004 13:27:37 GMT Subject: Redirecting I/O in embedded Python References: Message-ID: Hi Heather, Heather Coppersmith schrieb: > On 25 Jun 2004 12:11:48 GMT, > Bertram Scharpf wrote: > >> Hi, >> in one of my C programs, I call embedded Python code. Now, I >> would like to redirect stdin/stdout to strings I can assign >> to/read out within the C code. > >> This should be a solvable problem creating modules that have >> a member function 'write' or 'readline' respectively and >> assigning them to sys.stdin and sys.stdout. > >> Before I do this work, I would like to ask if there is a >> reported standard way to do it or if there is even the >> finished code to be obtained anywhere on the web. > > Put the library reference under your pillow tonight, and read the > sections on stringio and cstringio in the morning. Yes, I did already think of that solution. But compared to that mentioned above, it wouldn't be less effort in programming for me, but rather a loss in efficiency I suppose. (Additional modules would be loaded and strings would be copied once more.) Thank you, anyway. Bertram -- Bertram Scharpf Stuttgart, Deutschland/Germany http://www.bertram-scharpf.de From nomail at nospam.no Sun Jun 13 13:00:17 2004 From: nomail at nospam.no (Dominic) Date: Sun, 13 Jun 2004 19:00:17 +0200 Subject: Good IDE for Python In-Reply-To: <40cc6410$0$147$18b6e80@news.wanadoo.nl> References: <889cbba0.0406122346.2e77941b@posting.google.com> <40cc6410$0$147$18b6e80@news.wanadoo.nl> Message-ID: Ivan Herman wrote: > I am also a jEdit user... can you give the URL of this plugin? Yes, sure. http://jpydbg.sourceforge.net/ For debugging I had to add my sources path to a shell variable. I think it was PYTHONPATH. Otherwise your "imports" won't work. Ciao, Dominic From nospam at nospam.com Sun Jun 20 08:23:16 2004 From: nospam at nospam.com (NewToPython) Date: Sun, 20 Jun 2004 12:23:16 GMT Subject: datetime, calendar, time intervals References: <95aa1afa.0406162213.3cf3d7f7@posting.google.com> <10d35suo3ek1b51@news.supernews.com> Message-ID: On Thu, 17 Jun 2004 09:07:52 -0400, "John Roth" wrote: > >"David Eppstein" wrote in message >news:eppstein-ABCC82.23210816062004 at news.service.uci.edu... >> In article <95aa1afa.0406162213.3cf3d7f7 at posting.google.com>, >> michele.simionato at poste.it (Michele Simionato) wrote: >> >> > Strangely enough, I never needed the datetime and calendar module >> > before, so I just looked at them today. >> >> Me too. datetime was exactly what I wanted. Until I realized that it >> wasn't available in the 2.2.3 installation I needed my code to run in... > >Yeah, that's a problem. I've been avoiding putting a date type adapter >in the Python version of FIT for exactly that reason. Which brought up >the question of whether it would be possible to back-port it, and I >found that it was a C language module. Sigh. Sorry, I am new to Python, but I have a requirement for date manipulation in an app that will need to run in 2.2, so I am interested in the data functions of the latest release as well. When you say that it was a C module, are you saying the library of date functions in the latest version are written in C? Does this somehow stop us from back-porting it to 2.2 or 2.1 python? I would be very interested in seeing the C source code for the date routines, along with the routine descriptions - where can I find that? - Chris > >John Roth >> >> -- >> David Eppstein http://www.ics.uci.edu/~eppstein/ >> Univ. of California, Irvine, School of Information & Computer Science > From tzot at sil-tec.gr Tue Jun 8 05:50:48 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 08 Jun 2004 12:50:48 +0300 Subject: Destructors and exceptions References: Message-ID: On 8 Jun 2004 02:44:04 -0700, rumours say that dkturner at telkomsa.net (David Turner) might have written: >I can't think of any technical objections to having the exception >mechanism also release references to locals that are going to go out >of scope (unless one was planning to support resuming). Can you? Debugging. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From tjreedy at udel.edu Wed Jun 23 11:56:55 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jun 2004 11:56:55 -0400 Subject: Python intro questions (was: ) References: <2D1DF9BA9166D61188F30002B3A6E1530E68E2F0@ROSEEXCHMA> <10dj0jq3b1q6u2c@corp.supernews.com> Message-ID: "Cameron Laird" wrote in message news:10dj0jq3b1q6u2c at corp.supernews.com... > On an industrial scale, yes, pay for Python articles is > essentially zero. Please do note, though, that develop- > erWorks, O'Reilly, *Linux Journal*, *Linux Magazine*, > and at least a few other outlets have been surprisingly > generous in their support of Python-focused content. Other outlets includes Dr. Dobbs in the last few years. tjr From tzot at sil-tec.gr Wed Jun 2 09:21:26 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 02 Jun 2004 16:21:26 +0300 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> <2i4v2qFj4rvhU1@uni-berlin.de> Message-ID: <5ojrb0h573cipmlr83dgorlj22pq1vftpr@4ax.com> On Wed, 02 Jun 2004 09:52:58 +0200, rumours say that David Fraser might have written: >Greg Ewing wrote: >> Christian Gudrian wrote: >> >>> And what about the 'ss' in 'ssfd'? I don't know many languages that >>> allow >>> words to start with two identical letters. >> >> >> Obviously it's "my hovercraft is full of eels" with >> several spelling mistakes. >> > >The attached program shows that there is no one-to-one mapping of >characters that will result in this string matching words from >/usr/share/dict/words (at least on my machine) [snip code] I think Richard Brodie's remark about locality of the letters was enough to deduce that the "encrypted" text is just random keypresses. I also think the joke is actually a well-intended prank: readers might take it more seriously than they should, and start writing code to decrypt the text :) -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From rick.ratzel at scd.magma-da.com Fri Jun 4 11:02:33 2004 From: rick.ratzel at scd.magma-da.com (Rick Ratzel) Date: Fri, 04 Jun 2004 15:02:33 GMT Subject: undefined symbol: PyObject_GenericGetAttr when trying to embed Python In-Reply-To: References: Message-ID: You may have to link your app with some additional flags. You can use the distutils module to see which ones you need for loading shared objects (like _socket.so) at runtime. Here is what my Python build for Linux needs (from http://elmer.sourceforge.net/PyCon04 ): >>> import distutils.sysconfig >>> distutils.sysconfig.get_config_var("LINKFORSHARED") '-Xlinker -export-dynamic' Then, simply add -Xlinker -export-dynamic to the link line for the embedded Python app and the .so modules should have all the proper symbols resolved. Hope that helps, -Rick Ratzel Andreas Jung wrote: > I am trying to embed Python within a C++ application (Linux, Python2.3.4). > I am using the example from the example from the "Embeding and > Extending" docs. > This works fine importing a simple module without any imports. However > when I add > an "import urllib" inside the Python script to be imported through my > C++ application > then the import fails: > > Traceback (most recent call last): > File "/home/ajung/sandboxes/HR2/hr2_zope_wrapper/hr2_wrapper.py", line > 16, in hr2_wrapper > import urllib > File "/opt/python-2.3.4/lib/python2.3/urllib.py", line 26, in ? > import socket > File "/opt/python-2.3.4/lib/python2.3/socket.py", line 44, in ? > import _socket > ImportError: /opt/python-2.3.4/lib/python2.3/lib-dynload/_socket.so: > undefined symbol: PyObject_GenericGetAttr > > Any ideas? > > Andreas > > From bvande at po-box.mcgill.ca Fri Jun 11 11:59:32 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 11 Jun 2004 11:59:32 -0400 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: <40C9D6E4.9050704@po-box.mcgill.ca> Terry Reedy said unto the world upon 11/06/2004 11:31: > "Brian van den Broek" wrote in message > news:40C9C2F2.1020201 at po-box.mcgill.ca... > >>>>>myfile = open("myfilepath", "w") >>>>>myfile.write(reallybigbuffer) >>>>>myfile.close() > > >>>>... immediately raises a warning flag in the mind of an >>>>experienced Python programmer. >>> >>>Depends on the circumstance, I'd think. > > >> From that standpoint, I am wondering why the code that Michael P. >>Soulier provided above would worry an experienced Python programmer. > > > A reallybigbuffer might not fit on the hard disk, in which case writing > would raise an exception that it not caught. For an application intended > > Terry J. Reedy Thanks Terry! Best, Brian vdB From tootoo at yeah.net Wed Jun 23 21:17:47 2004 From: tootoo at yeah.net (dm) Date: Thu, 24 Jun 2004 09:17:47 +0800 Subject: vb mixed python programming Message-ID: Hi: I want to program using VB mixed python. who have any experience? and hwo to do ? thanks dm From michele.simionato at poste.it Fri Jun 18 00:10:53 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 17 Jun 2004 21:10:53 -0700 Subject: getting arguments off the command line References: Message-ID: <95aa1afa.0406172010.14fb5875@posting.google.com> "David Stockwell" wrote in message news:... > ... and if optparse seems a bit too verbose for your taste, there always my recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844 Michele Simionato From M.Waack at gmx.de Sun Jun 27 08:29:56 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sun, 27 Jun 2004 14:29:56 +0200 Subject: Timeout on file write? References: <40dda426$0$32608$a1866201@newsreader.visi.com> Message-ID: <47r2r1-cs8.ln1@valpo.de> Chris Farley wrote: > I would like to gracefully handle situations such as when the paper > is out or the printer is powered off. Right now the program just > hangs. The simplest way would be to use a timeout as described in the python lib docs, have a look at the signal module. Mathias From winexpert at hotmail.com Fri Jun 11 08:50:43 2004 From: winexpert at hotmail.com (David Stockwell) Date: Fri, 11 Jun 2004 12:50:43 +0000 Subject: [python] struct module round off error? Message-ID: Hi, When I started playing with the struct module, I wrote a simple little test program. I got the syntax bugs out of the way and found something that seems a bit odd. Here is my code ----- START ---- import struct print "Test of struct module" a = 5 b = 9 c = 'text' d = 50.3 myformat = 'ii4sf' print 'Original value for d[%s]' % d mystruct = struct.pack(myformat,a,b,c,d) print "packed mystruct.", mystruct, "., #bytes:", len(mystruct) unstruct = struct.unpack(myformat,mystruct) print 'After unpacking: ', unstruct ----- FIN de code ----- Here is the output ----- Start output ------ Test of struct module Original value for d[50.3] packed mystruct. text33IB ., #bytes: 16 After unpacking: (5, 9, 'text', 50.299999237060547) ----- FIN de output --- My question is with the 'd' object that I've setup. When I first set it and print it, it has the correct value (50.3). However all i did was pack it, and then unpack it and it lost its definite value of 50.3. After the unpack it was approximately 50.3 (50.29999......) I tried changing the format of d in the pack to a double but still got the same answer of approximately 50.3. The only difference I see here is the double is an 64 bit number and the float a 32 bit number. What can I do short of data manipulation to force the correct number? One way to do this would be to normalize the number to something like this d = 50.3 * 10 then do the pack like this pack('d',d) later when i unpack it ( Interesting side note: 503.0 packed as a 'd', when unpacked comes out 503.0 as opposed to 503) then div by 10. does python implement the IEEE fp standard, or does it implement java's approach (which uses less bits)? What can I do to prevent this sort of round off error so I can guarantee my numbers stay correct when I use python structs? David ------- free phone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From opengeometry at yahoo.ca Wed Jun 16 14:45:56 2004 From: opengeometry at yahoo.ca (William Park) Date: 16 Jun 2004 18:45:56 GMT Subject: Request for Comments -- shell features and documentation Message-ID: <2jbir3Fvp7bdU1@uni-berlin.de> Dear Experts and Newbies, As you know, I've been adding to Bash many useful features from Awk, Python, Zsh, and Ksh, and other things that you probably never heard of. Few pieces were posted here under "(patch for Bash)" subject. It's been pretty stable, so ready for release to general public. It can be found at http://freshmeat.net/projects/bashdiff/ I would appreciate any comments on features - whether it is useful to you, - what other features you might like to see, etc. documentation - whether it is clear and understandable, - what is missing, how it can be made clear, etc. Comments from Awk/Python/Zsh/Ksh users are most welcome, since they have been primary source of inspirations. :-) Yours truly, -- William Park, Open Geometry Consulting, No, I will not fix your computer! From delgado at informatik.uni-tuebingen.de Sat Jun 12 14:39:20 2004 From: delgado at informatik.uni-tuebingen.de (Olaf Delgado) Date: 12 Jun 2004 18:39:20 GMT Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> <7xhdtgzrtn.fsf@ruckus.brouhaha.com> Message-ID: In article <7xhdtgzrtn.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > > It occurs to me that I'd also like to do polynomial arithmetic over > finite fields, i.e. in GF(2**n)[x] for small n. I realize that's a new > request but I wonder if you know of anything. Thanks. Some years ago I wrote code to do some simple arithmetic in polynomials and finite fields for a class on Python which I taught. As far as I remember, you could combine these as well. It's not very sophisticated and probably not state of the art regarding current Python features, but I think it should still work. If you're interested, I could dig out the code for you. I'd be curious as well as to whether there is some more advanced and actively maintained package around for these things. Cheers, Olaf From chris.stone at gmail.com Sun Jun 27 04:03:37 2004 From: chris.stone at gmail.com (Christopher Stone) Date: 27 Jun 2004 01:03:37 -0700 Subject: Implementing a QFilePreview Class with PyQt Message-ID: Does anyone have an example of how to do this? When I try to make a class that subclasses from a QFilePreview class and a QWidget class, I get the following error: TypeError: Cannot sub-class from more than one wrapped class From ark at acm.org Fri Jun 18 10:33:06 2004 From: ark at acm.org (Andrew Koenig) Date: Fri, 18 Jun 2004 14:33:06 GMT Subject: Using multiple "*"-style arguments References: Message-ID: "Dave Opstad" wrote in message news:dave.opstad-D50FCC.07252818062004 at reader0901.news.uu.net... > File this one under "enhancement request" I guess, but it would sure be > nice. I wrote this line the other day, thinking it would just work: > > x = struct.pack(">HhhhhhhHHHL", i, *bounds, *b[0:2], *b[6:9], len(s)) > > Unfortunately, it doesn't. The only valid place for an "*"-style > argument is at the end of the arguments list. But this line seems so > natural! Since struct.pack expects all its arguments separately (rather > than gathered into a list or tuple), I have to be able to accommodate > its needs, and since I had several arguments already in lists, I thought > I could get away with this notation. Does this do what you want? x = struct.pack((">HhhhhhhHHHL", i, *(bounds + b[0:2] + b[6:9] + [len(s)])) From rowen at cesmail.net Tue Jun 8 14:41:20 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 08 Jun 2004 11:41:20 -0700 Subject: Tkinter wait_variable problem: hangs at termination Message-ID: I want to support execution of simple user-written scripts in a Tkinter application. The scripts should be able to wait for data and such without hanging the GUI (and without having to write the script as a bunch of asynchronously called subroutines). I decided to use Tkinter's wait_variable. I built a "script runner" object that has suitable wait methods. Internally each of these methods registers a callback that sets a variable when the wait condition is satisfied, then calls wait_variable to wait until the variable is set. The resulting scripts are simple and seem to work well, e.g.: myscript(sr): # do some normal python stuff that is fast sr.waitForData(...) # more normal fast python stuff sr.waitForMS(time) # etc. Unfortunately, if a user closes the root window while wait_variable is waiting, the application never fully quits. On my unix box the root window closes but the command-line prompt never returns and ^C is ignored. The process isn't using excess cpu cycles; it's just not listening. I have tried registering an atexit handler and adding a __del__ method so that the variable being waited on is toggled at shutdown, but it makes no difference. Here is an example: Press "Start" to start the script (which simply prints a number to sys.stdout every second, then quits. Close the root window while the script is waiting to print the next number, or after pausing the script, and you'll see the problem. Any suggestions for how to avoid/work around this problem? If it's a Tkinter bug I'll report it. -- Russell P.S. I saw that some perl/Tk users got around a different problem by faking wait_variable by running a tight "do one event, see if the wait condition is satisfied" loop. I don't think Tkinter allows one to execute a single event, and I suspect it would be inefficient even if it were possible. I might be able to use update (though the nice thing about wait_variable is most of the action happens down at the tcl/tk level, presumably making it maximally efficient). (This is one of those rare times I wish Tkinter worked at the C level the way perl's tk interface does.) From me at privacy.net Tue Jun 22 04:24:04 2004 From: me at privacy.net (Duncan Booth) Date: 22 Jun 2004 08:24:04 GMT Subject: References and copies References: Message-ID: "Larry Bates" wrote in news:ddqdnZ_PjrmN3krd4p2dnA at comcast.com: > You might try: > > x=n*[n*[' ']] > > But I always question creating arrays this > way in Python. It is normally much better > to start with an empty list and build it as > you go using .append() method. > Its just as well you question this as it creates a list containing n copies of the same list. A better way to write your example: x = [ n*[' '] for i in range(n) ] From jacek.generowicz at cern.ch Fri Jun 4 03:30:16 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 04 Jun 2004 09:30:16 +0200 Subject: Optimizing multiple dispatch References: Message-ID: Jeff Epler writes: > No message about optimization should be without one downright wrong > suggestion. Ain't dat da truth! From dkturner at telkomsa.net Tue Jun 15 04:04:22 2004 From: dkturner at telkomsa.net (David Turner) Date: 15 Jun 2004 01:04:22 -0700 Subject: does python have useless destructors? References: Message-ID: > > > >It's pretty darn hard to mess something like this up. So yes, you > >*can* use heap-based objects as RAII containers. > > It's pretty darn easy: what happens when you pass those pointers outside > of their stack holders? That's a *normal* part of Python programming; > changing that requires a whole new paradigm. > What happens is that you get an extra reference to it, just as you'd expect. When that reference is released, the file closes. So, no new paradigms there then. Regards David Turner From tkpmep at hotmail.com Wed Jun 16 14:49:48 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 16 Jun 2004 11:49:48 -0700 Subject: What ought to persist after a program is run? Message-ID: Here's a very simple program with an odd twist: class Player(object): def __init__(self,name): self.name = name hero = Player("A") print "hero",hero If I run it in IDLE and then type dir() at the prompt, I get >>>['Player', '__builtins__', '__doc__', '__name__', 'hero'] However, if I modify the program as follows class Player(object): def __init__(self,name): self.name = name def main(): hero = Player("A") print "hero=",hero main() and then run it in IDLE and type dir at the prompt, I get >>>['Player', '__builtins__', '__doc__', '__name__'] Why does 'hero' not appear in the workspace directory when main() is invoked and vice versa? Thomas Philips From rawbobb at hotmail.com Thu Jun 10 18:03:10 2004 From: rawbobb at hotmail.com (bobb) Date: Thu, 10 Jun 2004 22:03:10 GMT Subject: Zope NewBie loosing hairs on python References: Message-ID: I believe your looking to use an external method. there is a zope group also, zope at zope.org... bobb "Krapul" wrote in message news:fa50f244.0406090920.32ae6383 at posting.google.com... > Hi everybody, > > I'm using python for long time, now; currently developing a web-based > game working with python CGI and IIS. I've heard about various > interesting zope functionalities, but I'm facing a problem while > simply trying to integrate my python code within zope. > > Let's depict a bit of example, I could schematise my current apps like > this: > > ***on one side, I have a python module...let's say testa.py, formated > like this: > > class testb: > def __init__(self): > self.x='hello' > def dsp(self): > return self.x > > ***on the second side I have a CGI: > > import cgi,cgitb > import sys > import testa > sys.stderr = sys.stdout > print "HTTP/1.0 200 OK" + chr(13)+chr(10) > > a=testa.testb() > x=a.dsp() > print ""+str(x)+" > cgitb.enable() > ************************************************************************ > > What I would understand is : "Is there a way to upload my python > module to zope and then using it in a dtml page (I guess)instead of > CGI?" > > Please somebody help...I'm completly lost...Thanks in advance, > > Ludo From fishboy at spamspamspam.com Sat Jun 5 23:57:49 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 03:57:49 GMT Subject: How to run email-unpack.py from the Email Message Module. References: Message-ID: On Thu, 03 Jun 2004 15:08:21 +0100, Chuck Amadi wrote: >Im running $ python email-unpack.py -d /home/chuck/surveyResults >What parameters do I use I have tried substituting msgfile fp = open(msgfile) >for my given path (/home/chuck/Mail/Inobx) still no joy please explain what im >missing Im using the example from > Wild guess. Try executing the script directly: chmod 755 email-unpack.py ./email-unpack.py -d /home/chuck/surveyResults ><{{{*> From eppstein at ics.uci.edu Sat Jun 26 00:42:30 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 25 Jun 2004 21:42:30 -0700 Subject: any trick to allow anonymous code blocks in python? References: <10dphkp78g6ne9d@news.supernews.com> Message-ID: In article , Doug Holton wrote: > > b.OnClick = (lambda : sys.stdout("You clicked me")) > > Yeah, I didn't mention the lambda option. I was thinking about > designing a framework meant for beginners, and I'd rather stay away from > lambdas. I'm surprised no one is even proposing support for anonymous > code blocks in Python that support multiple lines, similar to what Ruby, > Java, and other languages have. Presumably the right (but non-Python) syntax for such a code block would be: def b.onClick(): print "You clicked me" One reason for not adding this to Python would be the difficulty of determining where the expression for the def'd object ends and where the argument list for its definition begins. One could imagine working backwards from the colon but I don't think Python's parser can do that, and anyway if it's difficult for machines to parse it's also difficult for humans to read. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From alloydflanagan at comcast.net Tue Jun 8 16:19:46 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 8 Jun 2004 13:19:46 -0700 Subject: Fw: any simple and multiplatform database? References: Message-ID: "Simon Roses Femerling" wrote in message news:... > Thx for your response > > sqllite looks very interesting :) > Here is the python module: http://sourceforge.net/projects/pysqlite/ > > I'm familiar with mysql and postgresql but there are too heavy and I > dont want to install a database. > > I'm looking for something like sqllite > > thx > > Sincerely, > > SRF If your needs are basic enough, the standard module anydbm is both simple and cross-platform. From vpopmail at emeka.unacom.net Fri Jun 25 23:05:39 2004 From: vpopmail at emeka.unacom.net (User Vpopmail) Date: Fri, 25 Jun 2004 22:05:39 -0500 (EST) Subject: (no subject) Message-ID: <200406260305.i5Q35dkt016156@emeka.unacom.net> From: support at unacom.net Subject: Help Desk Submission Sorry, you do not seem to have an account at the help desk. To submit requests via e-mail you must register. To do so please visit: http://support.unacom.net/cgi-bin/support/ Thank You. From paul at subsignal.org Tue Jun 29 04:16:43 2004 From: paul at subsignal.org (=?ISO-8859-1?Q?paul_k=F6lle?=) Date: Tue, 29 Jun 2004 10:16:43 +0200 Subject: Tkinter and Listbox questions Message-ID: <2kbgmrFd3e5U1@uni-berlin.de> Hi all, I have two instances of a custom Listbox in my frame with selectmode=multiple. When I leave one listbox to select items in the other, all entries in the fist one get lost (cleared). Is this 'normal'? Do I really have to catch the 'leave' event and restore the selection when reentering? thanks Paul From b_willy at hotmail.com Mon Jun 14 10:50:25 2004 From: b_willy at hotmail.com (Backhaus Willy) Date: Mon, 14 Jun 2004 16:50:25 +0200 Subject: xmodem or ymodem in python Message-ID: <2j5s9uFtve9sU1@uni-berlin.de> hello, where can I find sources for a xmodem or ymodem implementation in python? thanks, Willy email: w dot backhaus at newage-avkseg dot com From hungjunglu at yahoo.com Thu Jun 10 11:10:24 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 10 Jun 2004 08:10:24 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> Message-ID: <8ef9bea6.0406100710.1a17b11b@posting.google.com> moughanj at tcd.ie (James Moughan) wrote: > I still have to restrain myself from writing PyHaskell now and then. Maybe it's time to try with some simple prototype. > Secondly, Lisp's syntax doesn't parse well into the way people think, > or vica versa. Python's does; in other words, it's executable > pseudocode. Lisp, fundamentally, cannot change in this regard. But Python does have serious problems when one goes to the next level of software development. I guess that's why Io and Prothon were born. Python is at the stage where you need a fresh re-incarnation to go to the next level. There are a few directions that need to be explorered, and I am not sure creating a real new language is the way to go. I've seen it in Io, where once you set things in stone, it becomes just another Python with problems that will stay forever. I guess right now it's not the moment of creating more languages and set things in stone. It's probably better to have some toy languages or language prototypes to explorer ideas. Collect enough ideas and experience, and probably leave the rest to the next generation of people. Frankly, I see a few camps: (a) Lisp and AOP folks, (b) Functional folks, (c) Prototype-based folks. Because these are very specialized fields, very few people seem to be native speakers of all three of them. The next killer language will have to incorporate lessons learnt from all three camps. It's a daunting task. It's best to have some toy languages... like scaled-down model airplanes, or even just the model airplane parts, before one actually build the real thing. regards, Hung Jung From bart_nessux at hotmail.com Wed Jun 16 13:07:58 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 13:07:58 -0400 Subject: thread help In-Reply-To: <40cea9cb$1@nntp0.pdx.net> References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Aahz wrote: > >> Bart Nessux wrote: >> >>> Could someone show me how I can make this work correctly? I want to >>> probe > > >>64 unique IP address for HTTP servers simultaneously, ... > >> Create a threading.Thread subclass that takes one IP address and a list >> of ports to scan. Start 64 instances of this class, each with a >> different IP address. > > > An alternative is to create a que into which you push IP addresses to > contact, and have each thread read addresses off the queue when they are > free to process them. This has the advantage of decoupling the number > of threads from the number of addresses you want to examine. > > -Scott David Daniels > Scott.Daniels at Acm.Org I like this idea. I read up on the queue and threading module at python.org and a few other sites around the Web and came up with this, however, it doesn't work. I get these errors when it runs: Exception in thread Thread-149: Traceback (most recent call last): File "/usr/lib/python2.3/threading.py", line 434, in __bootstrap self.run() File "/usr/lib/python2.3/threading.py", line 414, in run self.__target(*self.__args, **self.__kwargs) File "www_reads_threaded_1.py", line 49, in sub_thread_proc f = urllib2.urlopen(url).read() File "/usr/lib/python2.3/urllib2.py", line 129, in urlopen return _opener.open(url, data) File "/usr/lib/python2.3/urllib2.py", line 324, in open type_ = req.get_type() AttributeError: 'NoneType' object has no attribute 'get_type' The problem I have is this: I know too little about thread programming. If anyone thinks the code I have below could be made to work for my tasks (probe 65,000 IPs for HTTP servers using threads to speed things up), then please *show* me how I might change it in order for it to work. Thanks again, Bart networks = [] hosts = [] urls = [] #socket.setdefaulttimeout(30) max_threads = 2 http_timeout = 30 start_time = time.time() # Add the network 192.168.0 possibility. networks.append("192.168.0.") # Generate and add networks 192.168.1-255 to the list of networks. n = 0 while n < 255: n = n + 1 networks.append("192.168.%s." %(n)) # Generate and add hosts 1-255 to each network for network in networks: h = 0 # Add the n.n.n.0 host possibility hosts.append(network+str(h)) while h < 255: h = h + 1 hosts.append(network+str(h)) for ip in hosts: ip = "http://" + ip urls.append(ip) urls = dict(zip(urls,urls)) # print urls # Create a queue of urls to feed the threads url_queue = Queue.Queue() for url in urls: url_queue.put(url) # print url def test_HTTP(url_queue): def sub_thread_proc(url, result): # try: f = urllib2.urlopen(url).read() # except Exception: # print "Exception" # else: result.append(url) while 1: try: url = url_queue.get(0) except Queue.Empty: return result = [] sub_thread = threading.Thread(target=sub_thread_proc, args=(url,result)) sub_thread.setDaemon(True) sub_thread.start() sub_thread.join(http_timeout) print result test_HTTP(urls) From irmen at -nospam-remove-this-xs4all.nl Sun Jun 27 15:18:23 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 27 Jun 2004 21:18:23 +0200 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: <889cbba0.0406271027.39b3044@posting.google.com> References: <40deae5e$0$65807$e4fe514c@news.xs4all.nl> <889cbba0.0406271027.39b3044@posting.google.com> Message-ID: <40df1d7f$0$65807$e4fe514c@news.xs4all.nl> (also in response to Mark's answer) Kamilche wrote: > >>...So, I'm sorry to say this but my experience with the new Pyzine >>is not too good. > > > Wow, that's not good, thanks for sharing that information with us. The > heck of it is, people probably WOULD write articles for their magazine > for their preferred set price (read: FREE!) if they would give them > even a magazine subscription in return. But that's a total gyp, > instead. Also to Mark: apologies for writing my story in the (too short) way that I did, you're comments are valid. What I wrote are the facts, but I may have expressed it too harshly. > Sorry to hear that you wasted your time! I didn't. The article *is* published. And I don't care about the money (I wrote the article at the time when PyZine had a different form, there was no talk about any author payment at that time). So again, it's not a big issue, I just wanted to share my experience. --Irmen. From dooms at info.LESS.ucl.SPAM.ac.be Thu Jun 17 02:43:16 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Thu, 17 Jun 2004 08:43:16 +0200 Subject: cannot pass a variable from a function In-Reply-To: <40d13306$0$84222$5fc3050@dreader2.news.tiscali.nl> References: <40d13306$0$84222$5fc3050@dreader2.news.tiscali.nl> Message-ID: <40d13daa$0$84222$5fc3050@dreader2.news.tiscali.nl> Gr?goire Dooms wrote: > If I understand well what you need: > >>> def f(a): > global q > q = a * 80 > print q > > >>> def g(l): > global q > for i in l: > q = i * 80 But this should better be implemented as def g(l): global q q = l[-1] * 80 Even better: def g(q,l): return l[-1] * 80 # and use as q = g(q,l) -- Gr?goire Dooms From mark at pyzine.com Sun Jun 27 14:42:55 2004 From: mark at pyzine.com (Mark) Date: Sun, 27 Jun 2004 14:42:55 -0400 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: <889cbba0.0406271027.39b3044@posting.google.com> References: <40deae5e$0$65807$e4fe514c@news.xs4all.nl> <889cbba0.0406271027.39b3044@posting.google.com> Message-ID: Hello Kamilche, > >> ...So, I'm sorry to say this but my experience with the new Pyzine >> is not too good. > > Wow, that's not good, thanks for sharing that information with us. The > heck of it is, people probably WOULD write articles for their magazine > for their preferred set price (read: FREE!) if they would give them > even a magazine subscription in return. But that's a total gyp, > instead. Huh? If you actually took the time to visit Py and read our Writer's Guidelines you will find a big bold headline that reads: "Complimentary PyZine subscription for Authors" and Irmen of course got a free subscription. Cheers, Mark From peter at engcorp.com Wed Jun 23 08:32:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 08:32:08 -0400 Subject: Parsing C Preprocessor files In-Reply-To: <20040623140151.6b8863f2@pistache.sara.nl> References: <20040623140151.6b8863f2@pistache.sara.nl> Message-ID: <4ICdnaUZjtvV5UTdRVn-jw@powergate.ca> Bram Stolk wrote: > What could I use to parse CPP macros in Python? > I tried the Parnassus Vaults, and python lib docs, but could not > find a suitable module. Does it really need to be in Python? There are probably dozens of free and adequate macro preprocessors out there already. (You might also want to clarify what you mean by "parse" in this case... do you mean actually running the whole preprocessor over an input file and expanding all macros, or do you mean something else?) -Peter From fishboy at spamspamspam.com Sat Jun 5 23:15:09 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 03:15:09 GMT Subject: Execute a command from a cgi script References: <40dd3107.0406022028.3fcbe08b@posting.google.com> Message-ID: <8735c09t40h6nnavhnt9plc4ad8t6jdrrm@4ax.com> On 2 Jun 2004 21:28:37 -0700, tedlandis at rogers.com (Ted) wrote: >Hi all, > >I am trying to execute a batch file from a python cgi script on an IIS >webserver on Win2K. I have changed all the permissions I can think of. >The command I am using is: > >p = os.spawnl(os.P_WAIT, 'spameggs.bat') > >I am using spawn because I need the Wait, but I have tried popen* and >command and none of them work either. > >The odd thing is that if I embed the python code in an asp page it >works just fine. I am aware there are a lot of variables here but has >anyone seen anything like this before? > >Thanks, >Ted try os.system()? ><{{{*> From bill.ramsay at clear.net.nz Wed Jun 9 04:36:25 2004 From: bill.ramsay at clear.net.nz (bill ramsay) Date: Wed, 09 Jun 2004 20:36:25 +1200 Subject: MIME attachments, and alternatives Message-ID: Hello I am writing a program that sends simple text files to a remote device. the files have to be in the format textX.dat where X = numbers in the range 0 up to 10 depending upon the situation. these files are stored in a directory called attachments. The files themselves are single line affairs in ascii. the files have to be sent in base64. the final email has a simple subject line, to and from addresses, and the attachments. so far so good, I have written the program to do this, don't laugh here it comes. the print statements are just there so that i can follow whats going on at the moment. -------------------------------------------------------------------------------------- import os import smtplib import mimetypes from email import Encoders from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def send_dat_files(subject_matter,serial,fromAddr,toAddr): base = os.getcwd() print base attachpath = base+'\\attachments' if not os.path.exists(attachpath): os.mkdir(attachpath) # Create the enclosing (outer) message if subject_matter == 'SU': subjectstring = 'KKK_KRDS1_'+serial+'_SU' outer = MIMEMultipart() outer['Subject'] = subjectstring outer['To'] = toAddr outer['From'] = fromAddr outer.add_header('Content-Description','Remote Management System') outer.epilogue = '' fileNames=[f for f in os.listdir(attachpath)] for fileName in fileNames: path = attachpath+'\\'+fileName f=open(path,"rb") bodytext = f.read() f.close() ctype, encoding = mimetypes.guess_type(path) maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(bodytext) else: print 'we got a problem here' break Encoders.encode_base64(msg) # Set the filename parameter filestart,extension = fileName.split('.',1) fileName = filestart+'.dat' msg.add_header('Content-Disposition', 'attachment', filename=fileName) outer.attach(msg) # Now send the message s = smtplib.SMTP('smtp.paradise.net.nz') print 'connecting' s.sendmail(fromAddr, toAddr, outer.as_string()) print 'sent email' s.quit() sender = email at address copieraddr = email at address send_dat_files('SU', '65AN88888',sender,copieraddr) _____________________________________ questions are: 1. you may note that i have to change the file extension to .dat, this is a requirement of the receiving device, when i do that to the file attachment directly, the encoding does not work. any idea why? 2. the attachment files will be generated by anothe bit of code that i am writing, it strikes me as being a bit clunky to wirte these to an extenal folder then copy then in to the above, is there anywhay that i can take a string, then pretend that it is a file and attach it to the email? sorry if this is a bit long. look forward to hearing from anyone kind regards bill ramsay. From 0gk500b4gd0888 at cougar.noc.ucla.edu Fri Jun 18 12:20:12 2004 From: 0gk500b4gd0888 at cougar.noc.ucla.edu (0gk500b4gd0888 at cougar.noc.ucla.edu) Date: Sat, 19 Jun 2004 01:20:12 +0900 Subject: Here Message-ID: Here is the file. -------------- next part -------------- A non-text attachment was scrubbed... Name: yours.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From dooms at info.LESS.ucl.SPAM.ac.be Tue Jun 15 11:33:08 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Tue, 15 Jun 2004 17:33:08 +0200 Subject: How to Access Unix Shell In-Reply-To: <2j8ecuFulf37U1@uni-berlin.de> References: <2d7af4f8.0406131648.42868c63@posting.google.com> <2d7af4f8.0406140615.310f1875@posting.google.com> <2j8ecuFulf37U1@uni-berlin.de> Message-ID: <40cf16d8$0$41758$5fc3050@dreader2.news.tiscali.nl> Paul Watson wrote: > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import os >>>>dir(os) What about : Python 2.3.3 (#2, Feb 24 2004, 09:29:20) [GCC 3.3.3 (Debian)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> help(os) From elbertlev at hotmail.com Wed Jun 23 16:45:31 2004 From: elbertlev at hotmail.com (Lev Elblert) Date: 23 Jun 2004 13:45:31 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: <9418be08.0406231245.2358f470@posting.google.com> Kamilche! I'm also puzzeld with your results. Here is a little test script, which generates 16mb array and scans it. import time s = 'C' print time.clock() for i in range(24): s += s print len(s) print time.clock() for c in s: pass print time.clock() When I run it on 500mg P3 the output is: 8.38095110386e-006 16777216 0.275403081843 10.9032218052 on 1.6 P4 it runs 4 seconds. I'm new to Python and learnig it. Can't you publish the code? If the crypto method you are using is a secret, please give the basic idea, how did you achived such a speed. From sjdevnull at yahoo.com Thu Jun 24 14:38:44 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 24 Jun 2004 11:38:44 -0700 Subject: Keyword arguments and user-defined dictionaries References: <96c2e938.0406231629.4103ccde@posting.google.com> Message-ID: <96c2e938.0406241038.4269037c@posting.google.com> Christopher T King wrote in message news:... > > My question is, what methods do I need to implement to make ** work on > > a custom dictionary-like object, or is it not possible? > > As far as I can tell, it's not possible..... [SNIP] > > If the syntax "**expression" appears in the function call, "expression" > > must evaluate to a (subclass of) dictionary > > which seems pretty indicative that Python's shortcutting function calls > for efficiency reasons. Darn. > Your best bet is probably to call the function as func(**dict(mydict)). > dict() doesn't shortcut custom methods, so this should act as expected. Yeah, I have a .explode() method that tells the dictionary to de-Lazify everything; that's basically what (**dict)(mydict) would do, except passing as dict(mydict) would de-Lazify every function call and .explode() just once (though .explode would keep the exploded values in memory and dict(mydict) would toss them after the function returned). Thanks for your time. From e.d.andersen at mosek.com Tue Jun 29 13:54:16 2004 From: e.d.andersen at mosek.com (edadk) Date: 29 Jun 2004 10:54:16 -0700 Subject: Problem with Python on MAC OSX References: <2kcql4Fo2nbU1@uni-berlin.de> Message-ID: Hi, > But why don't you like the result? The directories pointed to by both > paths are the same... > This feature is casuing problem when I use the Scons build. See www.scons.org. It call external tools to do various thing for instance calling the perforce source control commandline tool p4 via spawn. So when Scons do something like 'p4 sync file.c' perforce gets confused because it wants to work with /home/eda/file.c and not /private/home/eda/file.c I agree in most case this feature is not causing any problems but sometimes it does. Regards Erling From a at a.invalid Tue Jun 1 07:39:47 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 01 Jun 2004 11:39:47 GMT Subject: OT: Cryptography puzzle Message-ID: <7WZuc.134$mt.29@read3.inet.fi> I was looking through my old emails, and ran across this in a signature: """ -----------------------> <--------------------------- When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! """ Curious as I was, I wanted to decrypt the end. At first I thought that it was ROT-13, and tried that. Nope. Then I saw the lone "k" in the middle, and thought that it must be "a", so I tried ROT-16. Wrong again. I also tried all other rotations, from 1 to 26, to no avail. Does anyone have any ideas what to try next? I also included the arrows, which began the signature, since I thought they might be significant in some way... -- WT From cpl.19.ghum at spamgourmet.com Sat Jun 26 07:16:23 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 26 Jun 2004 11:16:23 +0000 (UTC) Subject: how to search directories under References: Message-ID: Haim, google for python path module cheers Harald From chuck.amadi at ntlworld.com Thu Jun 10 02:14:21 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Thu, 10 Jun 2004 07:14:21 +0100 Subject: My simple script parse output screen and to a new file! In-Reply-To: <84k6ygmg30.fsf@redpeanut.com> References: <84k6ygmg30.fsf@redpeanut.com> Message-ID: <40C7FC3D.2090902@ntlworld.com> David Fisher wrote: >chuck amadi writes: > > >>fp = open("/home/chuck/pythonScript/testbox") >> mbox = mailbox.UnixMailbox(fp, email.message_from_file) >>for mail in mbox: >> print mail['Subject'] >> print mail.get_content_type()#text/plain >> print mail.get_payload() >> >> >If your going to use the UnixMailbox in two different loops, you'll >need to reinitalize it. Just call: > >fp = open("/home/chuck/pythonScript/testbox") >mbox = mailbox.UnixMailbox(fp, email.message_from_file) > >again before you use 'mbox' again. Otherwise the file pointer is >still pointing at the end of the file which is why you get nothing the >second time. Or alternately, just to be more confusing :), use: > >for mail in mailbox.UnixMailbox(open("/home/chuck/pythonScript/testbox"), \ > email.message_from_file): > print mail['Subject'] > print mail.get_content_type()#text/plain > print mail.get_payload() > >Which does it all in one stroke. > >Oh, minor nitpick. open(filename) is depredicated I believe. The new >prefered (for now :P) usage is file(filename). Which makes sense >since it returns a file object not an 'open' object > > > >><{{{*> >> >> Cheers I thought I was going mad with that for loop . Thanks From jacek.generowicz at cern.ch Mon Jun 7 07:53:31 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jun 2004 13:53:31 +0200 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> Message-ID: "Maboroshi" writes: > Hi I am fairly new to programming but not as such that I am a total beginner > > From what I understand C and C++ are faster languages than Python. Languages cannot be fast or slow. Their implementations, however, differ in the speed with which they execute algorithims expressed in those languages. It is true that, today, most C++ implementations will tend to execute a C++ implementation of some algorithm more quickly that Python implementations execute a Python rendition of the same algorithm. It is true that, today, if speed of execution of the final product is the only factor you take into account when assessing the "speed" of a language[1], then C and C++ will appear to be "faster" than Python. > Also from what I understand there are Interpreted and Compiled > languages Languages are a means of expressing information. Whether or not they are compiled and interpreted, depends on what one choses to do with them. There are computer programs which interpret some computer programming languages[2]; these are called interpreters. There are computer programs which translate some computer programming languages into other computer programming languages; these are called compilers. There are computer programs which do a mixture of interpreting and translating; these are sometimes called partial evaluators. If it were to mean anything to say that a given language is compiled, then I propose that it would mean that a compiler for that language exists. An interpreted language would therefore be one for which an interpreter exists. Given those working definitions of "interpreted language" and "compiled language", your statement seems correct: there are languages which are both interpreted and compiled[3]. An example of such a language is Common Lisp; most implementations of Common Lisp systems include both an interpreter and a compiler for Common Lisp. C++ is an interpreted language: http://root.cern.ch/root/Cint.html C++ is, of course, also a compiled language: http://gcc.gnu.org/ so, C++ is another example of an "Interpreted and Compiled language", lending further support to your sattement. > Python is an Interpreted Language, am I right? Python is most certainly a compiled language. Python source code is first compiled into Python bytecode. Python bytecode is usually interpreted. You should also note, that the languages that one typically talks about as "fast" and "compiled" languages, are compiled to an _interpreted_ language: machine language. The interpreter which interprets the latter is implemented in the hardware itself. Please think about that last point, if you are ever tempted to suggest that interpreters, or the languages that they interpret are slow. > Or is this completely wrong? I'll let you draw your own conclusions. In case I made my point too subtly: Try to avoid pigeonholing languages. Trying to find out how to use each to your best advantage, is far more productive. Don't put too much faith in common wisdom. Try not to get in the habit of throwing mere words around. Understand the concepts which are represented by the words you use, in the context in which you use them. Expressing yourself precisely and accurately is important in computer programming, and not only in computer programming. HTH, [1] Thereby overlooking two factors which, in real-world programs, are often at least as important, and sometimes much more important: speed of development, and speed of maintenance. [2] I really should be saying "... interpret programs written in some computer programming languages ...", but these sentences are convoluted enough as it is. [3] I am deliberately interpreting the original, ambiguous, statement in a way in which it was not intended to be understood. From pearsoneric at yahoo.com Sat Jun 26 02:00:48 2004 From: pearsoneric at yahoo.com (pearsoneric) Date: Sat, 26 Jun 2004 06:00:48 -0000 Subject: new to this Message-ID: I have never tried to program before but I'm starting a class and I was wondering if anyone knew the best way to get started learning about python?? Any help would be very much welcomed because I have no idea what I'm doing.. Are there any good books out there? From liquid at kuht.it Mon Jun 21 09:04:04 2004 From: liquid at kuht.it (Gian Mario Tagliaretti) Date: Mon, 21 Jun 2004 15:04:04 +0200 Subject: sys.stdout.write() question Message-ID: <200406211504.04745.liquid@kuht.it> Hi all, It is (I hope) a simple question, I cannot figure out why sys.stdout.write() doesn't print immediatly the first text in the small example below, but before it process the code in between and then print both lines in one time. #!/usr/bin/env python import sys, time sys.stdout.write('write ') time.sleep(3) sys.stdout.write('this\n') if you try to run this, before it will wait 3 seconds and then print "write this" in one time. If I put \n here : sys.stdout.write('write \n') it work properly but I would like to print the text in one row. thanks to all Mario From chuck at smtl.co.uk Wed Jun 9 05:20:00 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Wed, 09 Jun 2004 10:20:00 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Wed, 09 Jun 2004 09:26:31 BST." <200406090826.i598QVeb002497@sevenofnine.smtl.co.uk> References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> <200406090826.i598QVeb002497@sevenofnine.smtl.co.uk> Message-ID: <200406090920.i599K0eb002672@sevenofnine.smtl.co.uk> Hi all forget my last post about all email body messages I added a comment before break . Sorry for reading my own comments lines. I get output desired .Now to pass to an external File. for mail in mbox: # body = mail.get_payload() # bodies.append(body) # msg = mail.message_from_file(mail) print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() # break # just look at one message From chuck at smtl.co.uk Wed Jun 9 04:26:31 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Wed, 09 Jun 2004 09:26:31 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Tue, 08 Jun 2004 09:18:01 GMT." References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> Message-ID: <200406090826.i598QVeb002497@sevenofnine.smtl.co.uk> Hi After createing a mailbox using packf packf +/home/chuck/testwwws all -file testbox and thus cp 3 5 6 (emails) . I get output with this except only one email header and body message , the commented out stuff , does that iterate or can it produce all current 3 email body messages. Cheers Im nearly there. for mail in mbox: # body = mail.get_payload() # bodies.append(body) # msg = mail.message_from_file(mail) print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() break # just look at one message From peter at engcorp.com Tue Jun 29 00:29:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 00:29:12 -0400 Subject: Speed of str(positive_integer).. In-Reply-To: References: <1ED4ECF91CDED24C8D012BCF2B034F13064C02AE@its-xchg4.massey.ac.nz> Message-ID: <8MKdnZysOvuFbX3dRVn-hQ@powergate.ca> alejandro david weil wrote: > On Mon June 28 2004 23:41, Tony Meyer wrote: >>I suppose that the divmod implementation could check to see if both numbers >>were integers and then do the faster integer case. You'd have to convince >>TPTB that the speed increase was worth it and that the overhead of doing >>the test didn't outweigh the benefits, though. > > What's TPTB? From context it appears to be The Powers That Be... From peter at engcorp.com Wed Jun 16 10:04:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 10:04:29 -0400 Subject: Rationale for core Python numeric types In-Reply-To: References: Message-ID: Matt Feinstein wrote: > I'm new to Python, and was somewhat taken aback to discover that the > core language lacks some basic numerical types (e.g., single-precision > float, short integers). I realize that there are extensions that add > these types-- But what's the rationale for leaving them out? Have I > wandered into a zone in the space/time continuum where people never > have to read binary data files? Check the docs for the struct module: http://docs.python.org/lib/module-struct.html Also start leaving your C background behind, since it will limit you in many other ways as you learn Python. :-) -Peter From bitshadow at yahoo.com Thu Jun 17 16:54:28 2004 From: bitshadow at yahoo.com (Michael Scarlett) Date: 17 Jun 2004 13:54:28 -0700 Subject: is there a python icq bot? References: <1087376647.8125.2.camel@dubb> Message-ID: Gerhard H?ring wrote in message news:... > gabor wrote: > > hi, > > > > is there a python icq bot somewhere? > > > > or at least a simple python icq library? [...] > > I use supybot. It rocks. I can highly recommend it. > > -- Gerhard yeah check this out: http://epycycle.athenia.org/index.spy?page=home From a at a.invalid Tue Jun 8 00:13:39 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 08 Jun 2004 04:13:39 GMT Subject: left-quote ( ` ) on International keyboards [Prothon] In-Reply-To: <6%axc.6$0N1.3@read3.inet.fi> References: <40c39ced$0$12752$636a15ce@news.free.fr> <6%axc.6$0N1.3@read3.inet.fi> Message-ID: Timo Virkkala wrote: > Mark Hahn wrote: > >> Is $ easier to type on foreign keyboards? > > > Well.. It's AltGr+4 on the Finnish keyboard, so not too hard. Easier > than {[]}\, since they are AltGr+7890+ and you can really do them with > one hand, whereas @?$ can be done with two hands. ... reading that sentence and realizing that it's a bit strange: It's not really the fact that it's one/two-handed, but with AltGr, I have to twist my right hand to a strange angle with the one-handed chars. The two-handed ones are faster to type. -- Timo "WT" Virkkala From steve.menard at videotron.ca Thu Jun 10 15:07:48 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Thu, 10 Jun 2004 15:07:48 -0400 Subject: Distutil question In-Reply-To: References: Message-ID: <6o2yc.16053$Rz.213893@weber.videotron.net> Chris Green wrote: > Steve Menard writes: > > >>How do I go about distributing those files so that a source >>dsitribution will compile properly? should I rename them to .h files >>instead? > > > The way I always fix this type of thing is to create a MANIFEST.in > and add > > recursive-include src *.hpp to it. Thanks man! that did it! Steve From miki.tebeka at zoran.com Thu Jun 17 08:39:13 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 17 Jun 2004 14:39:13 +0200 Subject: Rationale for core Python numeric types In-Reply-To: References: Message-ID: <20040617123913.GH2048@zoran.com> Hello Matt, > I'm new to Python, and was somewhat taken aback to discover that the > core language lacks some basic numerical types (e.g., single-precision > float, short integers). I realize that there are extensions that add > these types-- But what's the rationale for leaving them out? Have I > wandered into a zone in the space/time continuum where people never > have to read binary data files? I think the reason most types were left out is that they are machine specific and Python tries to be as cross platform as it can. I'm sure Tim will have more on the subject ;-) I work *a lot* with binary files and don't find these missing types any problem. Python provides good access to binary data with `array' and `sturct' modules. If I need some bounded number the following class is enough: class SizedNum: def __init__(self, size, value=0): self.mask = (1 << size) - 1 self.set(value) def set(self, value): self.value = value & self.mask You can get fancier by sub-classing long type. Maybe you can be more specific on *why* do you need these types. IIRC a rational type is about to be added. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From j_mckitrick at bigfoot.com Fri Jun 11 09:52:53 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 11 Jun 2004 06:52:53 -0700 Subject: How do you write test suites for GUI components? Message-ID: What exactly do you test for? From richie at entrian.com Wed Jun 16 08:25:15 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 16 Jun 2004 13:25:15 +0100 Subject: how to become a really good Python programmer? In-Reply-To: References: Message-ID: <0bd0d0pj4oed6pvra6br62k56piijmlm50@4ax.com> [Randall] > As I write more and larger and complex programs, I need to > code better. By better I mean clearer, cleaner, more efficient and > maintainable. If you're not doing so already, start using Test-Driven Development. Google will give you any number of resources about that, but in a nutshell it means writing unit tests *before* writing code, then writing the code to make the tests pass. This forces you to think about the design of your modules up front, and usually leads to better-designed software. The modules you write will have cleaner interfaces and will be less dependent upon each other, more clearly written, more reusable, and more amenable to changing without breaking things. The other important feature of test-driven development is that it's *hard*, or at least it's hard for some application areas (like networking and GUIs). There's nothing like working on a hard problem to sharpen your skills - knocking up a messy script is easy, but you don't learn from it. A concrete example of why it's hard and why it leads to better code: I have a lightweight RPC system (as yet unpublished) that sends "safe pickles" over the network to invoke functions on another machine. The unit tests are a mess, because they run the client and server socket code in different threads in the same process, and synchronising them is painful. Had I thought more about it up front, I'd have realised that the RPC system should be transport-independent, and the unit tests should provide a trivial transport system for the RPC code to use during the tests, rather than mucking about with sockets. I'd have ended up with a nice transport-independent RPC module with simple and complete unit tests, plus a tiny transport module to implement a socket transport for it. Done right, the transport module would be so trivial that either it didn't need unit tests, or the tests would be very simple. A question for experienced TDD-ers: is TDD really more intellectually demanding than code-first, or am I either a) doing it wrong, or b) stupid? -- Richie Hindle richie at entrian.com From llothar at web.de Fri Jun 4 14:03:17 2004 From: llothar at web.de (Lothar Scholz) Date: 4 Jun 2004 11:03:17 -0700 Subject: Why did no one invent Python before? References: Message-ID: <6ee58e07.0406041003.25e359fc@posting.google.com> Michael Sparks wrote in message news:... > Taking that same jump to extremes, *if* CPU cycle availability continues > to scale for the next 10-15 years, the same tests would take around 1.2 > seconds, meaning the entire test suite _might_be possible to run during > program startup. At that point new languages and programming techniques > might become _practical_ which aren't practical today. > > At that point, someone might come along and say "I can't believe how much > more productive I am with the built in runtime system diagnostic testing, > and automated algorithm anealling that Foobarr offers. It made me want to > quit my Python job. Well, not quite. ;-)". That already happened: the language is called Eiffel. Checking all pre- and postconditions and invariants on each call was terrible slow when i started my project with a PIV 400 MHz. It was mostly impossible to use on normal size data sets. Now i use a PIV 2800 and give away my product (http://www.ruby-ide.com :-) with all runtime checks enabled. This makes my programming style much much better. From michele.simionato at poste.it Wed Jun 16 23:58:20 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 16 Jun 2004 20:58:20 -0700 Subject: Making classes from Metaclasses globally available References: Message-ID: <95aa1afa.0406161958.54746ad4@posting.google.com> Jacek Generowicz wrote in message news:... > (though in one case I would like to try having a third namespace > similar to globals and builtins where to shove all this stuff > ... unfortunately I haven't found a satisfactory way of creating one > yet.) I do not understand what the problem is ... you can just create a class (or instance) called namespace, put it in __builtin__ and call all the names in this custom namespace as namespace.myname. Maybe you do not like to tweak with __builtin__ (which I can understand); another option is to use a dynamically created module to fake a namespace: import sys from types import ModuleType sys.modules["namespace"] = ModuleType("namespace", """This is a dynamically generated module used to fake a namespace.""") #populate it with setattr, getattr I am sure you thought to this solution too, so what is unsatisfactory about it? Just to know, Michele Simionato From richie at entrian.com Fri Jun 18 04:17:49 2004 From: richie at entrian.com (Richie Hindle) Date: 18 Jun 2004 01:17:49 -0700 Subject: on TDD (was Re: how to become a really good Python programmer?) References: Message-ID: <8a6ba1da.0406180017.1948543f@posting.google.com> [Peter] > (Yes, yes, I can see you smiling, you who was just waiting for my > response... or John's. :-) Oh, so you're into TDD, Peter? I had no idea. Thanks for clarifying my summary of TDD - I can see how it might have been misunderstood. > Once you've been down that path once or twice, you will start to > see the warning signals well in advance, and eventually you will just > do the thing he concluded should have been done, automatically and > without thinking much, right at the start. I'm looking forward to it. 8-) For others looking to learn more about TDD, I've found this paper: http://www.edwardh.com/ieee_article/goingfaster.pdf useful as an introduction to the principles of TDD - not the nuts and bolts of how to practise it, but ideas like splitting your core code (eg. my RPC protocol) away from hard-to-test external libraries (eg. sockets). I think one of the problems I'm having is that I'm thinking like a module coder rather than a test coder. A question for any passing TDD-er (not with anyone specific in mind, of course, smart questions and all that 8-) - how much does the design of the module and its API get influenced by the requirement of writing tests for it? A coder has two tasks: write a module (and the code that needs to use it), and write tests for it. Both will have some bearing on the interface to the module, but in what proportion? My suspicion is that 75% of the design of the module's API will fall out of the way the tests are written, and that that's a good thing...? -- Richie Hindle richie at entrian.com From rigga at hasnomail.com Sat Jun 19 03:18:31 2004 From: rigga at hasnomail.com (RiGGa) Date: Sat, 19 Jun 2004 08:18:31 +0100 Subject: Remove spaces and line wraps from html? References: <5MHAc.16619$NK4.2886117@stones.force9.net> <6JQAc.16709$NK4.2922044@stones.force9.net> <9dRAc.16712$NK4.2922888@stones.force9.net> Message-ID: RiGGa wrote: > RiGGa wrote: > >> Paramjit Oberoi wrote: >> >>>>> >> > http://groups.google.com/groups?q=HTMLPrinter&hl=en&lr=&ie=UTF-8&c2coff=1&selm=pan.2004.03.27.22.05.55.38448240hotmail.com&rnum=1 >>>>> >>>>> (or search c.l.p for "HTMLPrinter") >>>> >>>> Thanks, I forgot to mention I am new to Python so I dont yet know how >>>> to use that example :( >>> >>> Python has a HTMLParser module in the standard library: >>> >>> http://www.python.org/doc/lib/module-HTMLParser.html >>> http://www.python.org/doc/lib/htmlparser-example.html >>> >>> It looks complicated if you are new to all this, but it's fairly simple >>> really. Using it is much better than dealing with HTML syntax yourself. >>> >>> A small example: >>> >>> -------------------------------------------------- >>> from HTMLParser import HTMLParser >>> >>> class MyHTMLParser(HTMLParser): >>> >>> print "Encountered the beginning of a %s tag" % tag >>> def handle_endtag(self, tag): >>> print "Encountered the end of a %s tag" % tag >>> >>> my_parser=MyHTMLParser() >>> >>> html_data = """ >>> >>> >>> hi >>> >>> hi >>> >>> """ >>> >>> my_parser.feed(html_data) >>> -------------------------------------------------- >>> >>> will produce the result: >>> Encountered the beginning of a html tag >>> Encountered the beginning of a head tag >>> Encountered the beginning of a title tag >>> Encountered the end of a title tag >>> Encountered the end of a head tag >>> Encountered the beginning of a body tag >>> Encountered the end of a body tag >>> Encountered the end of a html tag >>> >>> You'll be able to figure out the rest using the >>> documentation and some experimentation. >>> >>> HTH, >>> -param >> Thank you!! that was just the kind of help I was >> looking for. >> >> Best regards >> >> Rigga > I have just tried your example exacly as you typed > it (copy and paste) and I get a syntax error everytime > I run it, it always fails at the line starting: > > def handle_starttag(self, tag, attrs): > > And the error message shown in the command line is: > > DeprecationWarning: Non-ASCII character '\xa0' > > What does this mean? > > Many thanks > > R Ignore that, I retyped it manually and it now works, must have been a hidden chatracter that my IDE didnt like. Thanks again for your help, no doubt I will post back later with more questions :) Thanks R From BELLEMAIL-SA at exponent.com Sat Jun 12 19:50:55 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Sat, 12 Jun 2004 16:50:55 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28DEC@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = danb_83 at yahoo.com(DanBishop) Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 162 Scanning time = 06/12/2004 16:50:55 Engine/Pattern = 7.000-1004/903 Action taken on message: The attachment friend.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From allen at premierweb.com Sun Jun 13 00:08:23 2004 From: allen at premierweb.com (Allen Unueco) Date: Sun, 13 Jun 2004 16:08:23 +1200 Subject: time.strftime Timezone issue In-Reply-To: References: Message-ID: Tim, As it turns out it was my mistake for using gmtime() not localtime(). Not really any point is formating the timezone when you are asking for the time in UTC. But it is a little strange why it should change, if anything I would assume it would change to UTC. Here is the output from my Debian (woody) box Python 2.2.1 (#1, Feb 28 2004, 00:52:10) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.daylight 1 >>> time.strftime("%Z") 'EDT' >>> time.strftime("%Z", time.localtime()) 'EDT' >>> time.strftime("%Z", time.gmtime()) 'EST' It seems to work fine on my OSX system, although I'm confused by time.daylight being set to '1' when it's NZST right now, down here. Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.daylight 1 >>> time.strftime("%Z") 'NZST' >>> time.strftime("%Z", time.gmtime()) 'NZST' >>> time.strftime("%Z", time.localtime()) 'NZST' Sorry for the incomplete original post, -allen Tim Peters wrote: > [Allen Unueco] > >>I feel that the '%Z' format specifier from strftime() returns the wrong >>value when daylight savings is in effect. >> >>Today the following is always true: time.strftime('%Z') == time.tzname[0] >> >>Shouldn't it be: time.strftime('%Z') == time.tzname[time.daylight] > > > Please give a concrete example, including Python version and OS. Platform C > bugs in time functions are common as mud. Here's my concrete example, > Python 2.3.4 on WinXP running in US Eastern: > > C:\Code>\python23\python.exe > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import time >>>>time.tzname > > ('Eastern Standard Time', 'Eastern Daylight Time') > >>>>time.daylight > > 1 > >>>>time.strftime("%Z") > > 'Eastern Daylight Time' > > > Here's another, Python 2.2.2 on a Red Hat box: > > -bash-2.05b$ python > Python 2.2.2 (#1, Feb 24 2003, 19:13:11) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import time >>>>time.tzname > > ('EST', 'EDT') > >>>>time.daylight > > 1 > >>>>time.strftime("%Z") > > 'EDT' > > > > > > > > > > > From Mike at DeleteThis.Geary.com Wed Jun 9 23:13:05 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 9 Jun 2004 20:13:05 -0700 Subject: Newbie Copy Question References: <-oadnfi_sdy3UVrdRVn-hw@powergate.ca> Message-ID: <10cfke2cvs2icfa@corp.supernews.com> > Stacy wrote: > > Thanks for the response, Peter! Another reader helped me > > out, too, but I figured out what the problem was...the folders > > and file names are case-sensitive! Once I changed documents > > and settings...blah blah blah to Documents and Settings blah > > blah blah it worked just fine. Peter Hansen wrote: > My guess is that you've misinterpreted what happened, but I've > been wrong before. > > Windows is almost never (ever?) case-sensitive, though it does > tend to preserve the case of filenames (sometimes, when it > wants to). Unless the jump drive is somehow case-sensitive, > I doubt this was the problem. This depends on the filesystem, but all of the filesystems in common use on Windows are case-preserving (all of the time, not just when Windows "wants to" ) and case-insensitive. > Note that if you were still using backslashes, and include paths > that had escape sequences in them, switching to upper case > would avoid the bad side-effects of the backslashes, leading > you to think the paths were case-sensitive when they really > weren't. > > That would mean that any paths that had components following > a slash that began with \a, \b, \f, \n, \r, \t, \v, \x > (give or take a couple) would magically appear to work when > converted to \A, \B, etc. +1 (insightful!) -Mike From pet100us at yahoo.com Wed Jun 16 10:01:35 2004 From: pet100us at yahoo.com (pet100us) Date: 16 Jun 2004 07:01:35 -0700 Subject: Something simular to java's hsqldb for python?? Message-ID: <792ea523.0406160601.1b217d78@posting.google.com> Hi, Is there some program that is simular to java's hsqldb (http://hsqldb.sourceforge.net/). It is a relational database that can easily be used within a small java program without installing a MySQL, Postgresql etc. It is used within the same virtual machine whitout installing anything extra. Is there somthing similar for python? I need a small database that I can build into my application. When the program starts the database should start and when the programm exits the database can stop. I know that the samething could be done with xml files or binary files. The database has some advantages. e.g. when I want to change the program that it uses a "real" database I dont need to replace much of the code. I just change the database driver an off we go. (the programmers dream) Thanks in advance pet100us From qrczak at knm.org.pl Wed Jun 9 07:46:47 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Wed, 09 Jun 2004 13:46:47 +0200 Subject: Embedding Python in C Message-ID: I made a bridge between my language Kogut and Python, which gives my language instant access to Python libraries. (I'm only linking to libpython, I'm not using the standalone interpreter.) I have a question about the proper way of compilation and linking. Currently I do it like this: I assume that the interpreter installed as 'python' determines the version. I check Python version: if python -c 'import sys; sys.exit(not hasattr(sys, "version_info"))'; then ko_cv_python_major=`python -c 'import sys; print sys.version_info[0]'` else ko_cv_python_major=ancient fi and similarly the minor version. Currently I accept only 2.2 and higher because of language features (iterators); while I could support earlier versions too with appropriate conditional compilation, I didn't bother. I check Python include directory: ko_cv_python_include=`python -c 'from distutils import sysconfig print sysconfig.get_python_inc()'` I add this directory to -I options of the C compiler (currently GCC only is supported), and #include . For linking, I add -lpython for version 2.3 and above, and -lpython -ldl -lpthread -lutil -lm for earlier versions, i.e. 2.2 only. Problems: 1. How to do it better? For example I feel uneasy about the way I specify which libraries should be linked. Is there a way to determine it in a more robust way? 2. Someone has reported to me that he has no distutils installed. Why could it be? I thought distutils is a part of the core Python package. Can I rely on distutils, and if not, how to determine the include directory? 3. I assume that -lpython is the same version as the 'python' program, and give no way to select alternative versions if multiple versions are installed. Should I do it in some better way? -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From stephen.no at spam.theboulets.net.please Tue Jun 29 01:39:54 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Tue, 29 Jun 2004 00:39:54 -0500 Subject: Cut and paste to X clipboard? References: Message-ID: <8POdnegyuLE3nXzdRVn_iw@speakeasy.net> Stephen Boulet wrote: > Does anyone have a code sample for cutting and pasting to the X-clipboard > in python? I found a solution for this thanks to the 'xsel' program: Copy from the clipboard: import os s = popen('xsel').read() Paste to the clipboard (ok this is a pia): import os filename = os.path.join(os.path.expanduser('~'),'.tempclipboard') f = file(filename,'wb') f.write(s) f.close() command = 'xsel < %s' % filename os.popen(command).read() os.remove(filename) -- Stephen If your desktop gets out of control easily, you probably have too much stuff on it that doesn't need to be there. Donna Smallin, "Unclutter Your Home" From simoninusa2001 at yahoo.co.uk Wed Jun 30 00:35:57 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 29 Jun 2004 21:35:57 -0700 Subject: setting icon using py2exe? References: Message-ID: <30260531.0406292035.7fa2b82c@posting.google.com> I think you have to have win32all/pywin32 installed to do resource/icon handling. This works fine for me on Windows 98SE/XP/2000: setup( windows = [ { "script": "hellow.py", "icon_resources": [(1, "hellow.ico")] } ], ) If you can't get this to work, you could just include the .ico file using data_files=["hellow.ico"], and then create the shortcuts, pointing to the icon, using your install program, e.g. InnoSetup (kinda like I do under Linux). From bart_nessux at hotmail.com Thu Jun 17 21:10:01 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 17 Jun 2004 21:10:01 -0400 Subject: Queue module and Python Documentation Rant In-Reply-To: <6bl9q1-e98.ln1@home.rogerbinns.com> References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: <40D240E9.6070801@hotmail.com> Roger Binns wrote: > There is a qsize() method clearly documented. What is wrong with > that? Where??? The documentation for the module named Queue says nothing at all about this... http://docs.python.org/lib/module-Queue.html > The [Python] documentation is fine. The docs are useless. One needs a Master's in CS just to read the module index. In general, it's far too abstract. Many have no examples for actual *usage* at all. Read the section about classes in the tutorial... how long can you stay awake? It's so abstract and scholarly that it boarders on being useless. CS is applied math. However, Python does not think of itself as being applied, but theoretical. This is good if you're a geek with a Ph.D, but not if you're the average sys-admin attempting to solve an every-day problem. Python has a great syntax for beginners and advanced users alike. One can do sequential, procedural and OO programming with it. Also, it can be applied to most any problem on most any platform. However, the docs are an exercise in futility. They remind me of the circumlocution that I read about in law school... constantly talking around things instead of about things. This is good if everyone is on the same high-level of knowledge, but not for a programming language (think applied approach to problem solving) that has tremendous potential and is touted as user friendly for non-programmers. No wonder so many people use Perl. As bad as Perl is, it does not have a scholarly opinion of itself and is thus approachable and usable. Forgive me, I'm frustrated. Bart From klachemin at home.com Thu Jun 24 21:34:42 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 18:34:42 -0700 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> <889cbba0.0406240650.35ebf730@posting.google.com> Message-ID: <889cbba0.0406241734.14667b79@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > Note how badly your solution using str.translate() may perform for certain > data due to its failure to shortcut. > > Peter Heheh, I'm a Python newbie. I can't even understand the code you have written, but I'll try. You know, as I was writing stuff like fn(**args.__dict__) yesterday (which for me is pretty advanced!), it occurred to me that Python is not 'simpler than C', like I had originally thought. :-D It's better in many ways, but it has its dark alleyways where a novice can get stabbed in the back, too. {looks suspiciously down the dark alleyway where Peter's code is standing, and tries to glide by undetected.} --Kamilche From missive at frontiernet.net Wed Jun 23 17:03:45 2004 From: missive at frontiernet.net (Lee Harr) Date: Wed, 23 Jun 2004 21:03:45 GMT Subject: how to obtain its ip address ? References: <40d9c75d$0$26573$626a14ce@news.free.fr> Message-ID: On 2004-06-23, marco wrote: > I'd search a lot ... but i had not found > how can i obtain my ip address (when i'm connected to the www) ?! > Probably it will depend somewhat on your operating system. This works for me ... >>> import socket >>> socket.gethostbyname('localhost') '127.0.0.1' >>> hostname = socket.gethostname() >>> hostname 'homer' >>> socket.gethostbyname(hostname) '172.16.0.5' From sholden at holdenweb.com Fri Jun 4 09:08:21 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 04 Jun 2004 09:08:21 -0400 Subject: urllib2 - closing sockets In-Reply-To: <84fc4588.0406030041.77bcdeeb@posting.google.com> References: <84fc4588.0406030041.77bcdeeb@posting.google.com> Message-ID: <40C07445.8040201@holdenweb.com> Anand Pillai wrote: > I recently noted that urllib2.urlopen(...) for http:// urls > does not make an explicit call to close the underlying > HTTPConnection socket once the data from the socket is read. > > This might not be required since the garbage collector will > close & collect open sockets that are not closed, but it might > cause the system to run out of socket memory if there are > multiple threads, each opening a socket and the gc not running > in between. > > This specifically happens in my HarvestMan program which uses > multiple threads to achieve fast offline web downloads. > > A patch to fix this in urllib2.py would be nice. > > Thanks > > -Anand In which case you'd be well advised to add this as a bug report on Sourceforge, as that is the only way to guarantee it will come to (and stay in) the developers' attention. It isn't that hard to do. regards Steve From zen19725 at zen.co.uk Sat Jun 19 19:02:49 2004 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 20 Jun 2004 00:02:49 +0100 Subject: Am I crazy regarding the style guide for function names? References: <2jhlvtF11ti8bU1@uni-berlin.de> <10d8shvsq01auf0@corp.supernews.com> Message-ID: On Sat, 19 Jun 2004 10:05:03 -0700, Michael Geary wrote: >Peter Hansen wrote: >> Judging by the wording of the "function names" section before >> and after the edit, the earlier version which "allowed" >> mixedCase names was merely being descriptive (saying what >> the codebase currently looked like), while the new version is >> being *prescriptive* (attempting to force a particular style by >> defining it as the standard). >> >> Personally, I don't like the change, but I also have no intention >> of paying attention to it. Now that the editor and tab-wars are >> over, we have to have _something_ to argue over, don't we? ;-) > >I'm glad I'm not the only one. :-) > >ClassesLikeThis and methods_like_this sounds like a way to make everybody >unhappy: people who hate MixedCase and people who hate >names_with_underscores. > >Ruby uses exactly this same convention. I have no idea why. > >Myself, I'm sticking with ClassesLikeThis and methodsLikeThis for my Python >and Ruby code. (I don't like underscores at all!) How do you find Ruby? From what I've read of it, it has some nice features, and is similar to Python in many ways. Do you find it is so similar that you get confused between the two? -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: zen19725 at zen dot co dot uk) From llothar at web.de Sat Jun 5 20:19:02 2004 From: llothar at web.de (Lothar Scholz) Date: 5 Jun 2004 17:19:02 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> Message-ID: <6ee58e07.0406051619.5190c17e@posting.google.com> djw wrote in message news:... > I don't think I agree with your statement at the bottom that says "if > all else fails, try Psyco." Since using Psyco is so effortless and may > produce dramatic speedups, I would recommend to people that they try it > before resorting to writing extension modules in C/C++. Sending people But Psyco can consume really huge amounts of memory. From cpl.19.ghum at spamgourmet.com Tue Jun 1 16:04:40 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 1 Jun 2004 22:04:40 +0200 Subject: py2exe: setting packages from setup script References: Message-ID: > I tried packages=["wx"] but it didn't work. options = {"py2exe": {"packages": ["wx"]}}, a dictionary is expected. best wishes harald From me at privacy.net Wed Jun 23 21:22:59 2004 From: me at privacy.net (Heather Coppersmith) Date: 23 Jun 2004 21:22:59 -0400 Subject: Bug in __del__ function References: <217kd05a0ohtfqepgm2i2lvm7616lga918@4ax.com> Message-ID: On Wed, 23 Jun 2004 18:07:50 -0700, David MacQuigg wrote: > The example below is a repeatable test case. It might be possible to > simplify this further, but at this point, I haven't a clue as to why > it works with some sequences of commands, but not others. > I'm also not able to repeat the problem by putting the commands in the > file, and just running the file. Adding the necessary 'print' > keywords makes the problem go away. This could be just a problem in > IDLE, but unless I'm sure of that, I don't want to be using __del__ in > my programs. > Is this a bug, or have I misunderstood the use of __del__? [ code / interaction mostly snipped ] >>>> del cat1 >>>> cat2 > <__main__.Cat object at 0x00A11F70> >>>> rc(cat2) > sys.getrefcount(obj): 5 ### Should be one less. I'm not sure about that. The interactive prompt keeps a reference to the last thing it printed, which in this case was cat2. Perhaps IDLE has similar behavior? That would also explain why adding extra print statements and/or running from a file makes the problem go away. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From peufeu at free.fr Sat Jun 26 07:44:35 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Sat, 26 Jun 2004 13:44:35 +0200 Subject: Help formatting a mysql query string References: Message-ID: > sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" - what are the "," doing here if you are trying to build a string ? - you should use the python povided way which is better (yours looks like php) cursor.execute( "INSERT INTO %(tb)s VALUES(%(a)s,%(b)s,%(c)s)", { 'tb':tablename, 'a':first data, 'b':second data, etc... } From Christian.Gudrian at gmx.de Tue Jun 1 08:28:19 2004 From: Christian.Gudrian at gmx.de (Christian Gudrian) Date: Tue, 1 Jun 2004 14:28:19 +0200 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: "A.M. Kuchling" schrieb: > and the > doubled 'dd' letters are probably 'ss' or 'll'. And what about the 'ss' in 'ssfd'? I don't know many languages that allow words to start with two identical letters. So either the encryption is a little more advanced than to just replace characters -- or it's a Scottish text. ;) Christian From p_s_oberoi at hotmail.com Mon Jun 21 14:05:19 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Mon, 21 Jun 2004 13:05:19 -0500 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> <69cbbef2.0406210114.439f4ee@posting.google.com> Message-ID: > Presentation logic is application code too, regardless of where you > put it and what language it's written in. > > - The advantage of embedding logic in markup is it's easier for > non-programmers and other folk who aren't good at/don't like working > in the abstract to see what's going on. (i.e. easier mental modelling) > > - The advantage of separating the two is very designer-friendly markup > and complete freedom in how you design and implement the logic. (i.e. > easier maintainance) > > With HTMLTemplate et-al, there's nothing to stop you putting the > controller code in separate modules to the model code, making it easy > to edit the former without messing with the latter. (Splitting each > layer into its own module is probably a good design practice anyway.) You are right: there are three pieces to be managed (1)application logic, (2)presentation logic, and (3)markup. MY understanding of HTMLTemplate is that it enforces the separation of markup and all logic (both presentation and application), which is certainly very designer friendly. The problem is that: (1)presentation logic is often trivial, which means it is often not separated from application logic. (2)markup and presentation logic are often quite closely coupled (i.e. significant changes to the markup often require changes to the presentation logic), but they are in different places (and even worse, the presentation logic may even be mixed with the application logic). The second point above is why I don't understand your claim that the separation of presentation logic and markup would be easier to maintain. The only advantage I see is that separating the two makes it easier for designers to work with any tools they want to use. Ideally all three, application logic, presentation logic, and markup would be separate, but I think it's more important to separate application logic from presentation+markup than markup from application+presentation. Also, presentation logic and markup often just naturally belong together. But, my views are also colored by the fact that I've never dealt with large and complicated templates. In that case it would probably be a good idea to separate the template from presentation code just to keep the complexity under control. >> Cheetah-like systems are much more flexible (and simple >> substitution-only templates are very limiting). > > DOM-style templating systems aren't 'substitution-only', and can > easily match or surpass macro-style systems for power and flexibility > at a fraction of the size and complexity. By flexibility I meant flexibility in what you can do by modifying the template alone (since presentation logic can be added to the template). In the case of 'DOM-style' systems you may have to edit the template as well as the presentation logic (which would mean modifying the 'program', not just the template). From jeffbarish at starband.net Thu Jun 17 12:43:21 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Thu, 17 Jun 2004 10:43:21 -0600 Subject: Easiest way to port Python program to PDA Message-ID: I have been developing a Python program with two intercommunicating (using sockets) parts, one of which runs on a desktop and the other on a PDA.??For?ease?of?development,?I?developed?them?both?on?a?desktop.? Now that I have them working on the desktop, I need to move the part destined for a PDA to a PDA.??I?had?originally?planned?to?use?a?Sharp Zaurus because it runs Linux (the OS of my desktop system) and I had found a Python port that was supposed to be available for that platform (Riverbank Computing).??Unfortunately,?Riverbank?Computing?just discontinued their port.??They?refer?interested?parties?to?another?port (http://www.vanille.de/projects/python.spy), but that site has no code to download and does not respond to queries.??Accordingly,?I?have?to conclude that there is no Python port available for the Zaurus so I am back to square 1. My question in short: does anyone have suggestions for the easiest way to move the Python program to a PDA.??The?program?uses?a?few?modules from the standard distribution (2.3): socket, thread, time, os, and Tkinter.??I?expected?to?rewrite?the?GUI,?but?I?am?hoping?to?rewrite?the rest of the program as little as possible. I have discovered a python for StrongARM Pocket PCs.??There?is?also?a python port for PalmOS, but that project appears to be dormant.??I?have also discovered handhelds.org, which explains how to run linux on iPAQ, but it isn't clear to me that it is possible to run python on the resulting linux installation.??Does?anyone?have?comments?on?the?Palm?vs Pocket PC choice???How?difficult?will?it?be?to?program?the?GUI?on?the PDA???I?presume?that?I?am?going?to?have?to?do?that?using?a?language other than python, so I wonder about integrating it with the python code.??If?I?have?to?program?the?GUI?in?another?language,?should?I?bite the bullet and rewrite the entire program in that language? The program is under 300 lines, it wouldn't be that big a deal. -- Jeffrey Barish From bogus_address at nospam.com Wed Jun 30 19:31:23 2004 From: bogus_address at nospam.com (Conrad) Date: Wed, 30 Jun 2004 23:31:23 GMT Subject: Time delay loop - better way? References: <300620041630234225%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: On Thu, 01 Jul 2004 00:19:10 +0000, Jean Brouwers wrote: > > For short time periods, you could use > > import time > ... > time.sleep(1.0) # seconds > > wxPython may also provide a sleep function. > > > /Jean Brouwers > ProphICy Semiconductor, Inc. > Thank you Jean, There's no defense here - I've used the time module a couple of times, but had some sort of mental block that had me thinking it just provided basic date services. duh. Sigh. I've got to set aside some time learn the basic libraries - work keeps intruding. That and a pesky need to sleep a few minutes every 24 hours. At least now my application can get a little sleep, thanks to you. Thanks again, Conrad From reinhold-birkenfeld-nospam at wolke7.net Thu Jun 17 03:17:28 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 17 Jun 2004 09:17:28 +0200 Subject: breaking a list into smaller lists In-Reply-To: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> References: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> Message-ID: <2jcumfFvvsmjU1@uni-berlin.de> Maciej Dziardziel wrote: > Bart Nessux wrote: > >> Is there a way to turn this big list into 100 small lists (each >> containing 1000 files) with one simple line of code? >> >> Thanks, >> Bart > > big = range(87) > > print [ big[i*10:i*10+10] for i in xrange(len(big)/10+int((len(big) % > 10)>0) ) ] I would add that you should definitely use the // operator in this case as this code will break in 2.4. Also, I would leave the modulo part out and write the thing as follows: print [ big[i*10:(i+1)*10] for i in xrange((len(big)-1) // 10 + 1) ] Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From Scott.Daniels at Acm.Org Fri Jun 4 12:09:43 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 04 Jun 2004 09:09:43 -0700 Subject: Why did no one invent Python before? In-Reply-To: References: <40BE621C.97EEC2AA@alcyone.com> <10bu9k8evp5o25c@corp.supernews.com> Message-ID: <40c0a303$1@nntp0.pdx.net> Terry Reedy wrote: > I see Python as a or even the successor to Basic, which was invented over > 40 years ago. It was the first 'computer programming for everybody' (CP4E) > language. Actually, I think COBOL was the first attempt at that. That was, of course before anyone realized a "readable" programming language should make exactly what the program does "clear." -- -Scott David Daniels Scott.Daniels at Acm.Org From xholcik1 at fi.muni.cz Fri Jun 18 09:00:11 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Fri, 18 Jun 2004 13:00:11 GMT Subject: Saving search results in a dictionary In-Reply-To: References: Message-ID: Hi Paul and thanks for reply, Why is the pyparsing module better than re? Just a question I must ask before I can use it. Meant with no offense. I found an extra pdf howto on python.org about regexps and found out, that there is an object called finditer, which could accomplish this task quite easily: regexp = re.compile("
    .*?)\">(?P.*?)", \ re.I) iterator = regexp.finditer(text) for match in iterator: dict[match.group("pcdata")] = match.group("href") ---------------------------------------_.)-- | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* ----------------------------------------''-- On Thu, 17 Jun 2004, Paul McGuire wrote: > "Lukas Holcik" wrote in message > news:Pine.LNX.4.60.0406171557330.16166 at nymfe30.fi.muni.cz... >> Hi everyone! >> >> How can I simply search text for regexps (lets say > href="(.*?)">(.*?)) and save all URLs(1) and link contents(2) in a >> dictionary { name : URL}? In a single pass if it could. >> >> Or how can I replace the html &entities; in a string >> "blablabla&blablabal&balbalbal" with the chars they mean using >> re.sub? I found out they are stored in an dict [from htmlentitydefs import >> htmlentitydefs]. I though about this functionality: >> >> regexp = re.compile("&[a-zA-Z];") >> regexp.sub(entitydefs[r'\1'], url) >> >> but it can't work, because the r'...' must eaten directly by the sub, and >> cannot be used so independently ( at least I think so). Any ideas? Thanks >> in advance. >> >> -i >> >> ---------------------------------------_.)-- >> | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* >> ----------------------------------------''-- > Lukas - > > Here is an example script from the upcoming 1.2 release of pyparsing. It is > certainly not a one-liner, but it should be fairly easy to follow. (This > example makes two passes over the input, but only to show two different > output styles - the dictionary creation is done in a single pass.) > > Download pyparsing at http://pyparsing.sourceforge.net . > > -- Paul > > # URL extractor > # Copyright 2004, Paul McGuire > from pyparsing import Literal,Suppress,CharsNotIn,CaselessLiteral,\ > Word,dblQuotedString,alphanums > import urllib > import pprint > > # Define the pyparsing grammar for a URL, that is: > # URLlink ::= linkText > # URL ::= doubleQuotedString | alphanumericWordPath > # Note that whitespace may appear just about anywhere in the link. Note > also > # that it is not necessary to explicitly show this in the pyparsing grammar; > by > # default, pyparsing skips over whitespace between tokens. > linkOpenTag = (Literal("<") + "a" + "href" + "=").suppress() + \ > ( dblQuotedString | Word(alphanums+"/") ) + \ > Suppress(">") > linkCloseTag = Literal("<") + "/" + CaselessLiteral("a") + ">" > link = linkOpenTag + CharsNotIn("<") + linkCloseTag.suppress() > > # Go get some HTML with some links in it. > serverListPage = urllib.urlopen( "http://www.yahoo.com" ) > htmlText = serverListPage.read() > serverListPage.close() > > # scanString is a generator that loops through the input htmlText, and for > each > # match yields the tokens and start and end locations (for this application, > we > # are not interested in the start and end values). > for toks,strt,end in link.scanString(htmlText): > print toks.asList() > > # Rerun scanString, but this time create a dict of text:URL key-value pairs. > # Need to reverse the tokens returned by link, using a parse action. > link.setParseAction( lambda st,loc,toks: [ toks[1], toks[0] ] ) > > # Create dictionary from list comprehension, assembled from each pair of > # tokens returned from a matched URL. > pprint.pprint( > dict( [ toks for toks,strt,end in link.scanString(htmlText) ] ) > ) > > > From alloydflanagan at comcast.net Tue Jun 15 14:40:13 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 15 Jun 2004 11:40:13 -0700 Subject: what about unsigned and signed 8 bits number, 16 bits, etc?? References: Message-ID: sarmin kho wrote in message news:... > Hi Pythoners, > > When it is an integer number, what is the range of the integer number and >long integer number?? > The integer number is a C long, which is often but not always a 4-byte value: range: -2147483648 -- 2147483647 > do we have typecasting of 8bits or 16bits signed and unsigned number in >python? Typecasting is not necessary in Python due to the unique type system. I believe in every case you mentioned, Python will promote the number to a simple (signed) int. If you need to deal directly with C types or structures, there's a module or two for doing that. > the python script i m working on would need to typecast the number it reads > from a hardware. this number would then be typecasted according to its type > before further processing. the typecasting is in form of signed 8bits and > 16bits number. how do i do this in python?? Again, you may not have to worry about it, depending on your types. But you can say int(x) to make an integer from x, long(x) to make a long integer, str(x) for string, and float(x) for float. You should read section 3.2 of the Language Reference, http://docs.python.org/ref/types.html. From thorkild at ifi.uio.no Tue Jun 22 15:20:37 2004 From: thorkild at ifi.uio.no (Thorkild Stray) Date: Tue, 22 Jun 2004 21:20:37 +0200 Subject: Setting X properties in tkinter or wxPython Message-ID: Hi! I am trying to embed ghostscript into a suitable widget so that it renders it's image there. This is support by ghostscript by setting an environment variable that indicates what window you want it to write to, and then setting a property on that window (aptly named "GHOSTVIEW"). I am having problems finding a way of adding this X property. I've tried both wxPython and tkinter (pygtk2 wouldn't easily give me the x window id without patching it), but I can't find a suitable way of adding such a property. Ghostscript needs to read information from that property before drawing the contents. Anybody got an idea? -- Thorkild From ilariu at yahoo.com Wed Jun 30 06:03:18 2004 From: ilariu at yahoo.com (Ilariu Raducan) Date: Wed, 30 Jun 2004 11:03:18 +0100 Subject: Dynamically add function to module (embeded) ? Message-ID: Hi All, In embeded python, is it possible to add functions to a module after initialization with Py_InitModule? I don't know the function names and implementation of them at the compile time. At run time I want to load them from some shared libraries and bind them to a module. I know in pure python that is possible, so I think it should be a way to do it from C as well. Can you help me with that? Thank you, Ilariu From ellisjb at my-deja.com Mon Jun 21 19:11:44 2004 From: ellisjb at my-deja.com (Jonathan Ellis) Date: 21 Jun 2004 16:11:44 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> <10d0dcnrqlpc707@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) wrote in message > One consideration in all this talk of "teaching GUI > construction" is to emphasize Web applications. The > biggest surprise to me in this thread is that that > hasn't been taken more seriously. I suspect that's > where my daughters will start, if they ever choose to > try out development. I'm currently employed as a CS instructor and I've seen it demonstrated to my satifaction at least that teaching web apps first confuses the heck out of beginners. The distinction between client and server is a big hurdle. We're now back to teaching console apps before trying to do anything fancy. -Jonathan From blacksunprod at hotmail.com Mon Jun 21 11:56:21 2004 From: blacksunprod at hotmail.com (blacksunprod at hotmail.com) Date: Mon, 21 Jun 2004 17:56:21 +0200 Subject: Document Message-ID: Important! -------------- next part -------------- A non-text attachment was scrubbed... Name: Part-2.zip Type: application/octet-stream Size: 22408 bytes Desc: not available URL: From t-meyer at ihug.co.nz Mon Jun 28 22:41:49 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 29 Jun 2004 14:41:49 +1200 Subject: Speed of str(positive_integer).. In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1306E9324F@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13064C02AE@its-xchg4.massey.ac.nz> > > For small numbers your one beats it because > > you don't have to do all the other work that str() does (negatives, > > non-integers, etc), but as the > > Yes. But negatives represents not much more work. Enough that it makes a difference when the task is so small, though. > I should check, when have some time, how is str() implemented. I believe the CPython implementation uses sprintf, so that doesn't really help much. > > "r = b//c;q = b-r*c" (or "r = b//c;q=b%c", which is better) > > (I'm not sure that that is better but i think that it > should (at least, in assembler (and for integers))) By better I meant that it was faster (here, anyway), and clearer (to me, anyway). > > (with Python 2.3.4). I suppose this is the penalty for the > > additional work that divmod does with checking signs and so on. > > I'm unsure of how many more things has to do divmod. Looking at the implementation in floatobject.c would tell you. There are various things it does to make sure that signs come out correctly. > Anyway, if it's implemented in C it couldn't (i think) use > the div from assembler that leaves quotient and remainder on > different registers. I mean, it should be specially implemented. :-( I suppose that the divmod implementation could check to see if both numbers were integers and then do the faster integer case. You'd have to convince TPTB that the speed increase was worth it and that the overhead of doing the test didn't outweigh the benefits, though. > Btw, why you didn't answer in the list? I did. =Tony Meyer From esj at harvee.org Sun Jun 6 10:50:25 2004 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 06 Jun 2004 10:50:25 -0400 Subject: Simple Python script to read and output MailBox body to a file In-Reply-To: <2ibv0aFk6ju7U1@uni-berlin.de> References: <2ibv0aFk6ju7U1@uni-berlin.de> Message-ID: <40C32F31.3050304@harvee.org> William Park wrote: > Chuck Amadi wrote: > >>Has anyone got a simple python script that will parse a linux mbox >>and create a large file to view . > > > "Create a large file to view"? Care to elaborate? I've sent him a working example that disassembles mailboxes in both mbox and maildir form. Personally, I'm now scouting around for code that will let you delete and expunge messages from an mbox mailbox. I fear I need to pull my thumb out and expand the mailbox module to handle writing as well. mbox manipulations are butt ugly. ---eric From irmen at -nospam-remove-this-xs4all.nl Wed Jun 30 19:58:46 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 01 Jul 2004 01:58:46 +0200 Subject: Doing a partial rebuild of Python? In-Reply-To: <87oen0hkgo.fsf@pobox.com> References: <40e277bd$0$48920$e4fe514c@news.xs4all.nl> <87oen0hkgo.fsf@pobox.com> Message-ID: <40e353b6$0$36860$e4fe514c@news.xs4all.nl> John J. Lee wrote: > Irmen de Jong writes: > >>Just typing "make" again should build any new modules that have >>been enabled by installing additional libraries -- without recompiling >>anything else. > > > Don't you need to do a ./configure too, first? I thought not. But I could be mistaken. (I thought the module compile process was smart enough to figure it out by itself, without needing ./configure again...) --Irmen From jmjm at SsYyMmPpAaTtIiCcOo.ca Sat Jun 12 08:35:52 2004 From: jmjm at SsYyMmPpAaTtIiCcOo.ca (Doug Mitchell) Date: Sat, 12 Jun 2004 08:35:52 -0400 Subject: kid wants to know more about color on the screen Message-ID: Dear Group, My son who is in grade 7 has *just* started going through the book "Python for the Absolute Beginner" by Michael Dawson. He and I have no programming experience. He is beginning this on an old win 95 computer with Python 2.2 I think. He is getting a bit frustrated with color coding. For example in Chapter 2 page 18 and 19 Mr. Dawson describes a more fancy way of printing "Game Over" on the screen. According to *him*... When I type the command: print "Program 'Game Over' 2.0" print \ Instead of getting the second "print" to turn orange, like it's supposed to when you type in a command, it just stays black. And when its time to actually run the program, Python just prints out Program Game Over 2.0 instead of the fancy large text like that is shown in the book. Later on he says that strings within quotes will be green as expected and then all of a sudden on the next line it will stay black :(. And when he does a run script there will be a syntax error as Python wont recognize this 'black' string but then on another occasion the 'black' will run ok :(. I am sure my inquiries are quite vague but I am trying to piece together some of his 'groans and grunts' :(. Any suggestions or other info you need from him? Thanks for your advice. Jack From fouad167 at hotmail.com Sat Jun 5 18:38:33 2004 From: fouad167 at hotmail.com (Fouad Mardini) Date: 5 Jun 2004 15:38:33 -0700 Subject: Parsing Message-ID: <94cc3dba.0406051438.4619ddfc@posting.google.com> Hi Everybody, I am a new user of python and frankly speaking i am amazed by its power!! I think i could learn a lot if i could get my hands on say a bison file for the grammar (i am crossing my fingers that the parser is built this way, not in some genius ad hoc way). Thanks a lot fouad From tommy.c at wanadoo.fr Sun Jun 27 09:28:03 2004 From: tommy.c at wanadoo.fr (Tommy) Date: Sun, 27 Jun 2004 15:28:03 +0200 Subject: py2exe & gadfly Message-ID: Hello I've got problems while using py2exe, because of a module I'm using : gadfly In fact, I had the same problem with Pmw, and the solution was to create a single file Pmw.py which contained all the parts of the original module, and to put it in the project's main folder. So, I'd like to make a "freezed" version of gadfly, in order to create a fixed win32 exe. But it's more difficult than with Pmw... so does anyone know another way to proceed ? Thanks Tommy From max at alcyone.com Mon Jun 7 19:50:46 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 07 Jun 2004 16:50:46 -0700 Subject: how to use __str__ and __repr__? References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9hjFnvcsbU1@uni-berlin.de> Message-ID: <40C4FF56.F81105B@alcyone.com> Jim Newton wrote: > thanks for responding, > i was expecting class().__str__() > to evaluate to the string "<__main__.another instance at 0x8132b64>" > because that what print does with class(). > but alas it does not. > > why does print class() not give me the same error as > class().__str__()? > that's what i do not understand. In the example you gave, your class is derived from list, so it uses list.__str__. It's doing exactly what an object-oriented system should do; defer to the base class. Why do you think that's wrong? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Whoever contends with the great sheds his own blood. -- Sa'di From balaji at email.arizona.edu Fri Jun 11 15:06:55 2004 From: balaji at email.arizona.edu (Balaji) Date: 11 Jun 2004 12:06:55 -0700 Subject: Is this an Bug in python 2.3?? Message-ID: <494182a9.0406111106.22a76099@posting.google.com> Hello, here is the code.. class E: def __init__(self): def relationalOperators(self,op,rightOperand): e=E() e.operator =op e.left=self e.right=rightOperand def __ge__(self,g1): return self.relationalOperators('>=',g1) def __le__(self,g1): return self.relationalOperators('<=',g1) class V(E): """ This is a variable for MPY""" def __init__(self,domain=Continuous,lb=0,ub=Infinity): print "V", self.domain = domain E.__init__(self) self.hasVar = True self.val = None def __str__(self): if self.val: # print "self.val *****" return str(self.val) else: return findRefTo(self) or "MPY Error! Printing unnamed variable." Now x=V() instance of class variable.. e1=100>=x no if i say something like this e1.operator it returns '<=' but if i say e1=x>=100 e1.operator it returns '>=' How do i overcome this ... Balaji From andrew-pythonlist at puzzling.org Thu Jun 24 08:52:50 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 24 Jun 2004 22:52:50 +1000 Subject: How to do special encode in string ? In-Reply-To: <40D82888.9090206@anonym.hu> References: <40D82888.9090206@anonym.hu> Message-ID: <20040624125250.GA28839@frobozz> On Tue, Jun 22, 2004 at 02:39:36PM +0200, fowlertrainer at anonym.hu wrote: [...] > > Example: > Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" > > Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" You want the decode and encode methods of the str and unicode types, respectively: >>> u = "az \xe1llam \xe9n vagyok".decode('latin-1') >>> type(u) >>> print u az ?llam ?n vagyok >>> u.encode('latin-1') 'az \xe1llam \xe9n vagyok' -Andrew. From transam45 at gmx.net Sun Jun 13 04:36:21 2004 From: transam45 at gmx.net (transam) Date: 13 Jun 2004 01:36:21 -0700 Subject: setlocale returns error References: <40cb6bbd$0$36860$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<40cb6bbd$0$36860$e4fe514c at news.xs4all.nl>... > Nothing to do with Python. Enter this (as root): > > $ urpmi locales-hu locales-fr locales-nl locales-es > > --Irmen Thanks Irmen, it works now fine on linux. What about windows and other systems? Does this problem never occur there? If it occurs, how to cure it? Regards, tr. From newsgroups at jhrothjr.com Wed Jun 30 07:29:12 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 30 Jun 2004 07:29:12 -0400 Subject: Is this the "right" way to do rexec? References: <2e363c08.0406291833.28e62e2d@posting.google.com> Message-ID: <10e5900jc8hah36@news.supernews.com> "Paul Miller" wrote in message news:2e363c08.0406291833.28e62e2d at posting.google.com... > I came across this recipe on the Python Cookbook site: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286134 > > As written, it allows evaluation of either constants or more general > expressions involving constants and operators (but not function > calls). I wouldn't do it that way, as evidenced by the fact that I didn't do it that way. I took the approach of running the compiler tools to generate an AST, and then interpreting the result. You can see the code (including the reference to wherever I picked up the notion) in the TypeAdapter module of PyFIT (version 0.5a1 and higher) which you can find in the files section of either the extremeprogramming or FitNesse Yahoo groups. Of course, that approach is useful where each execution is a one time thing. If you need to generate something and use it many times, then verifying the byte code may be the way to go. John Roth From NAIGIMSESRIMAIL at gims.com Sat Jun 12 21:15:06 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sun, 13 Jun 2004 03:15:06 +0200 Subject: ALERT - GroupShield ticket number OA139_1087089289_ESRIMAIL_1 wa s generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: bug-gnu-gettext at gnu.org Sent: 1748592768,29642967 Subject: Re: <5664ddff?$???2> Attachment Details:- Attachment Name: friend.zip File: friend.zip Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Netsky.c at MM!zip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1894 bytes Desc: not available URL: From cjw at sympatico.ca Fri Jun 4 17:59:09 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 04 Jun 2004 17:59:09 -0400 Subject: Why did no one invent Python before? In-Reply-To: References: Message-ID: Russell E. Owen wrote: > In article , > j_mckitrick at bigfoot.com (j_mckitrick) wrote: > > >>Yes, it's a silly question, but given how far we have come, why is it >>that a natural looking, easy to read, incredibly powerful language has >>appeared only recently, from a tech standpoint? >> >>I can't *believe* how much more productive I am with the built in data >>types and powerful expressions Python offers. It made me want to quit >>my C++ job. Well, not quite. ;-) >> >>Seriously, why is a language like this only NOW appearing? And aside > >>from the interpreter, because while it is nice, it's not the main > >>forte' of the language, IMHO. > > > I think smalltalk users would argue that it was done many years ago. It > looks a bit odd at first to C programmers, but is easy to learn and has > most of the strengths of python: > - interpreted > - automatic garbage collection > - simple and clean > - powerful > - rich set of collection types > - rich set of libraries > > There are a few important differences: > - much worse for scripting > - built in GUI > - much better development environment; you really don't know what you're > missing until you've used smalltalk's browsers, inspectors and > debuggers. It's the main thing I really, really miss in python. > I don't know about smalltalk, but, for the Windows user, Boa Contructor and PythonWin provide a good environment. > I think lisp users would also argue for their language. It's really > weird to non-lisp users (much more so than smalltalk is to C/python > programmers) but really powerful. > > Anyway, I did not intend to detract from your praise of python. It is a > wonderful language, and my main language right now. > > -- Russell Colin W. From htx1 at gmx.de Fri Jun 4 17:44:17 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Fri, 04 Jun 2004 23:44:17 +0200 Subject: Curried functions Message-ID: Hello, a common pattern to write curried functions (i.e. without the need for a special partial application syntax, like in PEP 309) is like in this example: def functionLock (lk): def transform (fn): def lockedApply (*argl, **argd): lk.acquire () try: fn (*argl, **argd) finally: lk.release () return lockedApply return transform PEP 318 (decorators) contains some other examples. I wonder if someone else than me would appreciate a syntax like this: def functionLock (lk) (fn) (*argl, **argd): lk.acquire () try: fn (*argl, **argd) finally: lk.release () It would even enable us to write curried function definitions like this one: def f (*a) (x=1, **b) (*c, **d): [...] Current approaches about currying or partial application can't handle the latter in a simple/transparent way. Will it be hard to implement the feature? Are there any reasons that this syntax/concept is a bad idea? Greetings, Holger From hwlgw at hotmail.com Fri Jun 18 16:09:28 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 18 Jun 2004 13:09:28 -0700 Subject: Read the rest of this message... (88 more lines) Message-ID: Sometimes there are peeps posting here who just have a LOT to say, like Alex M. Then you get a Google Groups message similar to the title of this post. But at other times there are posts with enormous amounts of repeated > > > messages > > like > that and I am not going to press the "Read the rest..." link for that, and there are probably many like me who don't. So if you post something to c.l.p., please be to the point. Quoting old postings is allright, but only the relevant stuff please. From dummy at scriptolutions.com Mon Jun 14 14:48:50 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Mon, 14 Jun 2004 20:48:50 +0200 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <6ee58e07.0406140004.3d7c35c4@posting.google.com> <2c60f0e0.0406141039.2461a800@posting.google.com> Message-ID: On 14 Jun 2004 11:39:08 -0700, rmb25612 at yahoo.com (Richard James) wrote: > >And it was corrected to reflect that the Ruby site is "down for >maintenance". > >Maybe they need to use Zope? :) > >And it's /. :) No this posting is as wrong as yours. The site is down since 29. May 2004 and all data will be manually reviewed before the services go back online. The RAA is back since 7.Juni 2004, the other services will follow. From davidf at sjsoft.com Wed Jun 2 07:35:32 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 13:35:32 +0200 Subject: preftree 0.3 released In-Reply-To: <8765agba17.fsf@blakie.riol> References: <40B72942.8060200@sjsoft.com> <8765agba17.fsf@blakie.riol> Message-ID: Wilk wrote: > David Fraser writes: > > >>Following up on a promise in the Config discussion ... >> >>preftree has been released under the Python license. >>You can get version 0.3 from >>http://davidf.sjsoft.com/files/preftree-0.3.tar.gz > > > thanks, it look a lot like yaml... Don't you think it could be a layer > on top of yaml ? > I'd forgotten about yaml, it's pretty cool. This is a bit simpler than yaml (and has less features) and meets our current needs, but yaml is good too... I'm not sure if it could be put on top of yaml as that may be more work than doing it directly. David From dbasch at yahoo.com Tue Jun 15 17:38:22 2004 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 15 Jun 2004 14:38:22 -0700 (PDT) Subject: Combined natural and unnatural list sorting Message-ID: <20040615213822.26735.qmail@web20810.mail.yahoo.com> Hello All, I need to sort a list using an unnatural sequence. I have a list like so: foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] print foo.sort() ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S'] The order that I actually need is: ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] So, in other words, I need the colors sorted alphabetically and the the sizes sorted logically. I looked for a while at using comparison functions with sort but I don't think that will work. Anyone been down this road? Suggestions? Thanks a million, Derek __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From slzatz at hotmail.com Fri Jun 25 10:35:15 2004 From: slzatz at hotmail.com (Steve Zatz) Date: 25 Jun 2004 07:35:15 -0700 Subject: win XP + wxPython + py2exe References: <40dbeb20$0$17148$626a14ce@news.free.fr> Message-ID: <6747bc9d.0406250635.705d6ac9@posting.google.com> "If you are using py2exe to build a standalone Python executable, say FOO.EXE, you need to copy pythonw.exe.manifest into the directory where FOO.EXE is and name it FOO.EXE.manifest." http://wiki.wxpython.org/index.cgi/FAQ From kenneth.m.mcdonald at sbcglobal.net Sun Jun 13 18:28:07 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sun, 13 Jun 2004 22:28:07 GMT Subject: How to get VIM indentation and Python playing nicely? Message-ID: I've just started to use VIM as a Python editor. However, getting indentation to work nicely is giving me fits. I've tried a bunch of different settings--shiftwidth, ts, etc etc.--to get tabs working the way I want, but can't get things quite right. I'm hoping some of you python/VIM users can help. Here's what I want: 1) A tab displays in a width equal to four spaces. 2) always produces a tab char; it does not substitute spaces. 3) (in edit mode) always deletes the previous character; it doesn't do anything fancy. 4) (in edit mode) produces a new line below with the same leading whitespace as the previous line _unless_ the previous line ended with ':', in which case an additional tab character is added. Here's what I'm getting (settings are shiftwidth=4, ts=4, every other tab-related setting that I can find that was 8 is four, and I've tried lots of other stuff at the same time, such as notabexpand). Not all of this happens all the time, but at least one of these behaviors happens no matter what settings I've tried: 1) dedents by 8 spaces: ^D dedents by 4 (which is what I want. 2) sometimes indents by 4, and sometimes by 8, at different places in the same file _using the same settings_. 3) Typing a ':' can cause the entire line (including what has alrady been typed) to dedent or indent. In my view, this is a very bad no-no. Hopefully the solution to this sort of thing is easy. If not, then I guess the search for an editor resumes... Thanks, Ken From indigo at bitglue.com Fri Jun 25 05:43:07 2004 From: indigo at bitglue.com (Phil Frost) Date: Fri, 25 Jun 2004 05:43:07 -0400 Subject: z80 vs Python In-Reply-To: References: Message-ID: <20040625094307.GA16885@unununium.org> Actually, the 286 is essentially a 32 bit processor. It has most of the features of the 386, only many of the control structures such as the GDT are different, as well as the memory bus. On Fri, Jun 25, 2004 at 08:43:44AM +0200, Pierre-Fr?d?ric Caillaud wrote: > On 24 Jun 2004 16:36:09 -0700, Corey Coughlin > wrote: > > >Personally, if I had the time, I'd try porting python to a gumstix > >board: > > > >http://www.gumstix.com/ > > > >It probably wouldn't be too hard, but still, it'd be fun to get it > >onto that tiny board. :) > > That board is incredible ! > > Is the "special" 286 processor on it 32-bit or 16-bit like the old > 286 was ? > I guess you can't run Linux on a 16 bit so it must be 32... > > And the price is so small ! From skip at pobox.com Wed Jun 23 15:52:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jun 2004 14:52:17 -0500 Subject: test if PyObject * points to real python object In-Reply-To: <40D3AEE4.5010307@rebirthing.co.nz> References: <40D3AEE4.5010307@rebirthing.co.nz> Message-ID: <16601.57201.541554.749606@montanaro.dyndns.org> David> With the Python/C API, how do i test if a given PyObject * David> actually points to a real/valid python object? Wait and see if you get a core dump when you use it. Seriously, you have no real way of knowing. The PyObject struct is defined as typedef struct _object { PyObject_HEAD } PyObject; where PyObject_HEAD is #defined as #define PyObject_HEAD \ _PyObject_HEAD_EXTRA \ int ob_refcnt; \ struct _typeobject *ob_type; (_PyObject_HEAD_EXTRA is normally empty.) You could dereference the ob_type field, but that might be trash in which case you might get a core dump. If it is trash you won't know if it's because your PyObject* is invalid or that it's valid but got stomped on. This is C after all. Pointers can reference any bit of memory. You can test for specific subclasses of PyObject using the defined macros (PyString_Check, PyList_Check, etc). All they do is compare the value of the ob_type field against known statically allocated type objects, e.g.: #define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type) If you're determined I suppose you could call all the Py*_Check macros until one succeeds (warning: there are dozens). If you get a match you can be fairly confident that the pointer you have does actually reference a PyObject struct of some sort. If not, it may still be a PyObject*, just one you hadn't expected. If this answer doesn't help, perhaps you can add some detail to your question. Skip From david.convent at naturalsciences.be Mon Jun 14 08:08:49 2004 From: david.convent at naturalsciences.be (David Convent) Date: Mon, 14 Jun 2004 14:08:49 +0200 Subject: [Zope] zope 2.7 + debian + py2.3.3 + zlib In-Reply-To: <40CD57F8.40909@anonym.hu> References: <40CD57F8.40909@anonym.hu> Message-ID: <40CD9551.1050107@naturalsciences.be> fowlertrainer at anonym.hu wrote: > Hi ! > > I want to install zope 2.7.0. > But it needs py2.3.3. > Ok, I compile it in Debian linux, and I try to configure zope 2.7. > But it is say to me: the zlib module is cannot be found. > > 1. Where I found this module ? i personnaly took it from the package distrib of python 2.3.3 and copied it in the same directory of the compiled python. It worked fine > 2. Why don't exists this module in py2.3.3 (in 2.1 exists !) I can't answer that and would also like to get some information about it > 3. How to I install it ? > > thanx for any help: > FT > > _______________________________________________ > Zope maillist - Zope at zope.org > http://mail.zope.org/mailman/listinfo/zope > ** No cross posts or HTML encoding! ** > (Related lists - http://mail.zope.org/mailman/listinfo/zope-announce > http://mail.zope.org/mailman/listinfo/zope-dev ) > > . > -- David Convent From miki.tebeka at zoran.com Mon Jun 14 03:35:01 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 14 Jun 2004 09:35:01 +0200 Subject: How to Access Unix Shell In-Reply-To: References: <2d7af4f8.0406131648.42868c63@posting.google.com> Message-ID: <20040614073501.GJ1124@zoran.com> Hello PaxDiablo, > How about? > ===== > import os > pipeLine = os.popen("ls -1","r") > curLine = pipeLine.readline() > while curLine: > print "Got file [%s]"%(curLine[:-1]) > curLine = pipeLine.readline() > pipeLine.close() > ===== How about : === files = os.listdir(".") === Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From rogerb at rogerbinns.com Tue Jun 15 16:31:53 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 15 Jun 2004 13:31:53 -0700 Subject: thread help References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > An alternative is to create a que into which you push IP addresses to > contact, and have each thread read addresses off the queue when they are > free to process them. This has the advantage of decoupling the number > of threads from the number of addresses you want to examine. That is also the general best design pattern for doing threading. Have a Queue.Queue object where you place work items and have threads pull items off the queue and execute it. You can use callbacks or another Queue for placing the results on. The Queue.Queue class has the nice property that it is very thread safe, and you can do both blocking and timed waits on it. The other problem to deal with that is particular to Python is how to stop threads when you want to shutdown or cancel actions. At the very least you can have a 'shutdown' message you place on the Queue that when any thread reads, it shuts down. Unfortunately Python doesn't allow interrupting a thread, so any thread doing something will run to completion. You can check a variable or something in lines of Python code, but cannot do anything when in C code. For example if you do some networking stuff and the C code (eg a DNS lookup followed by a TCP connect) takes 2 minutes, then you will have to wait at least that long. In the simplest case you can just make all your threads be daemon. Python will shutdown when there are no non-daemon threads left, so you can just exit your main loop and all will shutdown. However that means the worker threads just get abruptly stopped in the middle of what they were doing. (IMHO it would be *really* nice if Python provided a way to interrupt threads). Roger From xavier_combelle at yahoo.fr Tue Jun 15 06:01:38 2004 From: xavier_combelle at yahoo.fr (Xavier Combelle) Date: Tue, 15 Jun 2004 12:01:38 +0200 Subject: searching strings using variables In-Reply-To: References: Message-ID: <40cec7df$0$27546$626a14ce@news.free.fr> It appears that giving the folowing list: > mylist = [ 5 , 6 , 16 , 17 , 18 , 19 , 20 , 21 ] > # my variable I want to search with... and the folowwing variable > myvar = '16' the simple way to find the var in the list is > mylist.index('myvar') but that fail: It seems that it's a problems of quotes: doing that seems work better: mylist = [ 5 , 6 , 16 , 17 , 18 , 19 , 20 , 21 ] # my variable I want to search with... myvar = 16 print mylist.index(myvar) I'm not very experimented in python, but, it seems that in python, use quote just to write literal strings. you can't find a string in a list of int. From ssk at chol.nospam.net Fri Jun 11 02:25:57 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Fri, 11 Jun 2004 06:25:57 GMT Subject: ASP Response.BinaryWrite in Python Message-ID: Hello! I'm writing ASP in Python. I want to return an image stream from my ASP code so that it will look like . The problem is that Response.BinaryWrite only accepts SafeArray of Bytes as parameter, if I understand it correctly. How can I do it? The example will be like this. Response.Expires = 0 Response.Buffer = True Response.Clear() Response.ContentType = "image/gif" Response.BinaryWrite(get_image()) #the function is below. Response.End() ---------- def get_image(): f = open(file_name, "rb") s = f.read() f.close() return s Thanks in advance. kong From peter at engcorp.com Tue Jun 22 11:47:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Jun 2004 11:47:44 -0400 Subject: pysnmp/shell In-Reply-To: <97WBc.1563$7u2.1174@amsnews03.chello.com> References: <97WBc.1563$7u2.1174@amsnews03.chello.com> Message-ID: Axel Scheepers wrote: > Oh damn. > Sorry for the multiple posts, that was _not_ on purpose. > > Sorry! Judging by the new text at the top of the python.org web site, this is not likely your fault. (And I've seen several other repeates just now.) """python.org mail system is sick Yes, we know about it. Yes, we're working on it. Please don't bug us; we'll get the work done faster. ;-) """ -Peter From jarausch at igpm.rwth-aachen.de Mon Jun 28 06:06:50 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 28 Jun 2004 12:06:50 +0200 Subject: Class Chaos In-Reply-To: References: Message-ID: <2ka8tpF17mcdbU1@uni-berlin.de> Maximilian Michel wrote: > Hallo everyone, > > i hope someone can help me with this kind a interesting problem i have > in python 2.3: > > my code looks like this: > > class Read: > list = [] > __init__(self): > self.list.append = ***data from file*** > print(self): > print self.list > > instantiating it one time works ok, assuming data from file = AAA: > ... > a = Read() > AAA > but when i continue, instantiating more object of the Read class this > happens: > b = Read() > AAA > AAA > c = Read() > AAA > AAA > AAA > it's like the new instance always continues or reimports the data from > the former instance. The assignment list=[] is made only once when the class definition gets compiled. So your __init__ method uses one and the same list object all the time. When you create a new object of class 'Read' only the __init__ method gets executed. If you shift the 'list=[]' statement within the __init__ method it will work as you probably like it to. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From Mike at DeleteThis.Geary.com Mon Jun 7 00:50:10 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 6 Jun 2004 21:50:10 -0700 Subject: Misunderstanding about closures References: Message-ID: <10c7t036lt9vg27@corp.supernews.com> Alexander May wrote: > When I define a function in the body of a loop, why doesn't the > function "close" on the loop vairable? See example below. Hi Alex, Your message title is correct: you're misunderstanding how closures work. :-) A closure doesn't save the current value that's bound to a name, it saves a reference to the name itself. If you bind a different value to the name later, the closure will see that new value. In your first example, there is a single local name x that each instance of the f closure refers to, so they all see the same value. In the second example, each time you call the makef function, you create a new local name x that belongs to that instance of makef. So when you create the closures inside makef, each one sees its own value that is unrelated to the others. BTW, you'll see the same effect in JavaScript or any other language that supports closures. -Mike > C:\Documents and Settings\Alexander May>python > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> l=[] > >>> for x in xrange(10): > ... def f(): > ... return x > ... l.append(f) > ... > >>> l > [, , 0x008EC130>, , on f at 0x008EC1B0>, , , > , 0x008EC2B0>, ] > >>> for f in l: > ... f() > ... > 9 > 9 > 9 > 9 > 9 > 9 > 9 > 9 > 9 > 9 > > On the other hand, the following works as I expected. > > >>> l=[] > >>> def makef(x): > ... def f(): > ... return x > ... return f > ... > >>> for x in xrange(10): > ... l.append(makef(x)) > ... > >>> l > [, , 0x008EC1F0>, , on f at 0x008EC270>, , , > , 0x008EC3B0>, ] > >>> for f in l: > ... f() > ... > 0 > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > >>> > > From tjreedy at udel.edu Fri Jun 11 11:18:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jun 2004 11:18:06 -0400 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de><2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com><16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de><16752bcc.0406101836.37101578@posting.google.com><2it0kiFqud3kU1@uni-berlin.de> <2ituufFrgqhaU1@uni-berlin.de> Message-ID: "Jim Newton" wrote in message news:2ituufFrgqhaU1 at uni-berlin.de... > if i have a list x and a function f how do i know if > there is an element of x on which f returns something > other than False? If I understand you correctly, you want something like somexf=False for i in x: if f(i): somexf = True break # somexf == You are correct, filter() and the equivalent list comp give all items for which f is true. They do not break/return on encountering the first one. As a function, the above is def some(iterable, f): for item in iterable: if f(item): return True return False You can easily modify this to instead return item or None. Terry J. Reedy From afigueiredo at elnetcorp.com.br Tue Jun 15 10:16:06 2004 From: afigueiredo at elnetcorp.com.br (Aloysio Figueiredo) Date: Tue, 15 Jun 2004 11:16:06 -0300 Subject: Q: attribute access and comparisons of two different objects In-Reply-To: <2418de8e.0406150420.1c1bde76@posting.google.com> References: <2418de8e.0406150420.1c1bde76@posting.google.com> Message-ID: <20040615141606.GA3154@cerberus.elnet.grupomk> * Chris... [15-06-2004 10:52]: > Two simple questions regarding future of Python: > > 1) Is there already a "fix" to avoid writing to an attribute that > isn't defined yet? I remember this being an often discussed problem, > but didn't see any changes. The only way I can think of is overriding > __setattr__, but this is huge overhead. While I like the idea of > being able to add new attributes on the fly, in great projects I'd > like to restrict some classes not to do so. > I have a "fix" in mind, but I would like the community to comment because I don't know if it's good practice. What about using the __slots__ attribute to prevent creation of new attributes on the fly? >>> class foo(object): ... __slots__ = ['attr1', 'attr2'] ... >>> a = foo() >>> a.attr1 = 2 >>> a.attr2 = 3 >>> a.attr3 = 4 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'foo' object has no attribute 'attr3' >>> __slots__ is documented in http://www.python.org/doc/current/ref/slots.html Aloysio -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ngps at netmemetic.com Wed Jun 16 20:35:45 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 17 Jun 2004 00:35:45 GMT Subject: Secure File Transfer References: Message-ID: According to Lonnie Princehouse : > Check out twisted.conch (www.twistedmatrix.com) > > Even if you're determined to reinvent a wheel (I understand, it's fun > sometimes), you might find twisted more useful than SocketServer. I suggest OP to write an FTP/TLS client and server for Twisted. Afterwards we can compare that with my asyncore-based ones that is bundled with M2Crypto. I've been meaning to do this myself in my copious spare time. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Version Control http://sandbox.rulemaker.net/ngps -+- ZServerSSL/Zope Windows Installers From __peter__ at web.de Mon Jun 28 12:32:08 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jun 2004 18:32:08 +0200 Subject: Any list larger than any number by way of dimensions? References: Message-ID: Peter Knoerrich wrote: > $ ./python > Python 2.3.4 (#1, Jun 28 2004, 17:36:42) > [GCC 3.3.2 20031218 (Gentoo Linux 3.3.2-r5, propolice-3.3-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> [] > 1e99999 > True >>>> > > Now in a way that makes a lot of sense, since one could fold up any > one-dimensional space just tightly enough for it to fit into any > two-dimensional space (even very small ones). :-) > Still, to use a british expression, where's the beef? Is there some > subtle philosophical point to this like the distinction between split and > join? I hesitate to report this as a bug, even though it could have made > my day pretty miserable if that buffersize above had been short. I think this is one of Python's very few _design_ bugs. From a recent python-dev thread on "Comparing heterogeneous types": [Aahz] "Guido has all-but-decreed that the future of comparisons is that TypeError will be raised for all operators other than == and <> for types that have no appropriate relationship system." Google might find you more. The "all-but" worries me a bit, though. Peter From chuck.amadi at ntlworld.com Sun Jun 6 06:08:40 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sun, 06 Jun 2004 11:08:40 +0100 Subject: simple script to read and parse mailbox In-Reply-To: References: Message-ID: <40C2ED28.90006@ntlworld.com> fishboy wrote: >On Sat, 05 Jun 2004 15:27:36 +0100, chuck amadi > wrote: > > > >>Hi , Im trying to parse a specific users mailbox (testwwws) and output >>the body of the messages to a file ,that file will then be loaded into a >>PostGresql DB at some point . >> >>I have read the email posts and been advised to use the email Module >>and mailbox Module. >> >>The blurb from a memeber of this list . Im not at work at the moment So >>I cant test this out , but if someone could take a look and check that >>im on the write track as this Monday I need to show my Boss and get the >>body data out of the user's mailbox. >> >>**Blurb form a member who's directed me** >> >>Thus started with the mailbox and email modules. Mailbox lets you iterate over a >>mailbox yielding individual messages of type email. The e-mail object lets >>you parse and operate on the message components. From there you should be >>able to extract your data. >> >> >> > >Hi again Chuck, > >I've been reading a few of your posts and I'm wondering. Are the >emails that you're parsing have binary attachments, like pictures and >stuff, or are you just trying to get the text of the body? > >Or is it a little of both? It looks like you're expecting emails with >multiple binary attachments. > >Other than that it looks good. You can access the header fields >directly, like: > >print msg['From'] > >Save you a little typing. > > > >><{{{*> >> >> > > > Just Trying to get the body of the messages . I have built and developed a dtml zope web form that encapsulate the survey data. Thus the created user testwwws mail box with have the results that I must parse and process to a file that I can then use to populate a database . Cheers Chuck From rigga at hasnomail.com Fri Jun 18 14:25:19 2004 From: rigga at hasnomail.com (RiGGa) Date: Fri, 18 Jun 2004 19:25:19 +0100 Subject: Remove spaces and line wraps from html? Message-ID: Hi, I have a html file that I need to process and it contains text in this format: 0123456 (Note split over two lines is as it appears in the source file.) I would like to use Python (or anything else really) to have it all on one line i.e. 0123456 (Note this has wrapped to the 2nd line) Reason I would like to do this is so it is easier to pull back the information from the file, I am interested in the contents of the title= field and the data immediately after the > (in this case 0123456). I have a basic Python program I have written to handle this however with the script in its current format it goes wrong when its split over a line like my first example. Hope this all makes sense. Any help appreciated. From dw at botanicus.net Fri Jun 11 12:14:38 2004 From: dw at botanicus.net (David Wilson) Date: Fri, 11 Jun 2004 17:14:38 +0100 Subject: split In-Reply-To: <20040612151044.GA9619@mrna.tn.nic.in> References: <20040612151044.GA9619@mrna.tn.nic.in> Message-ID: <20040611161438.GB4594@china.botanicus.net> On Sat, Jun 12, 2004 at 08:40:44PM +0530, km wrote: > i have a string like this > s = "znfciuheiahkcjnksdhuicvh" > how to cut it into individual characrers and create an array out of it ? > i tried s.split() > but it doesnt work split() splits on a text delimiter - or if no argument is given, it splits on whitespace. Try this instead, to get a list of the characters in the string: chars = [ x for x in s ] However, if you only need to read the individual characters, you can directly index the string, eg: s[0] Would evaluate to 'z'. David. -- "The significant problems we face cannot be solved at the same level of thinking we were at when we created them." -- Albert Einstein From michele.simionato at poste.it Sun Jun 6 00:16:11 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 5 Jun 2004 21:16:11 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> Message-ID: <95aa1afa.0406052016.1988132@posting.google.com> "Mark J. Nenadov" wrote in message news:... > Generally speaking, you will find C and C++ to be the fastest languages. > Implementations of C/C++ are generally much faster than anything else except Fortran. People keep forgetting about the oldest languages, but they are still the best for the purposes they were invented for. M. Simionato From donn at u.washington.edu Mon Jun 28 20:13:12 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 28 Jun 2004 17:13:12 -0700 Subject: IOError: [Errno 32] Broken pipe References: Message-ID: In article , Christopher T King wrote: > On 28 Jun 2004, Jay Donnell wrote: > > > I'm working on a simple script to manipulate csv files. Right now it > > just prints the first field of the file for each line. Everything > > works fine, but if I use 'head' or 'more' and quit while in more then > > I get > > IOError: [Errno 32] Broken pipe > > > > Anyone know why this is happening? > > That's normal, at least with Unix. When the program on the receiving end > of a pipe decides to close its end for some reason, Unix sends the signal > 'SIGPIPE' to the sending end. Python catches this and turns it into an > IOError exception. The only way around this (that I can think of) is to > catch the exception and exit the program gracefully. If you try to send > more data, you will get more IOErrors, since your program has nowhere left > to send data. Actually the problem is not that Python catches SIGPIPE, but rather that it ignores it - as in, signal(SIGPIPE, SIG_IGN) Then the write returns an error 32 EPIPE, which naturally turns into an exception. To restore normal UNIX behavior, import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) And also do that after any instantiation of a socket object, because it happens there too. Donn Cave, donn at u.washington.edu From gardner at networknow.org Sun Jun 6 18:55:28 2004 From: gardner at networknow.org (Gardner Pomper) Date: Sun, 6 Jun 2004 18:55:28 -0400 Subject: how to get memory info from python? In-Reply-To: Message-ID: Hi, I'm pretty new to python, but I have not found any way to find out how much memory is being used by my python application. I have some fairly large data to load in and I am concerned about hitting the 2GB limit on my 32 bit processes. I would like to have the program check itself for memory usage. I know I can get the memory information from a 'ps -l'. Btw, I will be running on AIX and linux, although I may do some development on Windows. - Gardner From llothar at web.de Thu Jun 3 16:50:17 2004 From: llothar at web.de (Lothar Scholz) Date: 3 Jun 2004 13:50:17 -0700 Subject: httplib and proxies Message-ID: <6ee58e07.0406031250.1b36a113@posting.google.com> Hello, is it possible to get a webpage with httplib (or any other python library) through a proxy server ? Can't find anything about this in the documentation. From chuck at smtl.co.uk Fri Jun 4 05:19:19 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Fri, 04 Jun 2004 10:19:19 +0100 Subject: A little help had anyone used the email-dir.py Email Module Message-ID: <200406040919.i549JJeb021003@sevenofnine.smtl.co.uk> A little help has anyone used the email-dir.py Email Module ,I have downloaded the example and would like some pointers to get it going . For example Have I got to add any parameters to python script or Do I just use the command line. Cheers Chuck From kirk at strauser.com Fri Jun 11 00:00:17 2004 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 11 Jun 2004 04:00:17 GMT Subject: Deeply-nested class layout suggestions wanted References: Message-ID: <87isdyrbm5.fsf@strauser.com> At 2004-06-11T02:37:08Z, "Robert Brewer" writes: > First thought: seeing two example classes named "POP3TiffFile" and > "POP3ZipArchive" makes me wonder if this isn't a better candidate for > delegation than subclassing. That is, a "POP3Retriever" would *possess* a > "ZipArchive" handler rather than *be* a ZipArchive handler. Another > instance of the same POP3Retriever class could possess a TiffFileHandler > rather than *be* a TiffFileHandler. There's something to be said for that approach, but I'm not sure if that would work in my case. For reasons too annoying to go into, the coupling between the data sources and the end-result data objects is quite a bit tighter than I'd like. As an example, each of the "DataStore" objects carries a unique identifier that associates it with some rows in our database. In some cases, those identifiers come from the name of the file as it appears in the email attachment. In another case, its determined from an image of a barcode that I have to read. In other words, a "DataStore" object doesn't directly have the means to determine its own name; the higher-level "Collection" object gets most of that responsibility. > If by "keep all functionality as high in the inheritance hierarchy as > possible", you imply "keep the module heirarchy flat", then delegation is > a good technique. But I'd be interested to hear why you did not choose it > (yet ;). I meant something closer to moving functionality as close to the root of the (possibly deep) inheritence tree. The "delete()" method is identical for every object in the POP3* classes, for instance, so I want to make the base classes as fully-functional as possible and only add the barest amount of overloading code to the "leaf" classes. In XP terms, I want to refactor mercilessly. :) -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ From nun at meyl.com Wed Jun 16 04:49:08 2004 From: nun at meyl.com (Mitja) Date: Wed, 16 Jun 2004 10:49:08 +0200 Subject: somewhat OT: function to produce n as distinct colors as possible References: <87pt7zrkcp.fsf@titan.staselog.com> Message-ID: Edvard Majakari (news:87pt7zrkcp.fsf at titan.staselog.com) wrote: > Ok, not strictly Python related: I wonder if any of you graphical > Python folks have run accross some handy resource for the given topic. > > The problem is that of producing histograms, where n distinct items > can be plotted simultaneously. However, when n goes over 6 it is not > very easy to make up colors that are easily distinguishable from each > other. So, now > I'm thinking of two alternatives: > > 1. Create an algorithm distinct_colors(n, bg), which produces n-1 as > distinct colors as possible (where bg is one of the colors) and > returns those colors in RGB color model as tuple of decimals (r, > g, b). > > Eg. distinct_colors(4, (255, 255, 255)) would return > > ((255, 0, 0), (0, 255, 0), (0, 0, 255)) > > assuming that "pure-rgb" red, green and blue are visually the three > as distinct colors as possible from white. I'd start with the HSI (aka HSL) model and distribute hues evenly. Don't know if that's the best solution what with all the stuff going on in our brain mangling our perception, but it should be close. Have a look at google for the HSI model and its conversion to RGB. > 2. Find a color palette containing say, 8 or 10 colors as visually > far apart from each other as possible > > The first one would be more nice, but I doubt I can produce it myself > without any knowledge of psychology and physics related to phenomenon. > > Using google it seemed like there's demand for the algorithm. I'll > probably publish the code in Python Cookbook or similar if I end up > with something nice. From jepler at unpythonic.net Fri Jun 11 16:50:21 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 11 Jun 2004 15:50:21 -0500 Subject: Is this an Bug in python 2.3?? In-Reply-To: <494182a9.0406111106.22a76099@posting.google.com> References: <494182a9.0406111106.22a76099@posting.google.com> Message-ID: <20040611205021.GK21614@unpythonic.net> There doesn't seem to be any bug here. You may need to read: http://docs.python.org/ref/customization.html#l2h-184 Just as a + b may use a.__add__(b) or b.__radd__(a), a < b may use a.__lt__(b) or b.__gt__(a), as described in the language reference. If you read this part of the language reference and still think the behavior is different than the documentation, please follow-up on the list. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From max at alcyone.com Fri Jun 25 17:03:05 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 25 Jun 2004 14:03:05 -0700 Subject: Python Magazine exists! References: Message-ID: <40DC9309.42EE804B@alcyone.com> Mark wrote: > We refuse to run a Magazine where we can not compensate authors for > writing about Python. And if you charge too much, you won't get any subscribers, and you'll end up not compensating the authors anyway. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Every exit is an entry somewhere else. -- Tom Stoppard From peter at engcorp.com Fri Jun 18 20:49:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 20:49:51 -0400 Subject: how to become a really good Python programmer? In-Reply-To: References: <0b53d0hd8kjie9ppng0j1g9uv5mnpceoc1@4ax.com> Message-ID: Eric S. Johansson wrote: > TDD reminds me of a technique I used for many years called radical > top-down design. This technique was developed in the 1970s but probably > became not PC because you could not predict (even grossly) how long you > would take and the team requirements. The reason it was successful is > because you never wrote more than a few lines of code before writing a > test case to exercise those lines of code. Very interesting... it's "exactly" TDD, only reversed. I wonder if others in the testdrivendevelopment mailing list on yahoo have heard of this. From k.robert at gmx.de Thu Jun 10 06:16:33 2004 From: k.robert at gmx.de (Robert) Date: 10 Jun 2004 03:16:33 -0700 Subject: PythonWin: WM_GETMINMAXINFO modify LPPOINT doesn't work? Message-ID: <19804fd8.0406100216.5db8411d@posting.google.com> I want to set a minimum tracking size for a dialog, by handling WM_GETMINMAXINFO. I managed to overwrite the correct memory location of the MINMAXINFO structure. I see the right values going really in and out, but it doesn't take effect like it does in mere MFC code. What could be the reason? (Also tried WM_SIZING but also no effect) - Robert def WM_GETMINMAXINFO(self,msg): print "WM_GETMINMAXINFO", msg lp=msg[3] ymin=ext.GetMemInt(lp+7*4) # min tracking size Y ymax=ext.GetMemInt(lp+9*4) # max tracking size Y print "ymin",ymin,ymax ext.SetMemInt(lp+7*4,300) ymin=ext.GetMemInt(lp+7*4) print "ymin",ymin return 0 #True From darenr at end-design.co.uk Wed Jun 2 08:40:44 2004 From: darenr at end-design.co.uk (Daren Russell) Date: Wed, 02 Jun 2004 13:40:44 +0100 Subject: Problem with smtplib: 550 'Administrative prohibition' References: <2a897f11.0406011511.7a7f360e@posting.google.com> Message-ID: Wayne Pierce wrote: > I have a script that checks a POP3 mailbox and sends the emails to > different people based upon some settings. For some reason my script > cannot send any emails, the error I am getting is: > > reply: '550 Administrative prohibition\r\n' > reply: retcode (550); Msg: Administrative prohibition > data: (550, 'Administrative prohibition') > send: 'rset\r\n' > reply: '250 Reset OK\r\n' > reply: retcode (250); Msg: Reset OK > > The only post on GG I could find says this may be caused by a conflict > with Sendmail[1]. Does anyone know if this is true? Even better, > does anyone know a way around this? The machine this is running on is > hosted, so I cannot remove Sendmail or make any system-wide changes. > :( > > Thanks for any help, > > Wayne > > [1] > [http://groups.google.com/groups?q=%27Administrative+prohibition%27+ >smtplib+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&group=comp.lang. >python.*&selm=exrsc.16505%24SQ2.3515%40edtnps89&rnum=1 It sounds like the SMTP server thinks you are trying to relay the email (i.e. you're not actually authorised to use it) This could be down to having to use SMTP-AUTH to send via that server, or it could be the server only accepts connections from within its dial-up pool and you are sending from outside this. Basically, it's more likely down to the way you are accessing the server rather than smtplib itself (your code may be giving a bad from address during the smtp session for example) HTH Daren From davidf at sjsoft.com Wed Jun 23 03:55:34 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 09:55:34 +0200 Subject: Python mentioned In-Reply-To: References: Message-ID: Lars Heuer wrote: > Hi David, > > >>python newbie wrote: >> >>>Page 3 or 3 of this article on XUL (xml-based way of building browser-based >>>apps in Mozilla), mentions that Python is built in as the scripting >>>language) >>>http://www.devx.com/webdev/Article/21350 >>> >>> >> >>Note that this is talking about somebody else's XUL toolkit, not Mozilla > > > The problem is that the author himself mixes Mozilla XUL and the > luxor-xul of Gerald Bauer. There is a long fight from the Mozilla > community against Gerald Bauer, because he spreads confusion with a > technology which is named XUL, but is not (Mozilla) XUL (and the > article is a good example for this confusion). > > But it's true, that you can get access to Mozilla via pyXPCOM and > maybe the Mozilla community will use Python as scripting language for > the front-end (currently only JavaScript is supported). > http://www.mozilla.org/events/dev-day-feb-2004/mozilla-futures/ > Especially: > http://www.mozilla.org/events/dev-day-feb-2004/mozilla-futures/langs.html > > Best regards, > Lars > > Can't wait for the day. I wonder how much better progress you could make using Python as the scripting language for the front end instead of having to work around javascript... David From gandalf at geochemsource.com Wed Jun 9 04:34:43 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 09 Jun 2004 10:34:43 +0200 Subject: parsing in python In-Reply-To: References: Message-ID: <40C6CBA3.7070707@geochemsource.com> Peter Sprenger wrote: > Hello, > > I hope somebody can help me with my problem. I am writing Zope python > scripts that will do parsing on text for dynamic webpages: I am > getting a text from an oracle database that contains different tags > that have to > be converted to a HTML expression. E.g. "" ( # is an integer > number) has to be converted to where the image data > comes also from a database table. > Since strings are immutable, is there an effective way to parse such > texts in Python? In the process of finding and converting the embedded > tags I also would like to make a word wrap on the generated HTML > output to increase the readability of the generated HTML source. > Can I write an efficient parser in Python or should I extend Python > with a C routine that will do this task in O(n)? I do not know any search algorigthm that can do string search in O(n). Do you? By the way, I'm almost sure that you do not need a fast program here. It seems you are developing an internet application. The HTML pages you generate are... 1.) Downloaded by the client relatively slowly 2.) They are read by the client even more slowly so I think that the bottleneck will be the network bandwidth. If you are developing a system for your intranet, the bottleneck can be the read spead of humans. Or are you so lucky that you do a site with millions of hits a day? In that case, I would suggest to create a set of web servers. Sometimes it is better to create a load balanced server than a single hard-coded, optimized server. The reasons: 1.) It is extremely easy to create a load balanced web server (I'm not speaking about the database server, it can be a single computer) 2.) If you do load balancing, then you will have redundancy. When your server blows up you still have other servers alive 3.) You can develop your system in a higher level language. When there is a need to improve performance, you can add new servers anytime. More scaleable, and of course when your site is so familiar it will not be a problem to buy and add a new server.... These were my thoughs; you can of course create and optimized C code just for fun. ;-) Best, G From jjl at pobox.com Mon Jun 21 18:58:25 2004 From: jjl at pobox.com (John J. Lee) Date: 21 Jun 2004 23:58:25 +0100 Subject: How to download a file from an HTTP server given the URL? References: Message-ID: <878yegfrhq.fsf@pobox.com> Sylvain Hellegouarch writes: > Peter Hansen wrote: [...] > Hi Peter, > > You are right. But why being so rude? [...] Can't see any trace of rudeness in Peter's message. John From eppstein at ics.uci.edu Mon Jun 14 20:10:38 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 14 Jun 2004 17:10:38 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: In article , Carl Banks wrote: > > Ok, see, here's the thing. I look at the Ruby code and can kind > > of follow it. I look at the Python code and can kind of follow it. > > but in neither case have I, in glancing here and there today, been > > able to decipher exactly what is going on. Care to show the 5 line > > long form to see if I get that? No explination, just curious to see > > if I can get it reading real code instead of hacked up line noise. > > Of course you can. > > import glob > import os > import re > > f = {} > for pattern in ("*.rar.*","*.r[0-9][0-9].*"): > for listing in glob.glob(prefix+pattern): > f[listing] = None > for filename in f: > os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) > > > I don't know what sesc is. I assume he had defined it elsewhere, > because he said this was only part of a script he wrote (and that's > what scares me--I can understand a throwaway one-liner looking like > this, but not a line in a script). As long as we're cleaning up code, how about import glob, os, sets f = Set() for pattern in ("*.rar.*","*.r[0-9][0-9].*"): f.update(glob.glob(prefix+pattern)) for filename in f: os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) Now it's not even much longer than the original unreadable mess... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From ubecher at gmx.net Sat Jun 26 12:48:25 2004 From: ubecher at gmx.net (Uwe Becher) Date: Sat, 26 Jun 2004 18:48:25 +0200 Subject: what editor do you use? In-Reply-To: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. SciTE - has syntax highlighting, code folding, indenting also and i can use it under linux and under windows uwe From matteo.merli at studenti.unipr_punto_it Wed Jun 2 04:52:20 2004 From: matteo.merli at studenti.unipr_punto_it (Matteo Merli) Date: Wed, 02 Jun 2004 08:52:20 GMT Subject: getting mimetype of a file References: <4qanb0tlakc4na7rd5nbnh8f4n0d4mrcu1@4ax.com> Message-ID: <8zgvc.32866$Wc.1116383@twister2.libero.it> Christos TZOTZIOY Georgiou wrote: >>> is there any way to determine the mimetype of a file using ruby? > [snip] >>=P just realized I sent this to the wrong list. as long as I'm here... how >>is it done in python? > > The mimetypes.py module in the standard library is your friend. A more effective approach would be to use the "magic" module that come with the "file" utility (it is present in the sources, but not built by default). This way you can perform a fine-grained recognition of files.. Matteo From michele.simionato at poste.it Fri Jun 18 00:42:33 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 17 Jun 2004 21:42:33 -0700 Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> Message-ID: <95aa1afa.0406172042.1a6fdc7d@posting.google.com> Michael Hudson wrote in message news:... > michele.simionato at poste.it (Michele Simionato) writes: > > This is not a bug. The developers removed the possibility to change > > the bases of a new-style class. > > Bad news for you: I put it back in for 2.3. It is back! > If you read the error message, you'll notice that it's phrased to > suggest that assignment to __bases__ is *sometimes* possible :-) > > David's assignment probably should work -- there's a bug on sf about > this -- but there are definitely situations where assignment to bases > *shouldn't* be allowed -- e.g. when the so-called 'solid base' changes > -- but noone's put in the thinking time to make this precise in code. > Being over-restrictive seems the better course. > Uhm, I can see that in certain cases it may work, both what if a class has "object" as base and we change it to "type" ? What if we change the base class from new style to old style? What if we change one of the base classes with another one which is instance of a different metaclass? How do you solve the conflicts? What about ExtensionClasses and replacing normal bases with C-coded ones? I see a recipe for disasters here, so that's why I thought the developer removed the option of changing the bases. That would be understable. What I do not understand is why I cannot change the __name__ of a function, what could possible go wrong with that?? Michele From jepler at unpythonic.net Tue Jun 1 22:44:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 1 Jun 2004 21:44:59 -0500 Subject: Any Python modules for manipulating JFIF file contents? In-Reply-To: References: Message-ID: <20040602024459.GA1990@unpythonic.net> PIL can extract information like resolution. exifdump.py and EXIF.py can read the "EXIF" data that accompanies many photos taken on digital cameras. This can include a thumbnail, information like exposure time and focal length, and on some cameras it even tells you the orientation of the camera when the picture was taken. These two programs don't have any external requirements, they parse the JFIF and EXIF structures in pure Python. There are also Python wrappers for imlib and imagemagick, two other (unix) libraries often seen for image manipulation. I used imlib long ago, but I've never used imagemagick. My online photo albums (http://photos.unpy.net) use python with image metadata stored in a postgres database and the images themselves stored on the filesystem. It uses exifdump.py to read EXIF information. The source code to this is too nasty for me to consider sharing it with the world. More recently, I've been writing an image viewer in pygame, with the primary goal to reduce how often the user waits for a response. For instance, when the program is idle it preloads and scales the next/previous image in the image sequence. This has been fun (and I'm glad I learned pygame) but a user madly pressing "next" on an 800MHz machine can always get ahead of the computer trying to load 6 megapixel photos! To make things worse, PIL doesn't seem to release the GIL during long operations (such as loading a JPEG image or scaling it, each of which can take 2 seconds), and lacks progress callbacks (let alone a way to abort one of these operations in progress)... Have fun with your project! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From maketo at ukato.freeshell.org Fri Jun 25 10:35:16 2004 From: maketo at ukato.freeshell.org (Ognen Duzlevski) Date: Fri, 25 Jun 2004 14:35:16 +0000 (UTC) Subject: Python Magazine exists! References: Message-ID: Mark wrote: > It seems a lot of people are not aware that a Python Magazine exists. > Visit: > http://www.pyzine.com > to see what we are publishing this quarter and check out our free > articles to see what > kind of articles we publish. > I'd like to repudiate once and for all the claim that: > "Nobody gets paid to write articles about Python" Hi, I went to see your magazine and it looks pretty nice. However, you do publish quarterly and in my humble opinion, a yearly subscription of 49 Euros is crazy. Ognen From grante at visi.com Tue Jun 29 16:41:42 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jun 2004 20:41:42 GMT Subject: setting icon using py2exe? References: Message-ID: > 2) According to http://starship.python.net/crew/theller/moin.cgi/CustomIcons > you can set the icon_resources in the setup.py like this: > > # setup.py > from distutils.core import setup > import py2exe > setup(windows=[{"script":"vfcupdate.py","icon_resources":[(1,"rivatek.ico")]}]) > > That doesn't work either: > File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 577, in build_executable > add_icon(unicode(exe_path), unicode(ico_filename), ico_id) > RuntimeError: MapExistingFile: The handle is invalid. Never mind.... Further googling reveals this is a known bug when running under Win98/Me: http://groups.google.com/groups?th=4d594c535345b98b -- Grant Edwards grante Yow! Four thousand at different MAGNATES, MOGULS visi.com & NABOBS are romping in my gothic solarium!! From edewall at qualcomm.com Thu Jun 24 18:33:32 2004 From: edewall at qualcomm.com (Eric DeWall) Date: Thu, 24 Jun 2004 15:33:32 -0700 Subject: Optional use of logging library module References: Message-ID: Hi Neil, First off, happy to see someone else with some real appreciation for a standardized and full-featured logging module! You're preaching to the choir a bit here - I'm also not a speed freak and I will personally _always_ associate a logger with my class instance. But some folks _don't_ use/like/appreciate the logging module so I'd rather not make it a requirement for them to use logging to reuse my classes. Irmen's suggestion of the null pattern elegantly solves my dilemma. And for folks who don't want logging, they'll still have to handle exceptions when something goes wrong. :) --Eric "Neil Benn" wrote in message news:mailman.84.1088086108.27577.python-list at python.org... > > > However what I would suggest could be a good solution for you is to > always have a logger present and log debug messages as debug and use the > other levels for what they are meant for WARNING, ERROR, etc. That way > you can easily turn the logger off in the instance you are working > with. Yes, OK you take a small speed knock but the speed knock I've had > on this is small (I'm not a speed junkie anyways). > > I also agree with you, a fully featured logger is essential and > personally - I'm happy with the design, it's not too complicated you > only need to read through the docs and try it out - easy peasy lemon > squeezy. > > Cheers, > > Neil > From rhh at structurelabs.com Sun Jun 6 18:55:56 2004 From: rhh at structurelabs.com (r holland) Date: 6 Jun 2004 15:55:56 -0700 Subject: Problem with Python xrange References: Message-ID: xrange is a special object intended for operations like looping try this: a=xrange(10) b=range(10) if you do: type(a) type(b) you'll see that a is 'xrange' and b is a 'list' if you do: dir(a) dir(b) you'll see that a has all of the list methods (which includes slicing) whereas b has none. xrange is a generator object so slicing is not relevant, although you could assemble a list from the generator using append, that could then be sliced. From alex-news-deleteme at comcast.net Tue Jun 29 14:56:06 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 29 Jun 2004 18:56:06 GMT Subject: embedded python? References: Message-ID: What distro are you running? Thanks, Alex "Lars" wrote in message news:cbs7fr$n15$1 at new-usenet.uk.sun.com... > Hi, > > Python (at least version 1.something) was running fine on my Psion 5mx > (36 Mhz ARM, 16MB RAM). No problem. > > > Jirka > > > Alexander May wrote: > > Hi, > > > > I love Python! I've been using it for a couple of years now and have found > > it to be a highly productive language. I evangelize it to my developer > > friends and am probably responsible for the sale of at least 10 Alex > > Martelli books. I am now in the fortunate position of being able to use > > Python for a large project, and as such I have a question. > > > > We are developing a distributed application running on approximately six > > thousand nodes with somewhat limited hardware resources. Our hardware > > target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected > > specific hardware yet; the hardware target is what we are trying to fit into > > based on price constraints. Each device needs to be able to handle about 2 > > kbs (yes kilo, not mega) worth of network traffic. > > > > I intend to a least prototype the system in Python. It would be great if we > > could we could use Python in production by embedding it in the hardware. My > > question is does anyone have any real world experience using python in an > > embedded system? Two general categories of questions: > > > > 1) Are there any embedded Pythons out there? The nodes will likely be > > running some form of Linux, but I don't particularly feel like devoting > > resrouces to porting python. Any embedded Linuxes supporting Python? > > Thoughts in general? > > > > 2) What are the resource requirements of Python? How much overhead do the > > network related modules add? Obviously I'll be able to determine our > > application's resource usage once the prototype is written, but I curious > > about other people's past experience. > > > > In short, is embedding python realistic? > > > > Thoughts and comments are greatly appreciated! > > > > Thanks, > > Alex > > > > From reinhold-birkenfeld-nospam at wolke7.net Thu Jun 17 08:44:21 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 17 Jun 2004 14:44:21 +0200 Subject: Unnatural behaviour in Pickling In-Reply-To: References: Message-ID: <2jdhr9Fugd3hU1@uni-berlin.de> Pekka Niiranen wrote: > Hi there, > > why must file be opened in "r" -mode, before loading works > with Pickling? This forces me to close the file between pickle.dump > and pickle.load. :( > > Example: > -----************------ > > a = {'pekka': 1, 'jussi': 2} > fh = open('c:\temp\log.log', "wb") > pickle.dump(a,fh) > fh.close() > > **** now: > fh = open('c:\temp\log.log', "wb") > b = pickle.load(fh) > **** gives error: > IOError: (0, 'Error') > > **** however: > fh = open('c:\temp\loglog', "rb") > b = pickle.load(fh) > **** works. Well, unpickling involves reading from the file, so you must open it in read and write mode, e.g. "w+b". BTW, you should reset the file pointer between dumping and loading by using seek(). Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From davidf at sjsoft.com Wed Jun 2 07:38:55 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 13:38:55 +0200 Subject: distutils sdist and MANIFEST files Message-ID: Hi Does anyone else find it annoying that the sdist command for distutils relies on MANIFEST.in and MANIFEST files? I would really like to be able to do everything in the setup script ; if I don't, the MANIFEST files get created automatically (with warnings) and any new scripts added are forgotten. Any alternative approaches to this? David From BELLEMAIL-SA at exponent.com Thu Jun 10 10:46:28 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 10 Jun 2004 07:46:28 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28D6E@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = candycane1828 at hotmail.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 124 Scanning time = 06/10/2004 07:46:27 Engine/Pattern = 7.000-1004/903 Action taken on message: The attachment message_details.pif matched file blocking settings. ScanMail took the action: Deleted. The attachment your_file.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From me at privacy.net Thu Jun 10 12:29:36 2004 From: me at privacy.net (Duncan Booth) Date: 10 Jun 2004 16:29:36 GMT Subject: does python have useless destructors? References: Message-ID: "Robert Brewer" wrote in news:mailman.819.1086881457.6949.python-list at python.org: > AFAICT, you don't need to reraise the exception. Example: > >>>> try: > ... f > ... finally: > ... print 'finally' > ... > finally > Traceback (most recent call last): > File "", line 2, in ? > NameError: name 'f' is not defined > > > But I could be wrong--perhaps you've got a requirement I can't see on > first glance. I'll try to explain my intention a bit more clearly. As you note, if the try block throws then you don't need to re-raise the exception. What I was trying to do was to handle the case where the dispose code throws an exception. If that happens when we already have an exception, then I want to mask the second exception and continue with the first, but if it happens when there is no exception I want the exception to be thrown. I am quite willing to be persuaded though that the correct action would be that an exception thrown in the dispose be allowed to mask the inner exception. > > def dispose(localdict, argnames): you meant *argnames > for name in argnames: > obj = localdict.get(name) > if obj: > try: > dispfunc = obj.__dispose__ > except AttributeError: > pass > else: > dispfunc() > Close, but not quite there. I think you need to ensure that all of the __dispose__ methods *must* be called, even if an earlier one fails. From reiner.block at bisoft.de Fri Jun 4 07:43:56 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Fri, 04 Jun 2004 13:43:56 +0200 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2ib02kFljftcU1@uni-berlin.de> Message-ID: <2ib5jsFkop62U1@uni-berlin.de> Hi Heiko, > Hmm... Why not work with emacs? I actually like the emacs Python mode. It's > pretty sophisticated, and does all I need to program in Python. I've yet to > see eric (it's installed, but I've never used it), but I've never felt the > need for more than the Python-mode of emacs. at the moment I really don't want to learn such a high sophisticated editor like emacs. :-) Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From BELLEMAIL-SA at exponent.com Thu Jun 17 15:16:36 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 12:16:36 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EB8@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = miki.tebeka at zoran.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 236 Scanning time = 06/17/2004 12:16:36 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment Bill.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From peter at engcorp.com Fri Jun 25 09:05:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jun 2004 09:05:59 -0400 Subject: win XP + wxPython + py2exe In-Reply-To: <40dbeb20$0$17148$626a14ce@news.free.fr> References: <40dbeb20$0$17148$626a14ce@news.free.fr> Message-ID: Olivier Thiery wrote: > I've ported a software I've developped from win 2k to win xp and something I > wouldn't have expected happened. > > If I simply run the py files, the software uses the current xp skin > looknfeel, but if I compile it using py2exe it looks like any ugly standard > grey win2k app. > > Does anybody know why and how it can be fixed ? This has been discussed in the group and groups.google.com can certainly dig up the reference for you, if Jaco's advice doesn't get you all the way there. -Peter From insom at iol.ie Wed Jun 9 05:53:01 2004 From: insom at iol.ie (Aaron Brady) Date: Wed, 9 Jun 2004 10:53:01 +0100 (GMT Daylight Time) Subject: Python Speed Question and Opinion In-Reply-To: <40c6cf1e$0$3403$afc38c87@news.easynet.co.uk> References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> <3064b51d.0406080809.2b94b54c@posting.google.com> <40c6cf1e$0$3403$afc38c87@news.easynet.co.uk> Message-ID: > > Anyone who is writing python and has speed of execution as a priority has a > screw loose, just as anyone writing assembler and expecting ease of > development. > http://www.dadgum.com/james/performance.html The above essay, while dealing with Erlang, does something to dispell the myth that performace == assembler. A sequential-scan in assembler is still a sequential-scan - if you can implement, for example, BTrees easily in Python, then on large datasets that's a win. Aaron http://insom.me.uk/blog/ From reiner.block at bisoft.de Thu Jun 3 13:50:31 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Thu, 03 Jun 2004 19:50:31 +0200 Subject: Python reference Message-ID: <2i96n6Fklj78U2@uni-berlin.de> Hi, does anybody knows a really good Python reference? It is not the matter if it is online or a book, if it is in english or german. Because the official one from www.python.org is really bad. :-( Referencegreetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From chrisks at NOSPAMudel.edu Sat Jun 12 02:26:39 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 12 Jun 2004 02:26:39 -0400 Subject: Exec Multiple Lines? Message-ID: I'd like to dynamically execute multiple lines of indented code from within a script, but I can't seem to find a suitable function. Exec only works with unindented code, and execfile only works with files. I suppose I could write my string to a temporary file and then use execfile, but that seems like a hack. Is there an easier way? Any help is appreciated. From jimka at rdrop.com Mon Jun 7 16:17:56 2004 From: jimka at rdrop.com (Jim Newton) Date: Mon, 07 Jun 2004 22:17:56 +0200 Subject: if does not evaluate In-Reply-To: References: <2if8daFmdreiU1@uni-berlin.de> Message-ID: <2ik434Fntu3aU1@uni-berlin.de> well, i accept the fact that python offers some simple concepts and you do a lot with simple concepts, but why can't you put an if inside a lambda? if "if" were evaluatable then you would be able to do that. it seems to me. lambda seem to work for very simple things but not for anything substantial. Terry Reedy wrote: > "Jim Newton" wrote in message > news:2if8daFmdreiU1 at uni-berlin.de... > >>how do you put an if or a for inside a lambda? > > > By wrapping them in other functions; otherwise you don't. > > lambda *args: expr #abbreviates (minus the function name) > def f(*args): return expr > > If your function is more complicated than that, don't try to abbreviate. > Use def. > > Terry J. Reedy > > > > From moughanj at tcd.ie Thu Jun 10 17:54:17 2004 From: moughanj at tcd.ie (James Moughan) Date: 10 Jun 2004 14:54:17 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> Message-ID: <16752bcc.0406101354.63610c62@posting.google.com> Jacek Generowicz wrote in message news:... > moughanj at tcd.ie (James Moughan) trolls: > > > Lisp, I think, has two problems. > > > > Firstly an attitude among the community that actually *doing* anything > > is, well, beneath the language; > > Investigate the links in the sidebar on the left on > > http://www.franz.com/success/ > > for a summary of the sort of stuff people actually *do* in Lisp. > > If you actually bothered to look before posting unfounded rubbish, you > might have noticed that Lisp fans appreciate it exactly because it is > extremely good for writing industrial programs in real-world > situations. > I have no doubt that Lisp can be extremely practical as a language. I'm expressing a slightly humorous characterization of the attitude of parts of the Lisp community, especially in academia. > > after working through two books and several university courses on > > Lisp, going from the definition of eval to lexical vs dynamic > > scoping to macros to continuations, I suddenly realised that I had > > no idea how to open a file or do basic string manipulation. None of > > them condescended to sully themselves with such trivia. > > Maybe Lisp (and therefore Lisp books) are designed for intelligent > people who want to solve hard problems, and it is assumed that > intelligent people can look up trivia like how to open files in the > language standard (); maybe books are considered necessary to teach > you the difficult things which you cannot read between the lines of > the standard. > > Maybe you read the wrong books and go to the wrong universities, at > least for your sort of mind. Strange, I've always worked the other way around. For the extremely simple, basic things it seems like *slight* overkill to refer to the ansi standard. For complex issues I'd rather have a formal language document that tells me exactly what's going on, rather than someone blathering for 50 pages. In this case, I merely found it particularly striking that a subject like file i/o, which would be considered basic and important in most languages, seemed to be in many Lispers' 'blind spot'. Lisp is, without doubt, the most interesting language around in terms of pure theory. The corollary to that, I guess, is that it attracts a lot of pure theorists. > The following book, still in the process > of being written, might be more to your liking: > > http://www.gigamonkeys.com/book/ > > Note the title: _Practical Common Lisp_. > Yes, I'm aware that there's some stuff on the more practical side; the Lisp Cookbook isn't too bad either. But it's definitely not the norm, and you have to dig quite a bit. No problem, I'm a persistent git. > > Secondly, Lisp's syntax doesn't parse well into the way people > > think, > > ... after 20 seconds of thought. > > If you actually try using Lisp, as a programming language for writing > real-world programs, rather than as something to troll about, then you > will find that Lisp's syntax matches very closely the way people > think: they start thinking about source code as a tree structure > rather than a series of tokens. Not really, no. People think about programs tree-style where certain control structures occur, and virtually all languages nest at those points. However, not in cases like assignment and mathematical expressions, where Lisp would still tend to mandate it. That sort of deeply nested code is often the most unreadable. Also Lisp usually nests somewhat uncomfortably, e.g. in an if statement (if (< i 0) (* -1 i) i) There's simply no context there for the eye to pick up on. Nest all of that a couple of layers deeper and it's going to become annoying. That's the trouble with having an extremely regular, simple system. I guess it makes building the AST easy, though. ;) I am not trolling about Lisp, btw. I'm expressing my experiences of playing around with Lisp as a new language. My intention was more in the line of amusement. And, frankly, if you think that a mildly sarcastic comment about some of the learning materials for Lisp, along a bold statement that Lisp doesn't have the world's most intuitive syntax is a viscous, trollish slur on the language, justifying random personal attacks, then you really need to get a freaking life. >This takes us back to the original > point I made upthread. Just because your tools don't provide you with > the ability to do something, thereby ensuring that you don't do it, > does not mean that doing it is a bad idea, or that not being able to > do it is a language feature. > > Lisp allows you to think of program source as a tree. "Source is a > series of tokens" languages seriously limit the way you think about > your program: this is a shortcoming, not a feature. > > Don't conclude, just because the tools you use limit you in some way, > that escaping those limitations is somehow undesirable. It's quite possible to build a program as a set of recursive functions in just about any language, if you *wish* to build it as a tree structure. In fact I do that pretty often, where a problem happens to be best expressed in that way. However Lisp pretty much forces you into one way of doing things. That's a shortcoming, not a feature. The *advantage* of that shortcoming is that it allows you to blur or eliminate the distinction between program code and data; that's where Lisp gets it's power from. It's a trade-off, like most language design issues. Lisp has an extremely natural form for certain problems. Handling HTML and XML is one of those, and Lisp should really have squeezed into in many of the gaps currently filled by Java. (Yes, there have been companies doing this highly successfully; not many, though.) But different problems may - shock - be better expressed through different languages, and diferent syntaxes. From tdelaney at avaya.com Wed Jun 9 23:59:52 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 10 Jun 2004 13:59:52 +1000 Subject: does python have useless destructors? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019632E8@au3010avexu1.global.avaya.com> Michael Geary wrote: >>> try: >>> myfile = open("myfilepath", "w") >>> myfile.write(reallybigbuffer) >>> finally: >>> myfile.close() >> >> ... "feels" just right. This is how you do it when you >> want to be sure the file is closed, regardless of >> other considerations like garbage collection, etc. >> >> It is simple, clean, and most of all, very explicit. > > And it has a bug. :-) > > What if "myfilepath" is not writable? The open() call raises an > exception, which jumps to the finally: block, where myfile.close() > fails because myfile is undefined. > > What would be the cleanest way to code this to handle that error > situation? myfile = open("myfilepath", "w") try: myfile.write(reallybigbuffer) finally: myfile.close() Tim Delaney From roy at panix.com Thu Jun 3 11:07:14 2004 From: roy at panix.com (Roy Smith) Date: Thu, 03 Jun 2004 11:07:14 -0400 Subject: Why did no one invent Python before? References: Message-ID: Sion Arrowsmith wrote: > A more pertinent question might be why, when languages like this > appeared some time ago, are monstrosities like C# still being > created? Here's my take on the currently popular languages... C took off in the late 70's and early 80's because it was so much better than the alternatives, and because it was wrapped up with Unix (about which the same thing can be said). C really was (and still is) a very good language for what it was intended for: low level procedural programming. C++ took off in the mid to late 80's because it answered a need for OO functionality while maintaining backwards compatability with C. It also added a few useful features C was lacking. Unfortunately, it also suffered from a bad case of "second system syndrome". It piled one complicated feature on top of another, and grew to be an ugly monster. But don't underestimate the power of the C compatability; for better or worse, that is what made C++ become so popular. Java took off in the 1990's for two reasons. One is that it answered a need for a OOPL which didn't suck quite so much as C++, while still looking and feeling enough like it to make people comfortable. The other (and far more critical), reason is that Java jumped on the web bandwagon with both feet. Between applets and things like JSP (I actually think JSP is a pretty neat system), Java was the language to know if you wanted to be involved in web development in the 1990's, and everybody in the 1990's wanted to be involved in web development. You could have duct-taped a dead whale to the side of the web bandwagon and it would have gotten pulled along. The fact that Java was being hyped by Sun, the darling of the 90's, didn't hurt either. I must confess to not knowing much about C#, but my (somewhat ignorant) take on it is that it's taking off because it's yet another language that doesn't suck quite so much as C++, while still looking and feeling enough like it to make people comfortable, and it's duct-taped to the side of the Microsoft bandwagon. All python did was provide a good programming environment. From michele.simionato at gmail.com Mon Jun 28 12:05:08 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Jun 2004 09:05:08 -0700 Subject: What is the meaning of static and class methods ? References: Message-ID: <4edc17eb.0406280805.6fac0046@posting.google.com> "fowlertrainer at anonym.hu" wrote in message news:... > > I want to anyone please send an example of class/static methods that > HAVE MEANING. > A real example, to I understand, why we need that methods in python. > > Thanx for it: > FT I may sound heretic, but I never thought their introduction as builtins was a particularly clever idea. Python lived pretty well without them for years and could continue living without them. They are just a syntactic convenient which is not very convenient, actually, since we do not have decorators yet. Michele Simionato From roy at panix.com Mon Jun 21 12:28:33 2004 From: roy at panix.com (Roy Smith) Date: Mon, 21 Jun 2004 12:28:33 -0400 Subject: Python memory use (psyco, C++) Message-ID: I understand that psyco significantly increases memory use. Is that for code or data? More specifically, if I've got a memory intensive application (it might use 100's of Mbytes of data), should I expect memory use to go up significantly under psyco? Also, for that memory intensive application, how should I expect Python memory use to compare with C++? I'm really only interested in data; the memory needed to store the code is almost certainly insignificant in either case. The data is a large number of small objects, interconnected in various data structures, not just one huge block of raw data. I know all of the above is very vague, but I'm just trying to get a rough idea if a Python implementation is feasable (or at least plausable). If a C++ version takes 300 Mbytes and a Python version takes 1 Gig, that's probably not going to work. Are there any rules of thumb I could use to get a first-order estimate? From manatlan at online.fr Thu Jun 10 17:21:16 2004 From: manatlan at online.fr (marco) Date: Thu, 10 Jun 2004 23:21:16 +0200 Subject: dynamic import with heritage Message-ID: <40c8d0d0$0$26780$636a15ce@news.free.fr> i try to make a dynamic import of a plugin which herits from another class here my main: ------------------------------------------------------------------- class bidon: pass plugin = __import__( "plugins.dhuile" , globals(), locals()) ------------------------------------------------------------------- And in the file /plugins/dhuile/__init__.py, i've got : ------------------------------------------------------------------- class vidange(bidon): def test(): return "ok" ------------------------------------------------------------------- python2.3 gives me : "__init__.py : NameError: name 'bidon' is not defined" i don't understand where is the mistake ?! (class "bidon" is in passed by the globals() ... but it seems __init__.py doesn't understand) anybody have got an idea ? thanx From ralobao at gmail.com Fri Jun 11 19:01:01 2004 From: ralobao at gmail.com (ralobao) Date: 11 Jun 2004 16:01:01 -0700 Subject: Problem with urllib.urlretrieve Message-ID: Hi, i am doing a program to download all images from an specified site. it already works with most of the sites, but in some cases like: www.slashdot.org it only download 1kb of the image. This 1kb is a html page with a 503 error. What can i make to really get those images ? Thanks Your Help is aprecciate. From fperez528 at yahoo.com Tue Jun 15 02:28:45 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 15 Jun 2004 00:28:45 -0600 Subject: How to Access Unix Shell References: <2d7af4f8.0406131648.42868c63@posting.google.com> Message-ID: Neale wrote: > In a python program, I want to do a Unix directory list and then > append selected files to each other which, as you know, is just "cat > filename2 >> filename1." How do I escape into the shell and then > return, bringing with me a directory list? > > Where can I find some examples of mixing shell commands and Python? [~]> ipython Python 2.2.3 (#1, Oct 15 2003, 23:33:35) Type "copyright", "credits" or "license" for more information. IPython 0.6.1.cvs -- An enhanced Interactive Python. ? -> Introduction to IPython's features. @magic -> Information about IPython's 'magic' @ functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: cd test /usr/local/home/fperez/test In [2]: ls argv.py* die.py div.py err.pyc image2.eps ipython.log strings.py t.py bar.py div.c error.py* exit.py* image.eps ramptest.py* times.sh* bar.pyc div.f err.py foo.py image.ps scopes.py* tmp/ In [3]: cp t.py tmp/ cp: overwrite `tmp/t.py'? y In [4]: cd tmp /usr/local/home/fperez/test/tmp In [5]: ll total 8 -rw-r--r-- 1 fperez wavelet 91 Jun 15 00:19 strings.py -rw-r--r-- 1 fperez wavelet 43 Jun 15 00:27 t.py In [6]: cat strings.py >> t.py In [7]: ll total 8 -rw-r--r-- 1 fperez wavelet 91 Jun 15 00:19 strings.py -rw-r--r-- 1 fperez wavelet 134 Jun 15 00:27 t.py In [8]: !!ls Out[8]: ['strings.py', 't.py'] In [9]: for fname in _8: ...: print 'filename:',fname ...: filename: strings.py filename: t.py Hope this helps, f From newsgroups at jhrothjr.com Mon Jun 21 17:59:51 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 21 Jun 2004 17:59:51 -0400 Subject: Unicode perplex References: <10deickd7vpmo7a@news.supernews.com> Message-ID: <10demk2hkaq1v2d@news.supernews.com> "Ivan Voras" wrote in message news:cb7jks$9hv$1 at bagan.srce.hr... > John Roth wrote: > > > The problem is that I've got a normal string where > > the byte stream is actually UTF-8. How do I turn > > it into a Unicode string? Remember that the trick > > does > > str2 = str.decode('utf-8') > > work? [dirty word]. Thanks. I knew I'd seen it before somewhere; it just didn't occur to me to look in the obvious place. It sure ought to. Thanks. John Roth > > > -- > What part of "Ph'nglui mglw'nath Cthulhu R'lyeh wgah'nagl fhtagn" don't > you understand? From chris.cavalaria at free.fr Mon Jun 7 17:27:36 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Mon, 07 Jun 2004 23:27:36 +0200 Subject: Python Wiki & wiki Hosting? References: <20040605115256.1749992717.eric@zomething.com> <23891c90.0406070159.1925a39d@posting.google.com> Message-ID: <40c4ddc9$0$13927$636a15ce@news.free.fr> Eric S. Johansson wrote: > Paul Boddie wrote: > >> "Eric S. Johansson" wrote in message >> news:... >>> "Why can't you edit wiki pages like you were in >>>word". >> >> >> Development documentation in Word? Welcome to a world of pain! Sounds >> like exactly the sort of thing a CEO would want to have. (Yes, of >> course I'm twisting the very meaning of the words, and perhaps the CEO >> didn't actually want you to use Word.) > > yes, he did not actually want to use word and if you notice I said "like > you were in word". :-) > > he was looking for a WYSIWYG interface on the tool. And I have my own > reasons for wanting it as well. Something like that maybe : http://www.mozilla.org/editor/midasdemo/ From dg2smb at gmx.de Tue Jun 8 03:05:38 2004 From: dg2smb at gmx.de (Martin Brodbeck) Date: Tue, 08 Jun 2004 09:05:38 +0200 Subject: FTP, Proxy and urllib2 In-Reply-To: References: Message-ID: John J. Lee wrote: Hi John, > I think you need to use ftplib. urllib2 is for fetching files, not > uploading them (unless there's some obscure feature of ftp URLs that > allows it). > > Use ftplib. Ok, but what if there is a proxy between the client and the ftp server? Can ftplib handle this? How? Thanks Martin From klachemin at home.com Mon Jun 14 00:43:30 2004 From: klachemin at home.com (Kamilche) Date: 13 Jun 2004 21:43:30 -0700 Subject: Limits on number of classes? References: Message-ID: <889cbba0.0406132043.6e2049e8@posting.google.com> "Tim Peters" wrote in message news:... > If your inheritance chain is a thousand levels deep, then (a) it's going to > take a long time to resolve a method defined in the base class when accessed > from an instance of the most-derived class; and, (b) you're insane . No, just hundreds of shallow classes. I'm using classes as a 'prototype' for objects in memory, and there will be a million or so of those... I was just hoping that I could have hundreds of classes, without suffering a bad speed hit. From opengeometry at yahoo.ca Wed Jun 16 15:40:49 2004 From: opengeometry at yahoo.ca (William Park) Date: 16 Jun 2004 19:40:49 GMT Subject: very large dictionaries References: Message-ID: <2jbm1vFvh88vU1@uni-berlin.de> robin wrote: > I need to do a search through about 50 million records, each of which > are less than 100 bytes wide. A database is actually too slow for > this, so I thought of optimising the data and putting it all in > memory. > > There is a single key field, so a dictionary is an obvious choice for > a structure, since Python optimises these nicely. > > But is there a better choice? Is it worth building some sort of tree? 50M x 100 = 5000M = 5G. You got 5Gig of memory? Since you are talking about key/value record, you can choose from GDBM (gdbm), Berkeley DB (dbhash), or disk-based dictionary front-end (shelve). You can now access GDBM database from Bash shell. :-) -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From e.d.andersen at mosek.com Tue Jun 29 03:33:07 2004 From: e.d.andersen at mosek.com (edadk) Date: 29 Jun 2004 00:33:07 -0700 Subject: Problem with Python on MAC OSX Message-ID: Hi I have problem with Python on MAC OSX. The following code documents it strib:~ eda$ pwd /home/eda strib:~ eda$ python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.getcwd() /private/home/eda >>> Note I would have expected print os.getcwd() to print /home/eda Note that >>> os.system('echo $PWD') /home/eda 0 Of course /home/eda is a symbolic link to /private/home/eda. Is this a bug or a feature? Is there a good way to work around it? Regards Erling From tjreedy at udel.edu Thu Jun 3 14:59:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jun 2004 14:59:46 -0400 Subject: Why did no one invent Python before? References: <40BE621C.97EEC2AA@alcyone.com> <10bu9k8evp5o25c@corp.supernews.com> Message-ID: "Cameron Laird" wrote in message news:10bu9k8evp5o25c at corp.supernews.com... > I see as critical enough time to make sufficient mistakes. I see Python as a or even the successor to Basic, which was invented over 40 years ago. It was the first 'computer programming for everybody' (CP4E) language. Basic took off in the late 70s with the invention of microcomputers and the Microsoft port thereto. Its limitations were apparent by the mid 80s and so Guido invented/developed a new CP4E language. Terry J. Reedy From somebody at nowhere.com Tue Jun 29 04:54:03 2004 From: somebody at nowhere.com (Sean Richards) Date: Tue, 29 Jun 2004 20:54:03 +1200 Subject: Display vtkRendererWidgets References: Message-ID: <87u0wuhhhw.fsf@hugin.valhalla.net> "Yi-Yu Chou" writes: > Dear python users, > > I tried to display 4 vtkRendererWidgets arrayed in a 2x2 grid. > I method that I use is : > > root = Tk() > frame1 = Frame(root).pack(side=TOP) > frame2 = Frame(root).pack(side=BOTTOM) > x_pane = vtkTkRenderWidget(frame1,width=200,height=200) > y_pane = vtkTkRenderWidget(frame1,width=200,height=200) > z_pane = vtkTkRenderWidget(frame2,width=200,height=200) > all_pane = vtkTkRenderWidget(frame2,width=200,height=200) > > x_pane.pack(side=LEFT) > y_pane.pack(side=RIGHT) > z_pane.pack(side=LEFT) > all_pane.pack(side=RIGHT) > ..................................... > Idealy, the arrangement would be like : > > X | Y > -- | -- > Z | all > > However, I got some errors when running my code. > It seems that I can't use the syntax: vtkTkRendererWidget(frame1) > (I tried to display only one vtkTkRendererWidget by using > vtkTkRendererWidget(root), and it worked). > Any ideas ? > Thanks in advance !!! Not being a VTK guru myself but would it not be easier to just have the 1 vtkTkRendererWidget and then add 4 renderers each displaying to a separate area of the viewport. Here is a quick example --8<-------------------------------------------------------------------- from vtk import * from vtk.tk.vtkTkRenderWindowInteractor import * from Tkinter import * def coneExample1(): """ Creates a Cone inside a vtkTkRenderWindowInteractor. """ # create root window root = Tk() root.title("Cone 1") win = vtkTkRenderWindowInteractor(root, width=300, height=300) win.Initialize() def quit(obj=root): obj.quit() win.AddObserver("ExitEvent", lambda o,e,q=quit: q()) ren1 = vtk.vtkRenderer() win.GetRenderWindow().AddRenderer(ren1) ren2 = vtk.vtkRenderer() win.GetRenderWindow().AddRenderer(ren2) ren3 = vtk.vtkRenderer() win.GetRenderWindow().AddRenderer(ren3) ren4 = vtk.vtkRenderer() win.GetRenderWindow().AddRenderer(ren4) cone = vtk.vtkConeSource() cone.SetResolution(8) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInput(cone.GetOutput()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) ren1.AddActor(coneActor) ren2.AddActor(coneActor) ren3.AddActor(coneActor) ren4.AddActor(coneActor) ren1.SetViewport(0, 0, 0.5, 0.5) ren2.SetViewport(0.5, 0, 1, 0.5) ren3.SetViewport(0, 0.5, 0.5, 1) ren4.SetViewport(0.5, 0.5, 1, 1) # pack the win into the tk root win.pack(fill='both', expand=1) win.Start() # start the tk mainloop root.mainloop() if __name__ == "__main__": coneExample1() --8<-------------------------------------------------------------------- Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From nothanks at nothere.com Tue Jun 8 01:56:52 2004 From: nothanks at nothere.com (Emiliano Molina) Date: Tue, 08 Jun 2004 05:56:52 GMT Subject: wxPython DnD stops working after SetSizeHints In-Reply-To: References: Message-ID: >> self.panel=wxPanel(self,-1) > > This gets overwritten -^ > >> def __init__(self, window): > > unused --------------------^ Yes, you are 100% right, its there because I have been cutting down the original program bit by bit to find the problem! It should no longer be there. >># The following lines break the drag and drop >># self.panel=XRCCTRL(self.frame,"panel") >># sizer=self.panel.GetSizer() >># sizer.SetSizeHints(self.frame) > > > What is self.panel, as opposed to self.frame.panel? self.panel is where I am temporarily storing the window that I am adding the DnD to. One of the steps that I took when trying to work out where the problem was was to start with nothing but a frame and a panel and see if I could drop files into the panel. That worked fine, it was only when I added a sizer and then had to fit and set hints that DnD broke. I'm sorryt that the naming is a bit confusing, I posted this last night as a last desperate attempt before going to bed! > Hi Emiliano, it isn't clear what you are trying to do here, you seem to > have a panel being created in 3 different places -- which one do you > want? I suspect that the self.panel, is hiding the other panel > that you created (self.frame.panel) which is the drop target (just a > guess) The confusion is understandable, I should have spent more time tidying up the code before posting. self.frame.panel is used to store the retrieved control to which the DnD handler is attached. Its called panel because originally it WAS a panel, its now a wxListBox. self.panel is used to store the retrieved panel (this one IS a panel, sorry for the confusion) from which we can then obtain the main sizer for the frame. If we don't have the sizer we can't call SetSizeHints to arrange the controls in the window. Its the calling of SetSizeHints that seems to break the DnD handling. If I don't call SetSizeHints then DnD works fine and I can drop a file onto the list in the frame and its name is printed. The frame looks terrible of course, the controls are only arranged properly when I call SetSizeHints. > I've never used xrc, but this works for me (is it what you want?) > > some helpful code > > return True I tried the code you sent on the iBook and no luck, but you mentioned that it worked so I sent it over to the PC and tried it again. It worked! I had a close look at it and you have changed the drop target from the list to the main panel. I did the same with my code on the PC and it also worked. So the conclusion is that neither your or my code works on the Mac. Both sets of code work on the PC as long as the drop target is the panel and not the list. Thanks for your help and time. Now I have to figure out what is happening on the Mac. From gianluca.trombetta at tin.it Tue Jun 22 13:11:18 2004 From: gianluca.trombetta at tin.it (Gianluca Trombetta) Date: Tue, 22 Jun 2004 19:11:18 +0200 Subject: Remove font in python Message-ID: How can i remove a windows font using python? If i only remove the font file in windows\font directory, it remain in control panel, even though the file has been removed. Is there any functions that permit this? Any suggestion? Thanks in advance Regards. Gianluca Trombetta From brian at sweetapp.com Mon Jun 28 10:01:57 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 28 Jun 2004 16:01:57 +0200 Subject: ANN: Vancouver Python Workshop - Complete schedule available In-Reply-To: <40DC539D.2060206@sweetapp.com> References: <40CF1521.5040901@sweetapp.com> <40D5D59A.4060004@sweetapp.com> <40D86489.5060604@sweetapp.com> <40DC539D.2060206@sweetapp.com> Message-ID: <40E024D5.9090906@sweetapp.com> The complete schedule for the Vancouver Python Workshop is now available! For details, see: http://www.vanpyz.org/conference/programme.html Early bird conference registration is only open until Wednessday (June 30th) so you should register as soon as possible! For general conference information, see: http://www.vanpyz.org/conference About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o General Python Topics o Web application development with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From 'HUASMTP01_-_'securiQ.Watchdog'_Demon' at raiffeisen.hu Wed Jun 9 09:11:10 2004 From: 'HUASMTP01_-_'securiQ.Watchdog'_Demon' at raiffeisen.hu ('HUASMTP01_-_'securiQ.Watchdog'_Demon' at raiffeisen.hu) Date: Wed, 9 Jun 2004 15:11:10 +0200 Subject: ['securiQ.Watchdog': error during virus check>] Message-ID: GROUP securiQ.Watchdog Server: HUASMTP01 ----------------------------------------------------------------------- Your mail item contained attachments that caused an error during virus checking. Please contact your administrator ----------------------------------------------------------------------- Mail-Info From: python-list at python.org To: szeplaki.julianna at raiffeisen.hu Rec.: szeplaki.julianna at raiffeisen.hu Date: 06/09/2004 03:11:07 PM Subject: Re: Excel file ----------------------------------------------------------------------- file caused errors: document_excel.pif From heikowu at ceosg.de Fri Jun 4 05:36:52 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Fri, 4 Jun 2004 11:36:52 +0200 Subject: Class methods on user types Message-ID: <200406041136.52023.heikowu@ceosg.de> Hi all! I've written a user type, and I've declared class methods on it. Now... Strange things are'a happening, and the class methods which are declared on the type get the following output from pydoc: | bin = | fac = etc... The methods are declared in the PyMethodDef array of the class with the following syntax: {"bin", (PyCFunction)GMPi_bin, METH_CLASS | METH_VARARGS | METH_KEYWORDS, GMPi_bin_doc}, {"fac", (PyCFunction)GMPi_fac, METH_CLASS | METH_VARARGS | METH_KEYWORDS, GMPi_fac_doc}, etc. If I've understood the documentation correctly, this should create the appropriate class methods on the type. But why are they being attributed to type? Is it something I've done wrong in the declaration, or is this just the way it works? Any info appreciated! puzzeldly-y'rs, Heiko. From claudio.grondi at freenet.de Fri Jun 11 18:07:46 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 11 Jun 2004 22:07:46 -0000 Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> Message-ID: <2iui4lFr1nafU1@uni-berlin.de> If I understand right all your responses there is no way to get the decimal form of the prime within let me say minutes? Any other ideas how to get it similar fast as the hexadecimal form? Claudio P.S. the divmod() approach takes about four hours on a Pentium 4 2.8 GHz with 400 MHz dual RAM, where on Pentium III 900 MHz with 100 MHz RAM it lasts twice so long... mhhh... Is Pentium 4 slower than Pentium III running Pythons divmod() (compared at same Hz)? "Claudio Grondi" schrieb im Newsbeitrag news:2is27mFqeen8U1 at uni-berlin.de... > According to latest news the largest known prime is: > 2**24036583 - 1 > (right?) > > Do someone of you know how long would it take on > a 2.8 GHz Pentium 4 machine to write a _decimal_ form > (hexadecimal form can be written in less than one second) > of this prime to a file and what should be the Python code > to use for it? > > Claudio > P.S. file.write( '%i' % (2**24036583 - 1,) ) > takes 100% CPU for a long time without any result > and the critical part is the '%i' % (2**24036583 - 1,) > conversion. > > From cavallo at biochem.ucl.ac.uk Tue Jun 8 19:16:32 2004 From: cavallo at biochem.ucl.ac.uk (Antonio Cavallo) Date: 8 Jun 2004 16:16:32 -0700 Subject: speed problems References: Message-ID: > I've become interested in Python a while ago and just converted a simple > perl script to python. > I've found that there's a huge difference in execution time for the scripts, > in favor of perl and I can't pinpoint what's going wrong; I had the same problem in dealing with a large (compressed) file using python vs c++ (using the gzip library to open/read a file): the results were in favour of python against c++ this time;) I think the problem is in the flow: gzip -> file/pipe -> perl file -> zlib -> python The decompression through zlib is wfar slower because it is carried using data chunks: there is no mean to control where a chunk will terminate (like in correspondence to an EOL). Try using: zcat | myprogram.py In my case it solved all the puzzling speed problems: zcat uncoditionally dumps the data irregarding where the EOL happens (so the upper layer should not wait for the next chunk to be decompressed). regards, antonio cavallo From fowlertrainer at anonym.hu Tue Jun 22 08:39:36 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 22 Jun 2004 14:39:36 +0200 Subject: How to do special encode in string ? Message-ID: <40D82888.9090206@anonym.hu> Hi ! I'm hungarian, we use special characters like: ? - a' ? -o" etc. I want to encode this characters to in config file I see these characters as \nnn format. And I want to decode it automatically with python. How to I do it without write complex converter tool ? Thanx for it: FT Example: Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" From tdelaney at avaya.com Thu Jun 24 00:31:33 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 24 Jun 2004 14:31:33 +1000 Subject: How to download a file from an HTTP server given the URL? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019DCB22@au3010avexu1.global.avaya.com> Peter Hansen wrote: > Sylvain Hellegouarch wrote: > >> Hi Peter, >> >> You are right. But why being so rude? > > So I was not being rude. I was being helpful, in a blunt way. > I said nothing offensive, or at least not intentionally. > I asked the OP to give more info, and I added a bit of > coarse humour as well. Perhaps you were looking for offense where > none was intended... Peter was not only being very helpful (much more than I would have been) but was doing it in precisely the proper manner IMO. He provided pointers on ways to both assist us to work out the problem, and (hopefully) for the OP to work out the problem himself. >> Have you never been a newbie somewhere asking dumb question badly? I would have simply directed them to: http://www.catb.org/~esr/faqs/smart-questions.html (which I read several times a month to remind myself of the wisdom contained therein). Tim Delaney From surferjeff at gmail.com Fri Jun 11 15:08:47 2004 From: surferjeff at gmail.com (Jeff) Date: 11 Jun 2004 12:08:47 -0700 Subject: Anonymous file closing References: Message-ID: <781dd16f.0406111108.6f2e1afd@posting.google.com> Duncan Booth wrote in message news:... > Sergey Krushinsky wrote in > news:mailman.845.1086940793.6949.python-list at python.org: > > > Hello all, > > > > If I need to read a string from a file and use syntax like: > > text = open(filename, 'r').read() > > ... > > is the file object ever closed? > > > > With best regards, > > Sergey > > > > > > Yes it is closed, but it isn't well defined as to exactly when it is > closed. You can safely assume that the file will be closed sometime between > the read returning and your program exiting. > > If you aren't worried about portability, and you are using the C > implementation of Python then you may find it is closed immediately but it > is poor practice to depend on it. This is true, but I recommend: 1. Only use the C implementation of Python, a.k.a. The Implementation. 2. Depend on the file being closed immediately in this case. If the authors of the C implementation ever changed this behavior, they would break *lots* of existing python code, and they would also break one of the nicest example of how Python just works. From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 15 05:08:05 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 15 Jun 2004 11:08:05 +0200 Subject: Searching for the best scripting language, In-Reply-To: <2c60f0e0.0406131234.49b485ec@posting.google.com> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <2j7seqFu4237U1@uni-berlin.de> Richard James wrote: > Let the rabid "in defense of Python" flames begin! Come on, folks. Just look what "language" got the most points. Who would not refuse to write a shellscript of more than, say, 100 lines (except for quoting masochists)? Reinhold -- If a Linux distribution brought as few working software as Windows it would be a shame. The equivalent of Windows' "complete operating system" is called a rescue disk in the Linux world. -- David Kastrup in de.comp.os.unix.linux.misc, translated from German From peter at engcorp.com Tue Jun 22 05:52:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Jun 2004 05:52:58 -0400 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: <40d7c1cc_5@127.0.0.1> References: <40d7c1cc_5@127.0.0.1> Message-ID: Roger Upole wrote: > You can actually run tasks under your userid without a password > if you're logged in. However, you have to set a certain flag for the task. > (TASK_FLAG_RUN_ONLY_IF_LOGGED_ON) Wow, now there's someone who's been delving deep into the innards of MSDN. How do you guys *know* this stuff?! :-) From Scott.Daniels at Acm.Org Fri Jun 4 12:32:30 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 04 Jun 2004 09:32:30 -0700 Subject: Legitimacy of deepcopy In-Reply-To: References: Message-ID: <40c0a85a$1@nntp0.pdx.net> Eugeni Doljenko wrote: > There is a list of custom objects. I want do duplicate this list to modify > objects in new list and then compare old and new. I could do it with > deepcopy > > class foo: > def __init__(self, str): > self.str = str > old = [foo('str1'), foo('str2')] > > import copy > new = copy.deepcopy(old) > > But I've found very few deepcopy uses in Python library and other programs, > so I wonder it's possible to do it other, more elegant way. The problem with deepcopy is that it is impossible to do "correctly," since "correctly" depends on where your data structure abstractions are. A simple example: steve = People('Steve') joe = People(steve) mystruct = [(steve, joe, Dollars(5)), steve] Now, should a deepcopy have two distinct steves, or one? Is the $5.00 in the new structure "the same as" another $5.00 or not? Sometime you mean the identity of an object, and sometimes you mean it as a value, and no general purpose function named deepcopy can guess where to stop copying. -- -Scott David Daniels Scott.Daniels at Acm.Org From chrisks at NOSPAMudel.edu Sat Jun 26 00:28:56 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 26 Jun 2004 00:28:56 -0400 Subject: Persisting Dynamic Objects? Message-ID: Out of a somewhat academic interest, I've created a rudimentary module for persisting dynamically created objects and data structures in plain Python source code. Presently, it's a little under a thousand lines of code. It's still a work in progress and has several limitations but it is producing results. Is there any interest for me to clean it up and publicly release it? From jjl at pobox.com Tue Jun 1 15:42:56 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2004 20:42:56 +0100 Subject: Which is the most mature Soap module? References: Message-ID: <87d64jdpz3.fsf@pobox.com> Mickel Gr?nroos writes: > To the heart of the matter: Which of the available Soap modules is best > fitted for client side soap messaging? I have an upload service (written > in Perl) that I want to use from a Python application. What I want to do > is send base64 encoded files via Soap to this upload service which is on a > SSL encrypted server. I cannot really grasp the current development status IIRC, ZSI is. Certainly there is no solid WSDL implementation. Don't take my poor memory as gospel, though, read the recent article by Uche Ogbuji and Mike Olson that was referenced in a recent weekly Python-URL. Or you could just stick with httplib (I'd certainly rather not know anything about SOAP if I can help it, though). > of the various Soap modules around. Those I have found seem to need a lot > of other third-party modules. [...] What third-party modules? PyXML is the only one that comes to mind. That's only one package. John From newsgroups at jhrothjr.com Fri Jun 25 20:43:03 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 25 Jun 2004 20:43:03 -0400 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: <10dphkp78g6ne9d@news.supernews.com> "Doug Holton" wrote in message news:v6GdnWji9PwSMUHdRVn-uw at comcast.com... > Is there any metaclass trick or something similar to allow anonymous > code blocks? > > I'd like to be able to let users do something like this fictitious example: > b = Button() > b.OnClick =: > print "you clicked me" No. If you're looking for GUI callbacks, there's a significant gap between lambdas and bound methods. You could use something like (not tested): b.OnClick = (lambda : sys.stdout("You clicked me")) which will work (assuming I've got the syntax right). If you're doing anything other than a toy program, though, the best approach is to wrap the GUI widget in a class, and use a bound method of that class for the callbacks. The example in the Tkinter chapter of the Python Library Reference (16.1.2.2 in the Python 2.3.3 docs) shows how to do it. It's amazingly simple, it's completely object oriented, and it gives you full access to the instance within the callback. John Roth From bhoel at web.de Thu Jun 17 15:14:35 2004 From: bhoel at web.de (Berthold Höllmann) Date: Thu, 17 Jun 2004 21:14:35 +0200 Subject: Using Fortran libraries from Python? References: Message-ID: Carl writes: > I have experimented with f2c and swig-generated wrappers to create python > modules from Fortran files. > > I think I'm missing something when I'm building the Python module, because > when I import the built module the Python interpreter returns the > following: > >>>> import LDSsobol > Traceback (most recent call last): > File "", line 1, in ? > File "LDSsobol.py", line 4, in ? > import _LDSsobol > ImportError: /usr/lib/libf2c.so.0: undefined symbol: MAIN__ > > This is how I built LDSsobol: > >> gcc -c LDSsobol.c >> gcc -c LDSsobol_wrap.c -I/usr/include/python >> gcc -shared LDSsobol.o LDSsobol_wrap.o -l f2c -o _LDSsobol.so > Hello Carl, Googleing for "libf2c.so.0: undefined symbol: MAIN__" I found only 8 hits, some links broken, but also where I found: Currently users of f2c will probably encounter the following message: "libf2c.so.0: undefined symbol: MAIN__ ". Again, the culprit is that all references must be resolved, and libf2c.so unfortunately contains a reference to some dummy function. Fortunately the fix is simple, include the following snippet in your C native source (in our example mynativecalls.c): int MAIN__( ) { return(0); } Another solution (not tested) could be to use "-lg2c" instead of "-lf2c". As I understand it, the g77 runtime library is derived from the f2c runtime library. An even better (in my opinion) solution would be to use "f2py" from , a tool to wrap python (and C) code for python. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From Ian.Sparks at etrials.com Tue Jun 29 10:48:22 2004 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 29 Jun 2004 10:48:22 -0400 Subject: Listing functions in a file IN ORDER Message-ID: <41A1CBC76FDECC42B67946519C6677A9C5A735@pippin.int.etrials.com> I have a python file with a number of functions named with the form doX so : doTask1 doThing doOther The order these are executed in is important and I want them to be executed top-down. They all have the same parameter signature so I'd like to do : for name, func in vars(mymodule).items(): if not name.startswith("do") and callable(func): apply(func,my_params) but the problem is that the return from vars is not ordered the same as in the file. i.e. it could be doOther doTask1 doThing The low tech solution is to use dir() and re-name the functions to sort alphabetically but perhaps there is a more elegant solution? From SSchukat at dspace.de Mon Jun 28 12:20:26 2004 From: SSchukat at dspace.de (Stefan Schukat) Date: Mon, 28 Jun 2004 17:20:26 +0100 Subject: Python COM - limit on size/complexity of returned object? Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C0723BEE2@PDC-DSPACE> There was a reference bug in pythoncom.dll which lead to such errors. This should be fixed by now. Stefan -----Original Message----- From: pywin32-checkins-admin at lists.sourceforge.net [mailto:pywin32-checkins-admin at lists.sourceforge.net]On Behalf Of Mark Hammond Sent: Saturday, May 01, 2004 1:31 AM To: pywin32-checkins at lists.sourceforge.net Subject: [pywin32-checkins] pywin32/com/win32com/src oleargs.cpp,1.26,1.27 Update of /cvsroot/pywin32/pywin32/com/win32com/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv15064 Modified Files: oleargs.cpp Log Message: Fix a reference counting bug in the new arbitrary safearray code. Large arrays could cause a crash. Index: oleargs.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/src/oleargs.cpp,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** oleargs.cpp 25 Apr 2004 04:10:48 -0000 1.26 --- oleargs.cpp 1 May 2004 00:30:51 -0000 1.27 *************** *** 489,492 **** --- 489,493 ---- // Retrieve the stored size in this dimension ppyobDimension = PyInt_FromLong(lDimension); + // Note: No ref added by PyDict_GetItem ppyobDimensionSize = PyDict_GetItem(ppyobDimensionDictionary, ppyobDimension); if (NULL == ppyobDimensionSize) { *************** *** 500,504 **** { // if not the same size => no new dimension - Py_XDECREF(ppyobDimensionSize); Py_XDECREF(ppyobSize); Py_XDECREF(ppyobDimension); --- 501,504 ---- *************** *** 506,510 **** } } - Py_XDECREF(ppyobDimensionSize); Py_XDECREF(ppyobSize); Py_XDECREF(ppyobDimension); --- 506,509 ---- -----Original Message----- From: python-list-bounces+sschukat=dspace.de at python.org [mailto:python-list-bounces+sschukat=dspace.de at python.org]On Behalf Of google at prodigycomputing.com Sent: Saturday, June 26, 2004 11:22 AM To: python-list at python.org Subject: Re: Python COM - limit on size/complexity of returned object? kveretennicov at yahoo.com (Konstantin Veretennicov) wrote in message news:<5155aad2.0406250612.29d5039b at posting.google.com>... > Well, I did some testing with python 2.3 (that's what I have). > Not sure if it will cheer you up, but I had no problems. Thanks for the pointer. I tried it on another machine with 2.3 and that works with no problems. And I made some further discoveries on the 2.2 side: the problem isn't a limit on the size of the returned object, it's cumulative. I amended GetProfileComponentMatrixEx() to return the first n rows of the matrix, to find out what the limit was: like this >>> print len(GetProfileComponentMatrixEx(10)) 10 >>> print len(GetProfileComponentMatrixEx(40)) 40 >>> print len(GetProfileComponentMatrixEx(80)) But trying it repeatedly I found that I could only execute the following line once: it crashed calling it with an argument of 40 the second time: >>> print len(GetProfileComponentMatrixEx(40)) 40 >>> print len(GetProfileComponentMatrixEx(40)) And then I tried this repeatedly: >>> print len(GetProfileComponentMatrixEx(10)) and -- surprise! -- it failed about the 7th or 8th invocation. So, now there are two possibilities. 1. It's a 2.2 problem that is fixed in 2.3 (though I looked in Sourceforge for the bug reports and this did not show up there). 2. It's a side-effect of the module I'm importing to do the actual work. On the machine running 2.3, I had to write a stub to represent this module, because it is a home machine that can't see the work server where the data is. If the DLL is at fault, I'm going to have a hard time convincing the vendor that they have to fix it. If I were them, I'd be sceptical. The DLL is loaded by the import statement, but in this test it is never called. It's hard to see what it's initialization code could possibly be doing to break pythoncom. -- http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Tue Jun 29 08:41:52 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jun 2004 14:41:52 +0200 Subject: exec example - I don't understand References: Message-ID: kepes.krisztian at peto.hu wrote: > But I dont' understand that: > exec "x = 3; print x" in a > > So what this code do ? > Why we need "in a" ? > > This get same result ! First we make sure there's no variable x in the global namespace: >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined Underneath, the global namespace is just a dictionary with the variable names as keys and the objects as values. >>> "x" in globals() False Now let's use our own dictionary d as the namespace for the exec statement: >>> d = {} >>> exec "x=1" in d This leaves the global namespace unaffected: >>> "x" in globals() False Instead 1 is stored under the key "x" in the dictionary we provided: >>> "x" in d True >>> d["x"] 1 Now let's repeat the same exec statement without explicitly providing a dictionary. Python will then use globals() as the default. Therefore a variable x with the value 1 will "magically" appear: >>> exec "x=1" >>> "x" in globals() True >>> x 1 Peter From __peter__ at web.de Thu Jun 10 07:23:10 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jun 2004 13:23:10 +0200 Subject: Doc strings for a standalone app?? References: Message-ID: j_mckitrick wrote: > Peter Hansen wrote in message > news:... > >> The only thing I can think of to ask about that is "Why >> would you *not* want to use doc strings?". There is >> no significant overhead associated with them, so you >> don't really lose. They have potential advantages, given >> that the docs are available at runtime, more clearly >> identifiable as documentation, etc, whereas the other >> form of comments have no advantages for this kind of >> thing. So why not use them? > > Well, I can see that doc strings can be useful at the beginning of > each module/class/method/function. But since comments can be spread > throughout the code, explaining logic as needed, aren't they more > useful to someone who needs to maintain, rather than just use, your > code? I just came across an example where too many comments *obscured* the logic of a script. If you fear that your program cannot be understood without comments, try to express your intentions more clearly _in_ _code_ and reduce the number of # comments to the absolute minimum. > It SEEMS to me that doc strings are for those who will USE your code, > and comments for those who will MAINTAIN it. Does that make any > sense? The doc strings are/should be useful for both users and maintainers. In addition, maintainers can take advantage of a testsuite, either unit tests or - doc strings again - doctest. Comments are crutches. Peter From me at privacy.net Sat Jun 5 16:19:14 2004 From: me at privacy.net (Duncan Booth) Date: 5 Jun 2004 20:19:14 GMT Subject: print problem References: Message-ID: nick wrote in news:c9t9do$afn$1 at news3.bu.edu: > I want to print something without a '\n' automatically added at the end, sys.stdout.write('whatever') From flupke at nonexistingdomain.com Tue Jun 15 06:15:39 2004 From: flupke at nonexistingdomain.com (flupke) Date: Tue, 15 Jun 2004 10:15:39 GMT Subject: (OT) Boa Constructor and Python 2.3.4 Message-ID: Hi, i'm trying to get boa constructor working with Python 2.3.4 At first i tried with boa 0.2.3 but that gave me an error. After searching the web, it appeared that it's best to work with the CVS version. Well, i checked that version out and moved it to C:\Python23\Lib\site-packages\wxPython\tools\boa When i then try to run it "python boa.py" it gives me this output (windows 2000): C:\Python23>C:\Python23\python.exe C:\Python23\Lib\site-packages\wxPython\tools\boa\boa.py Starting Boa Constructor v0.2.8 importing wxPython reading user preferences Traceback (most recent call last): File "C:\Python23\Lib\site-packages\wxPython\tools\boa\boa.py", line 231, in ? import Preferences, Utils, About File "C:\Python23\Lib\site-packages\wxPython\tools\boa\Preferences.py", line 130, in ? execfile(file) File "C:\Python23\Lib\site-packages\wxPython\tools\boa\Config\prefs.rc.py", line 25, in ? splitterStyle = wxCLIP_CHILDREN | wxSP_LIVE_UPDATE | \ NameError: name 'wxSP_FULLSASH' is not defined My wxPython is version 2.5.1.5u. Any ideas? Kind regards, Benedict From bmorgan at usa.net Sat Jun 19 23:21:45 2004 From: bmorgan at usa.net (Byron Morgan) Date: 19 Jun 2004 20:21:45 -0700 Subject: Access SSL websites with Python? Message-ID: <85c78d18.0406191921.f7dcbc7@posting.google.com> I need to access a web site, log in, run a report and download the results, which will be added to a database. Of course, the login process uses SSL. Is it reasonable to attempt this with Python 2.3 on Windows 2000 platform? Can anyone provide an example of negotiating an SSL session? Byron Morgan From guenter.jantzen at t-mobile.de Wed Jun 9 07:00:58 2004 From: guenter.jantzen at t-mobile.de (G?nter Jantzen) Date: 9 Jun 2004 04:00:58 -0700 Subject: whatsnew 2.4 about itertools.groupby: Message-ID: In the documentation http://www.python.org/dev/doc/devel/whatsnew/node7.html is written about itertools.groupby: """Like it SQL counterpart, groupby() is typically used with sorted input.""" In SQL queries is the groupby clause not related to 'input order'. This notion makes not much sense in SQL context. SQL is based on relational Algebra. A SQL- table is based on an unordered set of rows (implementation can be different, of course). So the analogon of ---------------------- >>> import itertools >>> L = [2,4,6, 7,8,9,11, 12, 14] >>> for key_val, it in itertools.groupby(L, lambda x: x % 2): ... print key_val, list(it) ... 0 [2, 4, 6] 1 [7] 0 [8] 1 [9, 11] 0 [12, 14] >>> ------------------------ Say you have a table 'example' with only one column 'i' _________________________ select * from example; I ---- 2 14 6 7 8 9 11 12 4 ___________________________ the order of rows is not defined Then you can group this table ____________________________________________ select count(i), mod(i,2) from example group by mod(i,2) COUNT(I) | MOD(I,2) ---------+--------- 6 | 0 3 | 1 ___________________________________________ The result dos not depend on 'input order' or 'runs' From 24388.955485435 at www4.gmx.net Sun Jun 27 16:50:45 2004 From: 24388.955485435 at www4.gmx.net (24388.955485435 at www4.gmx.net) Date: Sun, 27 Jun 2004 22:50:45 +0200 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: why? -------------- next part -------------- A non-text attachment was scrubbed... Name: dinner.zip Type: application/x-zip-compressed Size: 25479 bytes Desc: not available URL: From bodywracked at toons-x.com Sun Jun 27 21:36:14 2004 From: bodywracked at toons-x.com (Entire) Date: Mon, 28 Jun 2004 01:36:14 GMT Subject: Lisa & Maggie Simpson secretly make love with Homer Message-ID: And a wild bonus: want to touch Homer Simpson's dick?! Visit it on: HTTP://www.toontoon.com/ximpsons Then try http://www.toons-x.com/simpsons_family for extra pics of Marge and Bart drinking eachothers' sex juices. Self wrote in message news:LASHuDAdw2xU4reTS6Ex8j867OyB at toons-x.com... > > passing through him intermittently soaking in the sensation of the large puddles > > > ddx501s From nessus at mit.edu Wed Jun 23 16:56:10 2004 From: nessus at mit.edu (Douglas Alan) Date: Wed, 23 Jun 2004 16:56:10 -0400 Subject: Tkinter and "jumpiness" References: Message-ID: klappnase at web.de (klappnase) writes: > Douglas Alan wrote in message > news:... >> Is it possible to double-buffer frame rendering with Tkinter? I'm >> writing a GUI app using Tkinter and the GUI police around here are >> complaining about the interface being too "jumpy" at times. If I >> could have the frame rendered offscreen and only put onto the >> screen once it has completely finished being rendered, then this >> would solve the problem. > Have you tried useing wait_visibility() on the frame like this: > frame .wait_visibility(last_widget_that_is_created) > frame.pack() Hmmmm, I'm not sure that I see how this should work. As I understand wait_visibility(), it should wait until last_widget_that_is_created is displayed on the screen. But if the frame isn't yet packed, then neither last_widget_that_is_created nor the frame will *ever* appear on the screen, because wait_visibility() will forever wait for something that won't happen until the waiting has finished. I tried implementing your suggestion just to make sure that my understanding is correct, and it behaved just as I expected -- i.e., it didn't work. Is there some other more subtle usage of wait_visibility() that you have in mind? >> One culprit in the jumpiness is a megawidget that I am using that >> initially displays a scrollbar and then a fraction of a second later >> removes the scrollbar when it realizes that it is not necessary. > I had a similar problem with a widget with automatic scrollbars I > wrote; the fix that worked for me was not to pack() the scrollbar > within the mega-widget's __init__ method; That's a good idea -- thanks. I'd prefer not to modify the megawidget, if possible, though. It's third-party software, and then I'll have to worry about backporting my changes into it whenever I get new distributions. Also, the megawidget is not the only source of jumpiness, so it only fixes part of the problem. Since my original post, I've heard rumors that one can indeed get a Tkinter frame to double-buffer, but I haven't quite been pointed at the how to accomplish that. If that doesn't pan out, perhaps I'll have to resort to tweaking the megawidget, as you suggest. |>oug From mail at neumann-rosenheim.de Sun Jun 6 16:46:33 2004 From: mail at neumann-rosenheim.de (Christian Neumann) Date: Sun, 6 Jun 2004 22:46:33 +0200 Subject: AW: Problem with Python xrange In-Reply-To: Message-ID: <200406062046.i56KkW58010619@post.webmailer.de> Hello Robert! Sorry. It was my mistake! I read over this: "They don't support slicing" Thank you very much indeed! Christian Neumann -----Urspr?ngliche Nachricht----- Von: Robert Brewer [mailto:fumanchu at amor.org] Gesendet: Sonntag, 6. Juni 2004 22:04 An: Christian Neumann; python-list at python.org Betreff: RE: Problem with Python xrange Christian Neumann wrote: > I use Python 2.3.4 (final) and i think there is a bug > in the built-in function xrange(). > > An example is: > > x = xrange(2, 11, 2) ## [2, 4, 6, 8, 10] > > I get an TypeError if i use it with SliceType: > > x[1:4] ## It should be return an xrange object with length 3 > > Here is the error message: > > "TypeError: sequence index must be integer". Hm. I never noticed this either: >>> x = xrange(2, 11, 2) >>> x xrange(2, 12, 2) But back to your question. Anytime you use the word "should" in a bug report, you might guess it's really a feature request, not a bug. ;) Simply put, the "xrange type" doesn't support slicing like that. From the docs: http://docs.python.org/lib/typesseq.html "Xrange objects are similar to buffers in that there is no specific syntax to create them, but they are created using the xrange() function. They don't support slicing, concatenation or repetition, and using in, not in, min() or max() on them is inefficient." Robert Brewer MIS Amor Ministries fumanchu at amor.org From dmq at gain.com Tue Jun 22 20:19:32 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 22 Jun 2004 17:19:32 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: On Sun, 20 Jun 2004 14:48:23 -0400, "Colin J. Williams" wrote: >I have yet to wrap my mind around decorators. Decorators are very simple. They are just a way to provide different forms of methods, without introducing a new keyword, or some other more awkward syntax. Say you wanted to define a method that didn't have 'self' as its first argument. You could add a new keyword to the language: noself methodA(x,y): return x + y Or you could add a "decorator" to the existing syntax: def methodA(x,y) [noself]: return x + y Change 'noself' to 'staticmethod' and you have one of the current proposals in PEP318. Don't get distracted by 'staticmethod' and other mumbo-jumbo terminology, and you should have no problem with decorators. -- Dave From michele.simionato at poste.it Fri Jun 18 06:29:01 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 18 Jun 2004 03:29:01 -0700 Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> Message-ID: <95aa1afa.0406180229.28c5b1bf@posting.google.com> David MacQuigg wrote in message news:... > On Thu, 17 Jun 2004 11:05:58 GMT, Michael Hudson > wrote: > > >michele.simionato at poste.it (Michele Simionato) writes: > > > >> David MacQuigg wrote in message news:... > >> > I have what looks like a bug trying to generate new style classes with > >> > a factory function. > >> > > >> > class Animal(object): pass > >> > class Mammal(Animal): pass > >> > > >> > def newAnimal(bases=(Animal,), dict={}): > >> > class C(object): pass > >> > C.__bases__ = bases > >> > dict['_count'] = 0 > >> > C.__dict__ = dict > >> > return C > >> > > >> > Canine = newAnimal((Mammal,)) > >> > TypeError: __bases__ assignment: 'Mammal' deallocator differs from > >> > 'object' > >> > > >> > If I remove the 'object' from the class C(object) statement, then I > >> > get a different, equally puzzling error message: > >> > > >> > TypeError: __bases__ items must be classes > >> > > >> > The function works only if I remove 'object' from all base classes. > >> > > >> > -- Dave > >> > >> This is not a bug. The developers removed the possibility to change > >> the bases of a new-style class. > > > >Bad news for you: I put it back in for 2.3. > > > >If you read the error message, you'll notice that it's phrased to > >suggest that assignment to __bases__ is *sometimes* possible :-) > > > >David's assignment probably should work -- there's a bug on sf about > >this -- but there are definitely situations where assignment to bases > >*shouldn't* be allowed -- e.g. when the so-called 'solid base' changes > >-- but noone's put in the thinking time to make this precise in code. > >Being over-restrictive seems the better course. > > This may be just a documentation problem then. The error message is > definitely misleading. > > >However, newAnimal could be written like this: > > > >def newAnimal(bases=(Animal,), ns=None): > > if ns is None: > > ns = {} > > ns['_count'] = 0 > > return type('C', bases, ns) > > > >which > > > >a) doesn't use the name of a builtin as a variable > >b) doesn't suffer the 'mutable default arguments' problem > >c) is rather less insane > >d) actually works :-) (probably, haven't tested it) > > It works great. The only thing I would change is the return line, > making that > > globals()[name] = type('C', bases, ns) > > so we don't have to type the name twice when creating a new class. > I've also added an __init__ function. Using the factory is now very > easy: > > >>> newAnimal('Dog',(Mammal,)) > >>> dog1 = Dog() > Hello from __init__ in Dog > >>> Dog._count > 1 > > The main limitation I see in using a factory function like this, > instead of a metaclass, is that I can't customize the new animal as > easily, because I don't have an indented block like in a class > definition. I've got to call the newAnimal function, then add a bunch > of attributes one at a time, with fully-qualified names. > > Dog.temperature = 102 > Dog.pulse = 82 > Dog.respiration = 36 > > If I'm adding methods, it gets even messier, because I've got to > define functions at the module level, then assign them to attributes > of Dog, then maybe delete all the excess names from the module > namespace. > > I have one last question. In reviewing all the ways to solve the > problem of creating specialized classes, I see there is a function > new.classobj(name, bases, dict) which appears to do the same thing as > type(name, bases, dict). What is the purpose of classobj()? The name > is a little more self-explanatory than 'type', but using it requires a > module import. > > - Dave I heard somebody saying that the module 'new' will be deprecated at some moment. new.classobj returns old-style classes: >>> import new >>> new.classobj("C",(),{}) >>> type(_) whereas type returns new style ones. You can create oldstyle classes even without recurring to new.classobj. Michele Simionato From klachemin at home.com Thu Jun 24 10:50:13 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 07:50:13 -0700 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: <889cbba0.0406240650.6209fbb2@posting.google.com> Pierre-Fr?d?ric Caillaud wrote in message news:... > why don't you use translate to delete all the valid characters and test > if the resulting string is not not empty ? this will save you two calls to > len()... heh heh You're right, Pierre, that just might be more efficient! But I doubt those two 'len' calls would show up on a profiler, somehow. ;-) But you have to time it again, because the question becomes 'how efficient is the translate function at removing invalid characters from a string?' It might be much more efficient at removing one char, than at removing a thousand. So the timings would still be necessary, to make sure you're not optimizing the wrong part. The 'dict' solution proposed wouldn't work because the data I'm testing is in string form, and the overhead of translating the string to a dict before testing would swamp the results. So would using a set, because timings show a set is 4x slower than a dict. Unless I'm misunderstanding Peter's suggestion. Did you mean translating the string into a dict, then using a 'if boguschar in dict' test? From __peter__ at web.de Wed Jun 9 16:30:17 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jun 2004 22:30:17 +0200 Subject: How to write dos newline in unix? References: Message-ID: Inyeol Lee wrote: > Is there any simple way to dos-style newline (\r\n) in *nix environment, > not by writing "\r" explicitly? What I'm trying to do is; >>> class Translate: ... def __init__(self, dest): ... self.dest = dest ... def write(self, s): ... self.dest.write(s.replace("\n", "\r\n")) ... def __getattr__(self, name): ... return getattr(self.dest, name) ... >>> f = Translate(file("tmp.txt", "w")) >>> print >> f, "so what" >>> print >> f, "will this print?" >>> f.close() >>> file("tmp.txt").read() 'so what\r\nwill this print?\r\n' Simple enough? Peter From chfrag at central.ntua.gr Mon Jun 7 05:37:43 2004 From: chfrag at central.ntua.gr (Christodoulos Fragoudakis) Date: Mon, 07 Jun 2004 12:37:43 +0300 Subject: urllib.urlopen() freezes unexpectedly Message-ID: Hello everyone! Can someone help us with the following problem: We are performing an urllib.urlopen() in order to fetch a text file from a https server. Most of the time the function works as expected but every now and then it freezes because of an unexpected error. We do know that the problem is not a network error because the code is inside a try-except block and we don't get an exception. The program just freezes waiting for ever for the execution of the urllib.urlopen() line to stop. The relevant code fragment is the following: try: file_h = urllib.urlopen("https:///test.txt") except: print "Network Error" The server we are connecting to is creating a text file every 30 minutes which may be empty and immediately replaces the previous one. When the freezing situation occurs we found out that even a browser connection to the above url hangs also, waiting forever to display the file. How can we time the operation and stop it after a specified time interval? Do threads help and how? Any help will be greatly appreciated. From peter at engcorp.com Thu Jun 17 10:38:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jun 2004 10:38:40 -0400 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: David Turner wrote: > Peter Hansen wrote in message news:... >>Since it's therefore obviously not a property of these languages >>that they are robust or not, it must be something more to do with >>the programmers, or the process, or something. I guess... ;-) > > I don't see how the "obviously" bit follows. It was just that you've had non-robust code in Python and robust code in C++, while I've had the other way around. Therefore obviously it's not a property of the language, but more about how we're using them... something like that. -Peter From jussij at zeusedit.com Wed Jun 9 23:52:32 2004 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Thu, 10 Jun 2004 13:52:32 +1000 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfihFq4aunU1@uni-berlin.de> Message-ID: <40C7DB00.7B71@zeusedit.com> Claudio Grondi wrote: > I wonder why the subject (Python scripting within HTML) is > not occuring in any past postings - do I miss something > very obvious? > > ... snip ... > > I have the latest Python 2.3.4 installed. > What do I wrong? You can only run Windows Scripting Host (WSH) languages inside the MSIE browser. By default Windows only has VB Script and JavaScript WSH scripts installed. So if you want to run Python you will need to install a WSH version of Python. I think ActiveState provide a WSH version of Python. Jussi Jumppanen Author of: Zeus for Windows (All new version 3.92 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From imbosol at aerojockey.invalid Mon Jun 14 04:24:37 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 14 Jun 2004 08:24:37 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <9hdzc.93679$DG4.801@fe2.columbus.rr.com> Richard James wrote: > What points are the Scriptometer survey missing, in regards to the > ease of use and beauty of the Python language? Everything. It's definitely one of the most useless side-by-side comparisons I've ever seen. The program lengths criterion is ridiculous. It rewards Perl for using unreadable line noise. (Since when does Perl have an interactive interpretter?) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From klachemin at home.com Sun Jun 27 14:27:42 2004 From: klachemin at home.com (Kamilche) Date: 27 Jun 2004 11:27:42 -0700 Subject: Python Magazine exists! (was: Python intro questions) References: <40deae5e$0$65807$e4fe514c@news.xs4all.nl> Message-ID: <889cbba0.0406271027.39b3044@posting.google.com> Irmen de Jong wrote in message news:<40deae5e$0$65807$e4fe514c at news.xs4all.nl>... > ...So, I'm sorry to say this but my experience with the new Pyzine > is not too good. Wow, that's not good, thanks for sharing that information with us. The heck of it is, people probably WOULD write articles for their magazine for their preferred set price (read: FREE!) if they would give them even a magazine subscription in return. But that's a total gyp, instead. Sorry to hear that you wasted your time! --Kamilche From jepler at unpythonic.net Thu Jun 3 09:54:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 3 Jun 2004 08:54:49 -0500 Subject: Optimizing multiple dispatch In-Reply-To: References: Message-ID: <20040603135449.GG19278@unpythonic.net> Avoding map() may help: tuple([type(a) for a in args]) Using generator expressions (aren't they in 2.4?) might or might not help: tuple(type(a) for a in args) You could write a small extension to perform this operation without all the Python function calls. cdef extern from "Python.h": extern int PyTuple_Check(object) extern object PyTuple_New(int) extern int PyTuple_GET_SIZE(object) extern void *PyObject_Type(void*) extern void PyTuple_SET_ITEM(object, int, void*) extern void *PyTuple_GET_ITEM(object, int) def maptype(i): if not PyTuple_Check(i): raise TypeError cdef int l cdef int j l = PyTuple_GET_SIZE(i) o = PyTuple_New(l) for j from 0 <= j < l: PyTuple_SET_ITEM(o, j, PyObject_Type(PyTuple_GET_ITEM(i, j))) return o >>> print maptype.maptype(("", 0, 0.0, 0L, str, int, type)) (, , , , , , ) $ timeit -s 's = ("", 0, 0.0, 0L, str, int, type); from maptype import maptype' 'maptype(s)' 100000 loops, best of 3: 2.41 usec per loop $ timeit -s 's = ("", 0, 0.0, 0L, str, int, type)' -s 'def maptype(s): return tuple([type(i) for i in s])' 'maptype(s)' 10000 loops, best of 3: 25.3 usec per loop $ timeit -s 's = ("", 0, 0.0, 0L, str, int, type)' -s 'def maptype(s): return tuple(map(type, s))' 'maptype(s)' 100000 loops, best of 3: 17 usec per loop ... hmm, map is faster than listcomp. my mistake! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From oliver.schoenborn at utoronto.ca Mon Jun 7 23:34:08 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Mon, 7 Jun 2004 23:34:08 -0400 Subject: Destructors and exceptions References: Message-ID: "David Turner" wrote in message news:e251b7ba.0406070651.1c98c09d at posting.google.com... > > The problem is that when an exception is raised, the destruction of > locals appears to be deferred to program exit. Am I missing > something? Is this behaviour by design? If so, is there any reason > for it? The only rationale I can think of is to speed up exception > handling; but as this approach breaks many safe programming idioms, I > see it as a poor trade. There is no Python equivalent of C++'s "destructor garanteed to be called upon scope exit", for a couple of reasons: scope exit only destroys references to objects, not the objects themselves; destruction of objects is left to the garbage collector and you have no influence on it. In particular, the gc is not required to release resources, so finalizers (the __del__ method, closest to C++'s destructor) may not get called. This means __del__ is pretty much useless (AFAIMC), and you can't rely on them being called before program exit (or ever, for that matter). I agree, it is a real pitty that Python doesn't have a way of doing what you mention, other than try-finally, which makes code more difficult to read. A new specifier, e.g. "scoped", would be a required addtion to Python: interpreter would garantee that __del__ of scoped objects would be called on scope exit, and raise an exception if attempt to alias. Oliver From j_mckitrick at bigfoot.com Tue Jun 8 09:53:07 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 8 Jun 2004 06:53:07 -0700 Subject: Encapsulation and GUIs Message-ID: I'm porting an app from tkinter to PyGTK, and I'm taking the opportunity to refine the design. For example, I have 3 dictionaries of settings, or preferences, that are all adjusted in one dialog. >From an encapsulation standpoint, am I better off extracting the options from the dictionary, setting each to the dialog, then gathering them all at the end and updating the options dictionaries? Or, is it better to pass dictionaries into the dialog, update them there, then pass them back? Option 1 obviously is more encapsulated, but option 2 seems more extensible as I add options to the dictionaries. jonathon From tim.peters at gmail.com Fri Jun 25 14:08:19 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 25 Jun 2004 14:08:19 -0400 Subject: [python] using try: finally: except In-Reply-To: References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> Message-ID: <1f7befae0406251108cba5c5d@mail.gmail.com> [Tim Peters] >> It's more that Guido deliberately separated them. Before Python >> 0.9.6, you could attach both 'except' and 'finally' clauses to the >> same 'try' structure (see Misc/HISTORY in a Python source >> distribution). I don't remember the semantics, and that was indeed >> the problem: nobody could remember, and half the time guessed wrong. [Peter Hansen] > I'm curious: was it that the order of execution was fixed, regardless > of the order of the 'finally' and 'except' in the source, or was > it still confusing even though the order of execution changed > logically with the order of the statements in the source? If present, a 'finally' clause had to be the last clause in a try/except/finally structure. That was enforced by the syntax. The most common confusion was over whether the code in the 'finally' clause would execute if an exception was raised during execution of an 'except' clause. That code isn't in the 'try' block, so why should 'finally' apply to it? For that matter, why shouldn't it? That's why nobody could remember (and I in fact don't remember what happened then). From peter at semantico.com Thu Jun 24 12:29:21 2004 From: peter at semantico.com (Peter Hickman) Date: Thu, 24 Jun 2004 17:29:21 +0100 Subject: eZ80 - correction [z80 vs Python thread] In-Reply-To: References: Message-ID: <40db0161$0$29542$afc38c87@news.easynet.co.uk> Perhaps you could look at the pippy project which is python on a PDA. They will have had to shrink python down, maybe you could use that as a starting point. From jacek.generowicz at cern.ch Tue Jun 8 03:42:55 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Jun 2004 09:42:55 +0200 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman writes: > There are very few 'pure' interpreted languages. Well, every native machine language is purely interpreted, for a start. > If you want pure speed you need assembler! No ifs, ands or buts. Lots of "if"s and "but"s actually. While it is theoretically possible to write any program you want, in some assembly language, and to write it in a way which overcomes some low-level inefficiencies introduced by higher-level languages, in practice you won't find many people writing efficent large-scale programs in assembler. Higher-level, more expressive, languages allow you to try out different approaches more easily. Getting the architecture of your program right, is far more important for overall speed of execution that the low-level details are. From lesstif-admin at lesstif.org Sat Jun 12 02:23:26 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Sat, 12 Jun 2004 06:23:26 -0000 Subject: Request to mailing list Lesstif rejected Message-ID: Your request to the Lesstif mailing list Posting of your message titled "Mail Delivery (failure lesstif at lesstif.org)" has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From tjreedy at udel.edu Wed Jun 9 07:04:19 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jun 2004 07:04:19 -0400 Subject: fast list search? References: Message-ID: "Thomas Guettler" wrote in message news:pan.2004.06.09.10.22.54.20397 at thomas-guettler.de... > Am Wed, 09 Jun 2004 11:49:19 +0200 schrieb ramon aragues: > > > Hi, > > > > I?ve got a list with more than 500,000 ints. Before inserting new ints, > > I have to check that it doesn?t exist already in the list. > > > > Currently, I am doing the standard: > > > > if new_int not in long_list: > > long_list.append(new_int) > > > > > > but it is extremely slow... is there a faster way of doing this in python? > > Hi, > > Use a dictionary instead of the list: > > if not long_dict.has_key(new_int): > long_dict[new_int]=1 Or use a set, which I believe will be faster (more C-coded) in 2.4. That eliminates the dummy value. TJR From peufeu at free.fr Fri Jun 18 04:52:07 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 10:52:07 +0200 Subject: very large dictionaries References: Message-ID: From what I understand... - The match table is static (or does not changes often) - Your input data changes every time (so you don't want to load it in a postgres database everytime) Your problem : - read the input data. - for each input row, generate several keys - lookup each key in the match table - take appropriate action My solution : - read the input data. - for each input row, generate several keys - save the keys in a file (tempfile) in this format : (key, record id) Generate tempfile in partitions : Generate N tempfiles which will each contain a partition of the keys. - For each tempfile : - Load it (you chose a number of partitions such that the files fit into about 1/4 your RAM.) - group by keys (dict( key: [record ids] )) again it fits into RAM. Record IDs are already sorted because they were generated this way. - sort on keys (again, fast because it fits in RAM) Now you have a sorted keyset which you want to lookup into a match table, which is ALSO sorted (you sorted it beforehand because it doesn't change often). Now start a key_pointer at the beginning of your key list, and a match_pointer at the beginning of your match table. You are basically comparing two sorted lists. This does not involve any search, rather a very simple algorithm. Your match table is not partitioned. If key_pointer.key < match_pointer.key: advance match_pointer elif key_pointer.key > match_pointer.key: advance key_pointer if at end of your tempfile partition, load the next one and sort it. elif key_pointer.key == match_pointer.key: you have a match. record id. What do you think ? I already used this algorithm and it's very powerful. > Let me specify further. Our actual data is enormous, and tests with > Postgres and MySQL indicate that the time taken just to build a single > index is on the order of hours, which is too long. After analysis we > believe that the important lookup info can be compressed to about 40 > million records of 48 bytes each. Furthermore, we have the flexibility > to partition this into four somewhat equal parts. Each will hence be > about 460MB in size. Even with structural overhead I see no reason > this couldn't fit into memory. This is our match file. > > Our process involves taking an input disk file, and traversing it one > record at a time. This we can sort by the same partition criteria used > to split the match file (so that each match file can be loaded but > once). For each input record we build a series of keys and compare > them to the appropriate match file; thus there are multiple lookups > per input record. An algorithm then determines which match record we > wish to pick and we write an ID to the input. > > There is more to it than this, but these are the major elements. The > input table may be millions of records long, but likely will be much > smaller. > > The total processing time will be a sum of: > time to sort/index input file > time to traverse input file > time to load in all parts of the match table > time to build keys on input records > time to search match table for each key > time to write match key ID > overhead time of routine > > A new wrinkle is that the match table may have duplicate keys, so > storing it as a dictionary is not an option. > > The data is alphanumeric. > > Assume an arbitrarily powerful computer, since adding a GB of RAM is > not an issue. > > The question I had, for those with experience with large data sets, is > what structure would best handle this problem? > > -- robin -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From eddie at holyrood.ed.ac.uk Thu Jun 17 07:18:58 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 17 Jun 2004 11:18:58 +0000 (UTC) Subject: Parsing ascii file References: Message-ID: "diablo" writes: >Hello , >I have a file that contains the following data (example) and does NOT have >any line feeds: >11 22 33 44 55 66 77 88 99 00 aa bb cc >dd ....to 128th byte 11 22 33 44 55 66 77 88 99 >00 aa bb cc dd .... and so on >record 1 starts at 0 and finishes at 128, record 2 starts at 129 and >finishes at 256 and so on. there can be as many as 5000 record per file. I >would like to parse the file and retreive the value at field at byte 64-65 >and conduct an arithmetical operation on the field (sum them all up). >Can I do this with python? >if I was to use awk it would look something like this : >cat | fold -w 128 | awk ' { SUM=SUM + substr($0,64,2) } END >{print SUM}' You can use stdin.read(128) to get consecutive records and slicing to extract the fields. Something like: from sys import stdin sum = 0 while True: record = stdin.read(128) if not record: break sum += int(record[64:65]) print sum Frankly, I'd stick with the Awk version unless it's a pedagogical exercise. Actually I'd go further and have a script that simplys sums up all the numbers in the input and add 'cut' into the pipeline to extract the columns first. Eddie From dev-python at smartology.nl Thu Jun 3 06:02:41 2004 From: dev-python at smartology.nl (Remy C. Cool) Date: Thu, 3 Jun 2004 12:02:41 +0200 Subject: Import weirdness Message-ID: <200406031202.41742.dev-python@smartology.nl> Hello, A couple of months ago, I posted a question related to the same problem, but didn't get any replies. I've created a ugly workaround but still would like to get some insight on the matter. Case: XMLRPC client imports modules and packages from a XMLRPC server. Method used: path_hooks See PEP302 - http://www.python.org/peps/pep-0302.html Basic layout of the importer class: class RemoteImporter: def __init__(self, path): self.path = path if path.split('.')[0] not in self.pathlist: raise ImportError def find_module(self, fullname, path=None): print 'FIND MODULE:', fullname self.package, self.code = self.server.import(fullname) if self.code: self.request_path = fullname.split('.') return self def load_module(self, fullname): print 'LOAD MODULE:', fullname path = self._get_code(fullname) # create new module mod = imp.new_module(fullname) mod.__file__ = "<%s>" % fullname mod.__loader__ = self mod.__path__ = path # register with sys.modules sys.modules[fullname] = mod # exec exec self.code in mod.__dict__ return mod def _get_code(self, fullname): if len(self.request_path) > 1: _fname = '.'.join(self.request_path[0:-1]) return self._get_subfile(fname, self.request_path[-1]) del fname else: return self._get_archive(self.request_path[-1]) def _get_archive(self, modname): # assemble path if self.package: path = ["%s" % self.fullname] else: path = [] # return results return path def _get_subfile(self, parent, modname): # assemble path if self.package: path = ["%s.%s" % (parent, modname)] else: path = [] # return results return path Note: pathlist contains ie: ['mymodules', 'RemoteImporter'] In the xmlrpc client app I have: import mymodules The package mymodules get's imported and modules contained in mymodules wil also be imported. One of the problems is that when I want to import modules in other modules contained in the package. Example: mymodules __init__.py module_1.py module_2.py module_3.py When I use the line: 'import module_2' in module_1.py, the 'fullname' as printed by find_module is not mymodules.module_2 but only module_2. Without the base, the module can't be found. It is solvable by prefixing imports with 'mymodules' like 'import mymodules.module_2', but that is not a portable solution since the name 'mymodules' could change. Is this behavour a bug? < Remy > From michael at foord.net Mon Jun 21 10:03:02 2004 From: michael at foord.net (Fuzzyman) Date: 21 Jun 2004 07:03:02 -0700 Subject: How to make an immutable instance References: Message-ID: <8089854e.0406210603.1c24a130@posting.google.com> "Batista, Facundo" wrote in message news:... > [Tim Peters] > > #- When/if Decimal is recoded in C, it will be easy to make it "truly > #- immutable". If you think you have to try in Python anyway, then yes, > #- read-only properties are the intended way to get an idiot-resistant > #- approximation to immutability. > > I particully don't care. But that was an specification from the original > pre-PEP (just to use it as key in dictionaries). > > I'm +0 to take out that request from the PEP. > > . Facundo If you want to use something as a dictionary key isn't the requirement that it be hashable, rather than immutable.... (Which means you should at least attempt to prevent people changing the value I guess....) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From light at soton.ac.uk Mon Jun 28 10:17:42 2004 From: light at soton.ac.uk (Mark Light) Date: Mon, 28 Jun 2004 14:17:42 +0000 (UTC) Subject: html POST in python Message-ID: Hi I am trying to "post" a file to a webpage and save the output as a file. I have looked at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 which seems to have several suggestions - my problem is my lack of knowledge of html forms. The active part of the webpage form in question is below - how would I feed this information into one of the python scripts from the cookbook examples. Also would I need to do something about handling the result? I have a plain text file in a location say "c:\temp\file.cif" """"
    File name:


    """" Any advei would be very useful to me. Mark. From Mike at DeleteThis.Geary.com Tue Jun 29 09:50:46 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 29 Jun 2004 06:50:46 -0700 Subject: Does Python optimize regexes? References: Message-ID: <10e2stn38qc19ec@corp.supernews.com> Peter Otten wrote: > Python puts the compiled regular expressions into a cache. The relevant > code is in sre.py: > > def match(pattern, string, flags=0): > return _compile(pattern, flags).match(string) > > ... > > def _compile(*key): > p = _cache.get(key) > if p is not None: > return p > ... > > So not explicitly calling compile() in advance only costs you two function > calls and a dictionary lookup - and maybe some clarity in your code. That cost can be significant. Here's a test case where not precompiling the regular expression increased the run time by more than 50%: http://groups.google.com/groups?selm=10b48qllaagcr11%40corp.supernews.com -Mike From greg at cosc.canterbury.ac.nz Mon Jun 14 06:36:51 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 14 Jun 2004 22:36:51 +1200 Subject: ANN: PyGUI 1.3 released (Greg's Pythonic GUI Framework) Message-ID: PyGUI (Greg's Pythonic GUI Framework) Version 1.3 ================================================= Some of you may remember the project I started a few years ago to define a pythonic GUI API for implementation on multiple platforms. I didn't make much progress on it for a while, but the project wasn't dead, just resting. Following a recent burst of activity, I am now pleased to announce the release of version 1.3. This release marks a milestone in the development of PyGUI, because, for the first time, implementations for two platforms are included: * MacOS X, via Carbon * Linux, via Gtk The Gtk implementation should also be usable on other Unix/X11 systems, or on Windows, if suitable libraries are installed. Download from here, or read the documentation online: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ Note: This version is not quite complete yet; support for images is missing, and a few classes remain to be documented. I expect to remedy these things soon. Greg Ewing greg at cosc.canterbury.ac.nz From flupke at nonexistingdomain.com Tue Jun 15 07:49:48 2004 From: flupke at nonexistingdomain.com (flupke) Date: Tue, 15 Jun 2004 11:49:48 GMT Subject: (OT) Boa Constructor and Python 2.3.4 References: Message-ID: "Lothar Scholz" schreef in bericht news:hajtc01o1it4ss4npcu5ba6045j7thuvkh at 4ax.com... > On Tue, 15 Jun 2004 10:15:39 GMT, "flupke" > wrote: > > >Hi, > > > >My wxPython is version 2.5.1.5u. > >Any ideas? > > > > AFAIK the CVS version only works with wyPython 2.4. Hhhmm. Bummer. I wanted to use it to quickly get a wxPython app going as i'm pretty new to Python & wxWindows. Well, i guess i can also "type" :) Are there any other screen designers (i've tried wxGlade but it seems a bit limited) Benedict From peter at engcorp.com Sun Jun 20 08:08:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jun 2004 08:08:42 -0400 Subject: Watershed Python Versions In-Reply-To: References: <40dd3107.0406191120.6879a1c6@posting.google.com> <40D4BBFF.7030508@v.loewis.de> Message-ID: Dennis Lee Bieber wrote: > On Sun, 20 Jun 2004 00:19:43 +0200, "Martin v. L?wis" > declaimed the following in comp.lang.python: > > >>Why "almost"? I have used NT 3.1 in '93 or so. There was no mentioning >>of a DOS-based Win32 implementation except for Win32s at that time, and >>NT was considered the successor, to both Win3.1 and OS/2. NT predates >>Win 3.11. >> > > The changes that took place from NT3.x to 4.x make NT4 almost as > great a change as that from WfW3.11 to W95... > > So... to me, NT didn't really "take" until 4.x NT didn't 'take' until Windows XP... From jjl at pobox.com Tue Jun 1 15:28:03 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2004 20:28:03 +0100 Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> <87hdtzeanw.fsf@pobox.com> <87y8n9bej9.fsf@pobox.com> <2pfob0d54qrj0gmav4o1v6r2a215bahgvp@4ax.com> Message-ID: <87llj7dqnw.fsf@pobox.com> Manlio Perillo writes: > On 31 May 2004 01:56:10 +0100, jjl at pobox.com (John J. Lee) wrote: [...] > >> This is very simple to do with httplib and Cookie modules, so why to > >> use more involved modules? > > > >No reason at all if you're happy with it, of course. That was what my > >"Cool" was meant to communicate. [...] > Of course I agree with you for all other cases, but there exist > programs that really needs only low level library. Was that not what I said? Sorry if I'm not making myself clear! (What follows is unrelated to your (quite unnecesary!) extended defence of your use of Cookie in your script, but just by the way of commentary on the points you make) > Actually, ad example, standard Cookie module is low level. Yes. The low-level stuff it does is not not always the right thing for client-side code, though. > It only parses key=value pairs, and, more important, it is 'other > library' neutral. [...] Same goes for ClientCookie. The interface required of request and response objects is defined in the docs. For doing what ClientCookie does (automatic cookie handling), I don't think it can get much simpler. John From kveretennicov at yahoo.com Mon Jun 21 07:11:39 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 21 Jun 2004 04:11:39 -0700 Subject: Another MSIE Python Question References: <22b7fd40.0406190617.a33514@posting.google.com> Message-ID: <5155aad2.0406210311.697e3c8f@posting.google.com> r.gable at mchsi.com (Ralph A. Gable) wrote in message news:<22b7fd40.0406190617.a33514 at posting.google.com>... > I am opening MSIE6 with this code: > > ie=Dispatch('InternetExplorer.Application.1') > ie.Navigate(url) > while ie.Busy: > time.sleep(0.1) > ied=ie.Document > while ied.ReadyState != 'complete': > time.sleep(0.1) > > ieh=ied.documentElement.outerHTML > I have tried your code as is (added imports, of course) and it worked. IE didn't show up in taskbar, url was loaded and outerHTML contained, well, HTML :) Test environment: Win2k, MSIE 6 and ActivePython 2.3. - kv From peter at engcorp.com Tue Jun 22 21:41:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Jun 2004 21:41:15 -0400 Subject: Stopping a thread from another one In-Reply-To: References: Message-ID: <-pednXsY4IgmQkXd4p2dnA@powergate.ca> Fabiano Sidler wrote: > I would prefer, if I end the subthreads by the main thread. > Is there any chance? The usual idiom is something like this: class StoppableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self._running = False def stop(self): self._running = False def run(self): while self._running: # do stuff here that loops periodically to allow # the flag to be checked Then from the main thread you can keep track of the child threads and do xxx.stop() on each of them, then an optional threading.Thread.join() call (check the docs for that). This can be made more sophisticated as required. -Peter From r.gable at mchsi.com Thu Jun 10 17:41:44 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 10 Jun 2004 14:41:44 -0700 Subject: MSIE6 Python Question References: Message-ID: <22b7fd40.0406101341.6f9c83b9@posting.google.com> All you guys have given me some super info. I have this problem under control (with your help). I really appreciate it. Keep up the good work. Ralph A. Gable "Andy Baker" wrote in message news:... > The site might be checking your user-agent string. Urllib must allow you to > choose what browser to identify itself as. Simply match the user-agent of > known version of IE and see if that works. > > > -----Original Message----- > > From: python-list-bounces+andy=andybak.net at python.org > > [mailto:python-list-bounces+andy=andybak.net at python.org] On > > Behalf Of Ralph A. Gable > > Sent: 24 May 2004 12:25 > > To: python-list at python.org > > Subject: Re: MSIE6 Python Question > > > > "Kevin T. Ryan" wrote in message > > news:<40b1697d$0$3131$61fed72c at news.rcn.com>... > > > Ralph A. Gable wrote: > > > > > > > I'm a newbie at this but I need to control MSIE6 using Python. I > > > > have read the O'Reilly win32 python books and got some > hints. But I > > > > need to Navigate to a site (which I know how to do) and > then I need > > > > to get at the source code for that site inside Python (as > when one > > > > used the > > > > View|Source drop down window). Can anyone point me to > some URLs that > > > > would help out? Or just tell me how to do it? I would be very > > > > grateful. > > > > > > I'm not sure why you need to go through IE, but maybe this will get > > > you into the right direction: > > > > > > >>> import urllib > > > >>> f = urllib.urlopen('http://www.python.org') > > > >>> f.readline() > ' > > >>> f.readline() > ' "http://www.w3.org/TR/html4/loose.dtd" >\n' > > > >>> > > > > > > You could do: > > > for line in f: > > > process(line) > > > > > > just like you can with a file. Check the urllib, urllib2, > and other > > > related modules (maybe httplib). Hope that helps. > > > > > > Sorry. I forgot to mention that I have tried that. The data I > > want is being stripped out when I access the URL via urllib. > > I CAN see the data when I go into IE and do view source but > > when I use urllib the site intentionally blanks out the > > information I want. For that reason, I would like to get it > > using IE6 if I can. If there are other ways to fake out the > > site, I would be interested in that also. I thought that > > perhaps the site was detecting the fact that I was not > > querying it using a browser. I tried putting that into into > > the HTTP messages but may not have done it right. At any rate > > couldn't get that to work. It may be that the site is using > > cookies to be sure someone is not getting the data. I haven't > > pursued that. Again that is another reason I wanted to use > > IE6 (since I know it works). The data is on a site to which I > > subscribe to a service. But the particular information is > > available to anyone if he/she types in the url (as long as > > you are using a browser). > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From jacek.generowicz at cern.ch Thu Jun 10 06:49:39 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jun 2004 12:49:39 +0200 Subject: Recoding closures in C Message-ID: Following on from my "Optimizing multiple dispatch" question last week: Thanks to those who offered suggestions: recoding tuple(map(type,args)) in C gives me a 20% speed improvement in "The Politically Important Benchmark". Now, in reaity, my code looks a bit more like this [though, still, I am bending the truth siginificantly, in order to hide irrelevant domain-specific details]: class MethodCollection: ... def getMethod(dispatcher_self): def dispatching_method(self, *args): the_method = dispatcher_self.methods[tuple(map(type,args))] return the_method(*args) return dispatching_method [Which is then used in a way which is broadly similar to this: Foo_bar = MethodCollection() Foo_bar.add_method(this) Foo_bar.add_method(that) Foo_bar.add_method(the_other) ... Foo = type('Foo', (object,), {'bar': Foo_bar.getMethod()}) ] Now, "The Politically Imoprtant Benchmark" calls various incarantions of dispatching_method in its inner loop (and the methods contained by dispatching_method don't do much work), so I suspect that I could get meaningful speed improvements by recoding dispatching_method in C. However, note that it's a closure over dispatcher_self. The most obvious way of doing this, seems to be to implement dispatching_method as an extension type, with a tp_call slot which implements the body of the original dispatching_method. Any advice, comments, warnings ? As an added complication, I would like the help for any given dispatching_method incarnation to display the signatures of the methods it holds. That's pretty easy in pure Python, but can it be done if dispatching_method is written in C, (bearing in mind that dispatching_methods are being created at run-time) ? From bvande at po-box.mcgill.ca Tue Jun 29 01:27:50 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 29 Jun 2004 01:27:50 -0400 Subject: Simple Practice Programs In-Reply-To: <8MKdnWKtOvt9c33dRVn-hQ@powergate.ca> References: <2004062816162375249%brianmartin@gmailcom> <8MKdnWKtOvt9c33dRVn-hQ@powergate.ca> Message-ID: <40E0FDD6.8060505@po-box.mcgill.ca> Peter Hansen said unto the world upon 29/06/2004 00:23: > Brian Martin wrote: > >> If I have gone through several beginner python tuts and understand >> basics, what's next? >> It seems there are very many very beginning tutorials but after that >> there is a large absence as far as tutorials. Any suggestions for a >> simple program to write? > > > The best simple program to write is always (IMHO) the one which > actually gives you back some value. What do _you_ want to use > your programming skills for? Pick some particular task that you > want to automate (CD collection, waking you up in the morning, > whatever) or a game idea you have or the world's Next Great > Editor or something, and start writing it. > > A couple of universal truths exist though: > > 1. You won't actually ever finish it. Don't let that stop you. > > 2. You'll learn an awful lot more than if you just follow > someone else's idea of what I envision you mean by "practice program". > Hi all, Unlike Peter, I count my programming experience in months, not years. :-) The advice above (and the snipped alternative, too) seem good counsel. At first, though, many of the things that I would want to be able to program seemed a bit too big to me. If that is where you are, I'd suggest you pick one or two (reasonably) small things on your computer that bug you and make them better. I at least was helped by aiming at a few fairly small such tasks. An example from my learning: I have a proprietary information management application which exports files to a multi-directory HTML file system. The HTML is really messy, defaults to opening links in new browser, and a bunch of other stuff that bugs me. So I wrote a Python script to walk the tree and fix the HTML, etc. issues. I learned a lot. (Enough so I now have taken on one of the sort of "you are not going to finish that" projects that Peter recommends.) A task where you can learn a few aspects rather than try to mix together all the things you've read about is what helped me anyway. Last, in case you didn't know, there is a similar thread on the Tutor list right now. (And if you are learning, that's a good list to read and post to; very patient folks :-) Best to all, Brian vdB From peter at engcorp.com Mon Jun 21 20:52:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 20:52:28 -0400 Subject: windows/python compatability In-Reply-To: <1a00439d.0406211538.52097044@posting.google.com> References: <1a00439d.0406211538.52097044@posting.google.com> Message-ID: kluge wrote: > i'm a newbie to python. i'm learning to program and wanted to know how > to tell which version of windows my finished python program will work > on. thank you. That will depend somewhat on what features it uses... but for the most part *any* currently available version of Windows will run it just fine, as well as probably any version of Windows 98 since the second edition was released, and possibly even the first one. The only real requirement is that Python will have to be installed on whatever machine tries to run it. If that's a problem, you can also investigate "py2exe" and use it plus a nice free installer program (like InnoSetup) to build an installer that anyone could use to install your program, without having to deal with a Python download and such. -Peter From claird at lairds.com Thu Jun 3 14:18:49 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 18:18:49 -0000 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: <10buqs9pgco8vf4@corp.supernews.com> In article <2i96n6Fklj78U2 at uni-berlin.de>, Reiner Block wrote: >Hi, > >does anybody knows a really good Python reference? It is not the matter if it >is online or a book, if it is in english or german. Because the official one >from www.python.org is really bad. :-( . . . When you provide more description about how is "bad", then others will understand better what you seek, and will be able to help you find "a really good Python reference" more accurately and efficiently. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Mon Jun 14 11:34:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 11:34:18 -0400 Subject: Searching for the best scripting language, In-Reply-To: <40cdc47a$0$20179$afc38c87@news.easynet.co.uk> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <40cdc47a$0$20179$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > Take it this way, if someone showed you some badly written Python would > that put you off Python? I'm waiting to see anyone succeed at writing Python code that badly. I'd argue that it's not possible, unless one is deliberately trying to make Python look bad. (Note: I'm not saying people don't write really poor Python code, or even code that looks awful. I am saying that I don't think even the worst that I've seen would actually have made me say "Ugh, Python must suck!" as a result, if I didn't already know what Python was really like.) -Peter From mwh at python.net Wed Jun 2 05:54:43 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 2 Jun 2004 09:54:43 GMT Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> Message-ID: Alexander Schmolck writes: > Scott David Daniels writes: > > > Calvin Spealman wrote: > >> ... > >> Have to admit tho, a continue feature might be useful. Some languages have > >> this, don't they? The thing is, Where exactly to continue? Should you retry > >> whatever raised the exception, continue just after it, at the beginning of > >> that line, or what? > >> > > See this older thread: > > > > > > Xerox's experience (in deliberately removing the "continue from > > exception" language feature) I found very instructive. > > Did this language support working interactively? If so I'd be pretty surprised > to hear that no one found it useful to be able to manually fix things and > continue execution; not being able to do so is presumably my number one gripe > with python [1] -- it annoys me no end if I need to start an expensive > computation from scratch because some trivial and easily fixable problem > occured towards the end of the computation (sometimes it is possible to > salvage stuff by hand by pickling things from the appropriate post-mortem > frame, but I'd *much* prefer being able to say: foo=some_value; resume). I'd like this too. It might be quite hard to implement non-disruptively but I haven't thought about it too hard. Would make an excellent project for a master's thesis, IMHO. > Footnotes: > [1] Number 2 would be the stupid try: finally: idiom which also seems to > screw up tracebacks ? > (which has occasionally led me to get rid of them completely > while debugging -- surely not a good thinge). My other gripes > are again related to python's limitations for interactive > software development -- I rather like python, but I really wish > it did that better. What do you mean here, specifically? I find I can do interactive development in Python most of the time (I do wish it was more possible with PyObjC, though). Cheers, mwh -- I think perhaps we should have electoral collages and construct our representatives entirely of little bits of cloth and papier mache. -- Owen Dunn, ucam.chat, from his review of the year From qrczak at knm.org.pl Tue Jun 15 18:34:01 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Wed, 16 Jun 2004 00:34:01 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: On Tue, 15 Jun 2004 15:07:05 -0700, Mark Hahn wrote: > Choice 2 is my favorite in that it matches the dynamic nature of Prothon, > but it is an expensive solution. Choice 1 is the least expensive solution > but it is limiting to the user. Choice 1 does not help the second code > sample above. Choice 3 is a good compromise since an object.copy() is > pretty fast in Prothon. > > Comments? How much Python code would these different proposals break? I like 2 the most. Well, actually I like only 2 :-) I'm not sure why it would be expensive, it's a pity if it's expensive, but it should be appropriate for most cases and it's easy to understand. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From nc-jantzegu at netcologne.de Thu Jun 17 20:42:11 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Fri, 18 Jun 2004 02:42:11 +0200 Subject: Easiest way to port Python program to PDA References: Message-ID: And surely you find OpenEmbedded on the OpenZaurus site - with an actual Metadata for Python http://openembedded.bkbits.net:8080/packages/src/python?nav=index.html|src/. (I just followed the links - can't give further explanations now) From http Tue Jun 29 02:32:30 2004 From: http (Paul Rubin) Date: 28 Jun 2004 23:32:30 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: <7xacymeuwx.fsf@ruckus.brouhaha.com> "Mark Hahn" writes: > Yes, a Prothon identifier is the same as a Python identifier except that it > can end with an exclamation mark ( ! )or a question mark ( ? ). These marks > can only appear at the end and there can only be one. It is up to the > programmer to make sure he/she uses them properly. How do you parse a!=b From jimka at rdrop.com Tue Jun 8 02:12:22 2004 From: jimka at rdrop.com (Jim Newton) Date: Tue, 08 Jun 2004 08:12:22 +0200 Subject: how to use __str__ and __repr__? In-Reply-To: <7P6dnaLiT8YikVjdRVn-hQ@powergate.ca> References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9mdFnvcsbU2@uni-berlin.de> <7P6dnaLiT8YikVjdRVn-hQ@powergate.ca> Message-ID: <2il6tmFo4tkpU2@uni-berlin.de> hmm, even when i change it to calling str() rather than __str__() it does not work. class another: pass print another() # works another().str() # does not work does anyone know why? -jim Peter Hansen wrote: > Jim Newton wrote: > >> i read that in the documenation. and i assumed from that that >> print another() >> actually prints the string returned from another().__str__() >> and thus __str__ must be being inherited from the superclass >> of another, but apparently print does something different. >> >> why does print another() actually print something rather than >> complaining that there is no __str__ defined? > > > I believe print basically calls str(obj) on the object, and > str() is a builtin which (I believe) basically tries to call > __str__() and if that is not defined, calls __repr__(). If > __repr__ is not defined, it probably defers to a standard > representation based on the id() of the object, which is > always defined. > > Not sure what else you're trying to do (I haven't read your > full post) but I believe this and some thought should answer > for pretty much everything you're seeing. > > Note that you should probably never call __str__() directly, > but call the str() builtin instead. Same for __repr__() > versus the repr() builtin. > > -Peter From miki.tebeka at zoran.com Thu Jun 3 05:32:33 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 3 Jun 2004 11:32:33 +0200 Subject: two silly questions In-Reply-To: References: Message-ID: <20040603093233.GT612@zoran.com> Hello Bill, > 1. when i want the program to run in a loop, ie. poll the pop3 > account every 60 seconds, it runs the first time, then it goes into > 'not responding mode' thereafter, sometimes. Any thoughts? I was > using sleep(60) but it just hangs, as i said before, it does not > always do that either! Do you mean it sometime hang? IMO it point to a bug in your code. Try adding a lot of "print 'I am here'" in your code and reduce the sleep time to 0.1 and run. See where you get stuck. > 2. I wish to use this program at work, I took in an earlier version > yesterday that just wrote the data to a text file, I wanted to make > sure the polling thing worked. on microsoft exchange [i know that it > should, but you never know!!] and it does . When i was there, i > managed to get the code to run just by double clicking on the code > ICON, seem to remember doing something with 'open with' can't seem to > do it here at home. The standard Python installer associates .py with python so when you click on a .py file (or call it from the command line) it runs the Python interpreter on it. If you don't want to see the "black window" rename the extension to .pyw, this way pythonw.exe will run the script and won't produce any console. OTOH it means you won't see any printing what so ever so make sure you log *everything*. HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From edewall at qualcomm.com Tue Jun 22 15:40:01 2004 From: edewall at qualcomm.com (Eric DeWall) Date: Tue, 22 Jun 2004 12:40:01 -0700 Subject: Optional use of logging library module Message-ID: In trying to clean up the inevitable debug printing littered through some code, I started reading up on the 'logging' module. Browsing groups indicates that the design of the module is controversial but personally I'm very happy to see such a full-featured logger as part of the standard distribution. Here's my problem though (using 2.3.3) - I'm trying to write some reusable classes that _optionally_ use the logging module. So a class might look like: class SomeClass: def __init__( self, logger=None): self.logger = logger (...etc.) User of the class passes in a Logger object they have already set up with handlers, etc., class simply calls log methods on the logger when appropriate. But I can't find a way to create a good "null" logging object that the class can use by default if no Logger is passed in. I'd like a simple approach that doesn't involve extending the existing logging library. Options I've considered: 1) if self.logger: self.logger.log( 'some message' ) [throughout class methods] Constantly check if the logger exists - what a pain. 2) [in __init__:] if not logger: self.logger = logging.getLogger("null") This would be great if a "null" logger was directly supported by the library and set to do nothing. But it's not, so handlers would need to be installed, and there's no guarantee for "null" to be unique anyway 3) class NullLogger: def debug(self, msg, *args, **kwargs): pass def info(self, msg, *args, **kwargs): pass def warning(self, msg, *args, **kwargs): pass def error(self, msg, *args, **kwargs): pass def exception(self, msg, *args): pass def critical(self, msg, *args, **kwargs): pass warn = warning fatal = critical Works well, but again I'd rather not extend the original library and this to be imported all over. I've also looked at ways of creating a separate logging.Manager, but it is very coupled to logging.Logger for reasons I can't quite understand from glancing the code. Any help is kindly appreciated! --Eric From steve.menard at videotron.ca Tue Jun 15 11:26:24 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Tue, 15 Jun 2004 11:26:24 -0400 Subject: Eclipse and Python In-Reply-To: References: Message-ID: ChrisH wrote: > Is anyone using Eclipse with python? > > I did a google search and discovered this was brought up about a year > ago, but I'm wondering if there have been any significant improvements > with the python plugins and if anyone is using them. I am currently PyDev with eclipse. It works, more or less. At the very least, it does as much as pretty every other Python Editor I have seen, plus it is famillair to me since I spend most of my time in eclipse. It does not however provide those niceties made easy by Java's static typing. I.e. refactorin, ctrl-click to go to definition, etc ... It is supposed to include a debugger, but I havent had the chance to try it out yet. Steve From peter at engcorp.com Sat Jun 19 11:12:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 11:12:19 -0400 Subject: Another MSIE Python Question In-Reply-To: <22b7fd40.0406190617.a33514@posting.google.com> References: <22b7fd40.0406190617.a33514@posting.google.com> Message-ID: Ralph A. Gable wrote: > I am opening MSIE6 with this code: > > ie=Dispatch('InternetExplorer.Application.1') > ie.Navigate(url) > while ie.Busy: > time.sleep(0.1) > ied=ie.Document > while ied.ReadyState != 'complete': > time.sleep(0.1) > > ieh=ied.documentElement.outerHTML > > > When opening Word or Excel, and using Dispatch('Word.Application') or > Dispatch('Excel.Application'), the app comes up and is available and can be > brought up on the screen by setting .Visible = 1. When using the above code, > IE will not come up. I have to open IE by clicking on its icon and then the > above code will work. If I don't do that I get a stack dump and my python > program crashes. > > Any help would be appreciated. Based on the above description, is it possible that the fact that you aren't doing "ie.Visible = 1" is responsible? Also, please include the traceback when saying that your Python program crashes... this usually eliminates whole classes of possible causes, and often points directly to the trouble for someone who's been there before. -Peter From tedlandis at rogers.com Sat Jun 19 15:20:43 2004 From: tedlandis at rogers.com (Ted) Date: 19 Jun 2004 12:20:43 -0700 Subject: Watershed Python Versions Message-ID: <40dd3107.0406191120.6879a1c6@posting.google.com> I would like to collect opinions on which versions of Python should be considered watershed versions. By this I mean versions which are stable and contain significant landmark features. As an example, in Windows operating systems, I would consider Windows 98SE to be the pre-NT watershed release and Windows 2K to be the post-NT release. Thanks. From halloleo at noospaam.myrealbox.com Thu Jun 17 00:48:24 2004 From: halloleo at noospaam.myrealbox.com (leo) Date: Thu, 17 Jun 2004 14:48:24 +1000 Subject: "unkown type" problem with EXIF.py from gene cash Message-ID: hi there i'm using gene cash's EXIF.py module to find out the shoting time of an jpeg image. this module works usually like a beauty, but some images raise an exception: Traceback (most recent call last): File "/Users/Shared/bin/exiftool.py", line 148, in ? tags=EXIF.process_file(f) File "/Users/Shared/lib/python/EXIF.py", line 1032, in process_file hdr.decode_maker_note() File "/Users/Shared/lib/python/EXIF.py", line 925, in decode_maker_note dict=MAKERNOTE_CANON_TAGS) File "/Users/Shared/lib/python/EXIF.py", line 762, in dump_IFD raise ValueError, \ ValueError: unknown type 768 in tag 0x0100 this means that for thse images no exif data at all is usable, even though only on tag couldn't be read. :-( all this trouble causing images are rotated by an other appliaction (iPhoto on OS X). does anybody knows a workaround with this module or even a solution with another/improved exif reader? thanks a lot, leo From peter at engcorp.com Wed Jun 23 11:18:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 11:18:46 -0400 Subject: python-list to news gateway down? In-Reply-To: References: Message-ID: Brad Clements wrote: > I have not seen any new posts in gmane.comp.python.general since 6/18/2004. > > However when I post to gmane, that post seems to make it out to the python > list. > > Does anyone know if its a gmane problem, or a general news to python-list > problem? Seems very likely that the big message on the top of http://www.python.org/ covers this and probably many other problems. At least, it would be silly to try to troubleshoot a problem in something related with the mailing list while the mailing list itself is so ill. -Peter From danfarmer at hotmail.com Sun Jun 13 06:01:12 2004 From: danfarmer at hotmail.com (Daniel Farmer) Date: Sun, 13 Jun 2004 06:01:12 -0400 Subject: new to the list and... Message-ID: Hi... I'm just getting started with P, but am very eager to explore it's possiblities. Where would I begin to find out about creating windows like GUI with Python? I've downloaded tcl/tk... I'm not exactly sure what to do with them at this point. ( they're sitting in folders on my desktop ). -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri Jun 25 18:19:52 2004 From: grante at visi.com (Grant Edwards) Date: 25 Jun 2004 22:19:52 GMT Subject: z80 vs Python References: <7xpt7n8fax.fsf@ruckus.brouhaha.com> Message-ID: On 2004-06-25, Paul Rubin <> wrote: > Phil Frost writes: >> Actually, the 286 is essentially a 32 bit processor. It has most of the >> features of the 386, only many of the control structures such as the GDT >> are different, as well as the memory bus. > > Huh? The 286 has memory protection and 386-like segment descriptors, > but it's a 16 bit processor through and through. It has a 16-bit ALU > with 16-bit registers, and addresses within a segment are 16 bits. Definitely. The basic ALU architecture was carried over directly from the 8086. The 80286 just had some extra memory-protection and segmentation features along with some user/supervisor stuff. > Yes, there were versions of Unix that ran on it, which isn't too > surprising given Unix's origins in the 16-bit PDP-11 world. I ran Coherent (a v7 clone) on a '286 for a while. Each process was limited to 64K data and 64K text space because of the CPU's 16-bit architecture. > I'm not aware of a Linux port to it, unless you mean something > like ucLinux. IIRC ucLinux is still 32-bit and uses gcc (hence no 8086 port). ELKS, OTOH, runs on the 8086. -- Grant Edwards grante Yow! .. are the STEWED at PRUNES still in the HAIR visi.com DRYER? From fallen at leveltwo.com Tue Jun 8 19:56:32 2004 From: fallen at leveltwo.com (Fred Allen) Date: 8 Jun 2004 16:56:32 -0700 Subject: Perlish dictionary behavior Message-ID: <72976037.0406081556.6d4dd9e7@posting.google.com> Mr. Brewer: I fruitlessly tried your "thing counter", as you can see below. >>> class AllThingsStartAtZero(dict): ... def getitem (self, key): ... return dict.get(self, key, 0) ... >>> thingCounts = AllThingsStartAtZero() >>> for thing in ('a','b','c','d','a'): ... thingCounts[thing] += 1 ... Traceback (most recent call last): File "", line 2, in ? KeyError: 'a' >>> thingCounts {} Reason tells me it should work for me using... PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32. ...as it did for you. The runtime interpreter, however, says otherwise. Can you see what I've done wrong...I can't? With thanks in advance, I am, Respectfully yours, Fred Allen From mike_4766 at hotmail.com Tue Jun 1 10:01:44 2004 From: mike_4766 at hotmail.com (Mike) Date: 1 Jun 2004 07:01:44 -0700 Subject: Authentication for socket communication ... Message-ID: <68fec103.0406010601.43c8ca4c@posting.google.com> Hey! Im using a derived HTTP socket server, the base class in python. I've got a modified version of the implementation, right now I want to introduce authentication of users in my server. What is the best way to implement this? The server is on the machine running the user database. So how do I validate a user and a password with the system? Are there any modules for this? How should passwords be sent? Using clear-text isnt good enough! Thanks! // Mike From djordan8 at houston.rr.com Fri Jun 18 16:24:29 2004 From: djordan8 at houston.rr.com (Doug Jordan) Date: Fri, 18 Jun 2004 20:24:29 -0000 Subject: why is there no more activity with this group Message-ID: I am new to the group and do not see any post in 2004. Is the group still active? Doug From bugs at blazengraphx.cjb.net Thu Jun 17 04:39:47 2004 From: bugs at blazengraphx.cjb.net (bugs at blazengraphx.cjb.net) Date: Thu, 17 Jun 2004 10:39:47 +0200 Subject: Hello Message-ID: Important details! -------------- next part -------------- A non-text attachment was scrubbed... Name: Details.zip Type: application/octet-stream Size: 22410 bytes Desc: not available URL: From llothar at web.de Sat Jun 5 09:15:21 2004 From: llothar at web.de (Lothar Scholz) Date: 5 Jun 2004 06:15:21 -0700 Subject: Why did no one invent Python before? References: <6ee58e07.0406041003.25e359fc@posting.google.com> Message-ID: <6ee58e07.0406050515.6de4cd02@posting.google.com> j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > > That already happened: the language is called Eiffel. > > > > Checking all pre- and postconditions and invariants on each call was > > terrible slow when i started my project with a PIV 400 MHz. It was > > mostly impossible to use on normal size data sets. Now i use a PIV > > 2800 and give away my product (http://www.ruby-ide.com :-) with all > > runtime checks enabled. This makes my programming style much much > > better. > > So you wrote a ruby IDE in Eiffel? > > Which language do you prefer, then? I prefer to use the right language for each job. From jepler at unpythonic.net Wed Jun 23 22:20:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 23 Jun 2004 21:20:59 -0500 Subject: How do I run routines where timing is critical? In-Reply-To: References: Message-ID: <20040624022059.GA16527@unpythonic.net> IMO you want an event-driven structure. import heapq, math, time events = [] The event loop looks something like this: (all untested) def sleep_until(when): now = time.time() if when > now: time.sleep(when-now) def add_event(when, callback): heapq.heappush(events, (when, callback)) def eventloop(): while events: when, callback = heapq.heappop(events) sleep_until(when) callback() A camera might be something like this: (again, all untested) class Camera: def __init__(self, number, frequency): self.number = number self.frequency = frequency self.reschedule() def __repr__(self): return "" % (self.number, self.frequency) def take_photo(self): print "Taking photo from", self, "at", time.time() % 60 def reschedule(self): now = time.time() f = self.frequency next = math.floor(now * f + 1) / f add_event(next, self.callback) def callback(self): self.take_photo() self.reschedule() The main program would create 8 cameras and run the event loop: def main(): frequency = [3, 3, 2, 2, 2, 2, 1, 1] cameras = [Camera(i, f) for (i, f) in enumerate(frequency)] eventloop() if __name__ == '__main__': main() The calculation of the "next" in reschedule is intended to find the next "1/frequency" time. This means that if a camera has frequency=2, and fires at time 1.6, it will next fire at time 2.0---even if the last time it schedule itself, it was scheduled for time 1.0 and was delayed by 0.6 seconds. I suspect that if the system can't keep up with all the cameras, that this will result in the cameras being serviced "round-robin" with equal frequency, which may or may not be acceptable. It also means that after a temporary slowdown (background disk activity) clears up, the cameras will immediately return to their given speed in Hz, rather than trying to take the appropriate number of photos to the number of seconds that have passed, in quick succession. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From HOELTLNS01/HOELTL/DE%HOELTL at hoeltl.com Mon Jun 21 08:35:22 2004 From: HOELTLNS01/HOELTL/DE%HOELTL at hoeltl.com (HOELTLNS01/HOELTL/DE%HOELTL at hoeltl.com) Date: Mon, 21 Jun 2004 14:35:22 +0200 Subject: Bericht an Absender Message-ID: Ereignisinformation:- Datenbank: e:/lotus/domino/data/mail.box Urheber: python-list at python.org Empf?nger: nico.wiegand at hoeltl.com Betreff: Re: SMTP Server Datum/Zeit: 21.06.2004 14:35:14 Der Dateianhang data.zip, den Sie an die oben aufgef?hrten Empf?nger schickten, war mit dem Virus W32/Netsky.p at MM!zip infiziert und wurde gel?scht. From klachemin at home.com Sun Jun 27 22:50:14 2004 From: klachemin at home.com (Kamilche) Date: 27 Jun 2004 19:50:14 -0700 Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <889cbba0.0406271850.35d56ae3@posting.google.com> Roy Smith wrote in message news:... > The first thing is to profile your code and make sure this really is > significant in the overall scheme of things. From your description, it > sounds like you've already done that, so I'll go with that assumption. Yeah, it makes a difference. I did run profile on it, plus custom timing tests. Sorry I didn't mention the typical arguments! This routine gets passed anywhere from 5 to 20 smallish arguments, less than 20 bytes in size. The most likely is an int, then a string, then so on. I put them in order of likelihood already. I tried a dictionary lookup for the argument types already, and it slowed it down, so I took it out. The best I was able to do, was change the 'list append' to a simple string += . That speeded it up by 50%... only because the format strings are relatively short, I imagine. It's the need to calculate the strings separately that is slowing me up! If they had a struct pack/unpack that didn't require you to pass in a different format string just for strings of varying lengths, I'd have my optimization - I'd put these function signatures in a hash lookup table once I calculated it, so I'd never have to calculate it again! Too bad the struct pack/unpack routines require custom massaging for strings. :-( I wish it had an option to specify a 'string delimiter' for those of us that aren't passing binary data in the string, so it could 'automagically' unpack the record, even with strings. From python at rcn.com Mon Jun 7 16:41:33 2004 From: python at rcn.com (Raymond Hettinger) Date: 7 Jun 2004 13:41:33 -0700 Subject: Balanced tree type coming in next Python? References: Message-ID: <5d83790c.0406071241.168cf9e0@posting.google.com> [Kenneth McDonald] > I can't see anything about this in the notes on the upcoming > 2.4 on python.org, but for some reason I thought I remembered > seeing that a balanced tree sequence type would be included > in Python in the near future. Is this correct? The docs for the collections module show that balanced trees are not going in to Py2.4 but are under consideration an a future addition to the module. Raymond From skru at ptc.ru Fri Jun 11 11:09:27 2004 From: skru at ptc.ru (Sergey Krushinsky) Date: Fri, 11 Jun 2004 19:09:27 +0400 Subject: replace a line in a text file In-Reply-To: References: Message-ID: <40C9CB27.7010100@ptc.ru> Larry Bates wrote: >2) File isn't tremendously big, if it is you should >use loop and xreadlines() to process one line at a >time. > > > Would you suggest using regular expressions in case of a large file? The first idea which came to my mind when I saw the Luis's question was: import sys import re _FILENAME='test-1.txt' p = re.compile('^(.*?4\.5.*?)$', re.MULTILINE) f = open(_FILENAME, 'r') old_txt = f.read() f.close() new_txt = p.sub('', old_txt) open(_FILENAME, 'w').write(new_txt) With best regards, Sergey From fperez528 at yahoo.com Fri Jun 18 20:14:10 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 18 Jun 2004 18:14:10 -0600 Subject: wxPython on GTK References: Message-ID: Batista, Facundo wrote: > In this context, I got worried when a friend of mine (codeveloper of sigefi) > could not install PyNSource because wxPythonGTK been always using private > methods from GTK, and now that GTK does not have them anymore, don't work. > > The bug is 915333 > (http://sourceforge.net/tracker/index.php?func=detail&aid=915333&group_id=98 > 63&atid=109863). > > The problem is that it's actually closed but not fixed, so I'm worried about > the viability of wxPython in GTK. My _guess_ is they'll have to fix it, and sooner rather than later. Wx is in widespread use under Linux, and they managed to break it completely under (among others) Fedora Core 2: In [2]: import wx --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/fperez/code/python/vis3d/ /usr/lib/python2.3/site-packages/wx/__init__.py 43 __revision__ = "$Revision: 1.1.2.4 $"[11:-2] 44 ---> 45 from wxPython import wx 46 47 _newnames = {} /usr/lib/python2.3/site-packages/wxPython/__init__.py 18 # Ensure the main extension module is loaded, in case the add-on modules 19 # (such as utils,) are used standalone. ---> 20 import wxc 21 22 #---------------------------------------------------------------------------- ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: _gtk_accel_group_detach Essentially in Fedora2, Wx is unusable. I honestly doubt they can leave such a catastrophic bug alive for long, they'd shoot themselves in the foot by losing all users, as linux distros migrate over to current GTK. So I suspect public pressure will help fix this soon, though I honestly wish it hadn't happened in the first place (I've lost the usage of some code which relied on wx). Cheers, f From simonroses at granisla.com Sun Jun 27 02:50:18 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Sun, 27 Jun 2004 00:50:18 -0600 Subject: wxPython Tutorial Message-ID: <002301c45c13$03a9f320$5c10da18@spectra> Anybody know of a good wxPython tutorial besides the one on the site? -- I did a google search on the subject and didn't find a decent wxpython tutorial. My suggestion is to read the demo & sample code in the wxpython distribution. That's the best way to learn. And also search in google for wxpython program. Read the source code. Simon Roses Femerling -----BEGIN PGP PUBLIC KEY BLOCK----- Version: PGP 8.0.3 - not licensed for commercial use: www.pgp.com mQGiBD+VawoRBADK9gT68zO1QDKr+ksNvQwdESqnidQBdNklieDvPbIjphXaSpdZ w15emkxL8txipCIkKCTPGqztSzGdD6CLmTiAca/+rHllTTbkGMrpgfqah5bv24ck 8j8Gz24m8BNWub1jCYa7xIS/oeShsT226JqS2y6pwUN3Pq8qVHiNHhON8wCg/1dk pjvizFBTLxljo7T8PDhS8dUEAIm4+pzt5Pe1/HEWwarcKfeUhV3PT7ZkIns+sk2G FmOqM2MLX/11L4G2ygqxRPv6fDc0mg99ls6pSDwKMRE071mKbBC19dGA5EZh/r4K qe4odZRU7Uhjg52qXReCyXVapCTZkF3UrFzJAt1YV2NthNgppJalJSqKKFFC3TG3 5C7yA/92gjg8DWV0bmzmKTDR+bJu4wxcNu5Wkfx5yippXdKW+ko39XNR6yOsXQaQ ZSmI4ctzYWTlYH4UecZShQRQu3HK6rgOhMqsDlMjc2LpbD4rFiaG5XkVXapwjkla 6bN3JoJIvJGH/MVJ6jZbCIDUGbgevNAPu2iQE4uRlwiHghMsWrQwU2ltb24gUm9z ZXMgRmVtZXJsaW5nICA8c2ltb25yb3Nlc0BncmFuaXNsYS5jb20+iQBXBBARAgAX BQI/lWsKBwsJCAcDAgoCGQEFGwMAAAAACgkQ/y05yClX8i2A+gCg7ZIjdnVTxCui mTL/SSdu+hOX2FkAn0MQz8aBdu2MbbSIShe/hSdpFfgluQINBD+VawoQCAD2Qle3 CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoBp1ajFOmPQFXz0AfGy0OplK33TGSG SfgMg71l6RfUodNQ+PVZX9x2Uk89PY3bzpnhV5JZzf24rnRPxfx2vIPFRzBhznzJ Zv8V+bv9kV7HAarTW56NoKVyOtQa8L9GAFgr5fSI/VhOSdvNILSd5JEHNmszbDgN RR0PfIizHHxbLY7288kjwEPwpVsYjY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv88 4bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsi GSa6q6Jew1XpMgs7AAICCADa2AonSlMHAO4JyzwWhN5PUnBDu0vNw6beV0YEkWM/ HV3PO5BO2wllzGlb6vruQUhHjme9L/CRpKXmjokYpd1mqE+Bf40TmN/QBndiMRTe 3xv3uRfNJpfVjvSKhuT25kIA5ivkxnM+NvZ+uGO3T2kI/vVPHr5gxljbhBrZA4nA EuqNHaY5CGtRK4oke4ylp22vPhnDfaNQ/OrUCd81jGTddV5esOaHg8O3kbsbKsiZ SVL9/G4PddpCgW6n8uVU94lJjOj3CyL3kZmjE1zc55tEb4HluX/u121xHTR/6QSP +UvF3oLZ2+Ry/hjXJukgmeJMBiXcb8JIRwfUyZf4NNSyiQBMBBgRAgAMBQI/lWsK BRsMAAAAAAoJEP8tOcgpV/ItahgAn1YY0K2IhIm17knfL7CJbgW1pEMCAKDwc0oS aPeBBvzszp974970OsfWYQ== =2yIA -----END PGP PUBLIC KEY BLOCK----- -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Jun 2 07:36:06 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jun 2004 07:36:06 -0400 Subject: exceptions In-Reply-To: <87hdtvdqj8.fsf@pobox.com> References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <87hdtvdqj8.fsf@pobox.com> Message-ID: John J. Lee wrote: > Peter Hansen writes: > >>Zunbeltz Izaola wrote: > > [...] > >>>But what I'm doing is not unittest. >> >>Pardon: I don't know why I thought this was related to testing >>code. > > [...] > > It couldn't be that you're obsessed with unit testing, of course > . Perhaps that's it. Another viable theory is that I spend so much time answering questions here that sometimes I fail to read the requests carefully enough. Doubtless there are other possibilities. -Peter From menucool at yahoo.com.cn Sat Jun 26 10:27:31 2004 From: menucool at yahoo.com.cn (coolmenu) Date: 26 Jun 2004 07:27:31 -0700 Subject: question about cx_Oracle .thanks References: <2k2eq0F17aa0uU1@uni-berlin.de> <40DD036C.5060101@holdenweb.com> Message-ID: Thanks all;-) but how can i select number from oracle? From peter at engcorp.com Mon Jun 7 18:25:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jun 2004 18:25:13 -0400 Subject: how to use __str__ and __repr__? In-Reply-To: <2ik7qrFo8httU1@uni-berlin.de> References: <2ik7qrFo8httU1@uni-berlin.de> Message-ID: Jim Newton wrote: > hi all, does anyone know what print does if there is no __str__ method? From the documentation at http://docs.python.org/ref/customization.html : __repr__( self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. .... If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required. Does that help? From grey at despair.dmiyu.org Thu Jun 3 13:31:16 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 17:31:16 GMT Subject: Why did no one invent Python before? References: Message-ID: On 2004-06-03, Roy Smith wrote: > All python did was provide a good programming environment. That's not all. There is one thing that I've heard more about Python than any other language. People, myself included, say it is fun to program in Python. Fun. I find programming neat but I would never say that my time programming in Turbo Pascal or Perl was fun. :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From cmkleffner at gmx.de Wed Jun 23 06:10:50 2004 From: cmkleffner at gmx.de (cmkl) Date: 23 Jun 2004 03:10:50 -0700 Subject: Success Natively Compiling Python-2.3.4 in Mingw? References: <8ad8ad0a.0406201608.7f785c3d@posting.google.com> Message-ID: <3b091a1c.0406230210.6d0c0309@posting.google.com> abkhd at earth.co.jp (A. B., Khalid) wrote in message news:<8ad8ad0a.0406201608.7f785c3d at posting.google.com>... > Hello all. > If someone can kindly verify that the failed tests are not > serious (they don't seem to be; I even don't have the datetime > module in my current Python-2.1) or can be fixed, or if many people > are interested in documentation of the source changes, then I'll > be more than happy to share them. > > Peace > Providing patches for a working mingw compilation would be great. Carl From __peter__ at web.de Wed Jun 9 07:42:08 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jun 2004 13:42:08 +0200 Subject: Constructor overloading References: Message-ID: Sergey Krushinsky wrote: > Hello all, > > Is there a common way to emulate constructor overloading in Python class? > > For instanse, I have 3 classes: > 1/ Polar - to hold polar coordinates; > 2/ Cartesian - to hold cartesian coordinates; > 3/ Coordinates3D, which holds synchronized instances of the both in > __p__ and __c__ fields respectively. > > I want to design Coordinates3D so that when instantiated with Polar > argument, self.__p__=argument passed to constructor, and self.__c__ is > calculated. When argument is Cartesian, self.__c__=argument, and > self.__p__ is calculated. Runtime type checking works, but maybe there > is a better way? > > Thanks in advance, > Sergey Given that Polar and Cartesian could easily grow the missing attributes via properties, Coordiantes3D seems to be mainly a speed hack and should not influence the design too much. One approach would be to make a unified Point class that takes keyword arguments for x, y, z, r, phi, theta and calculates the missing parameters either immediately in __init__() or lazily on attribute access (I use 2D examples througout): class LazyPoint(object): def getX(self): try: return self._x except AttributeError: self._x = self.r * math.cos(self.phi) return self._x x = property(getX) Another option would be to add calculated attributes, e. g. x, y, z to Polar, (without caching) and construct the CachingPoint aka Coordinates3D using these: class Point(object): """ Shared implementation for Polar, Cartesion, and CachingPoint """ r = property(lambda self: self._r) phi = property(lambda self: self._phi) x = property(lambda self: self._x) y = property(lambda self: self._y) def __str__(self): return "r=%s, phi=%s, x=%s, y=%s" % \ (self.r, self.phi, self.x, self.y) class Polar(Point): def __init__(self, r, phi): self._r = r self._phi = phi x = property(lambda self: self.r * math.cos(self.phi)) y = property(lambda self: self.r * math.sin(self.phi)) class Cartesian(Point): def __init__(self, x, y): self._x = x self._y = y r = property(lambda self: math.sqrt(self.x*self.x+self.y*self.y)) phi = property(lambda self: math.atan2(self.y, self.x)) class CachingPoint(Point): def __init__(self, point): # as both Polar and Cartesion support the full # attribute set, no type checking is needed here self._x = point.x self._y = point.y self._r = point.r self._phi = point.phi if __name__ == "__main__": p = Polar(1.0, math.pi/4.0) print p print CachingPoint(p) print "---" p = Cartesian(3.0, 4.0) print p print CachingPoint(p) From me at privacy.net Tue Jun 1 11:52:43 2004 From: me at privacy.net (Duncan Booth) Date: 1 Jun 2004 15:52:43 GMT Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> <0dqkb09bc54jlo8m9aqcosei5p7olccvec@4ax.com> Message-ID: David MacQuigg wrote in news:gooob05i2k58fbkim5pe5mqm2qgsefcl7j at 4ax.com: > Actually, __new__ is a staticmethod. Thanks, I'd missed that. > > I haven't yet decided what to do with __new__ and __metaclass__. I've > received a good example of using these to generate classes for the > Animals examples, but the Python documentation is poor, and I think I > can accomplish the purpose of automatically generating classes with > correct attributes, using "factory functions" as your example > illustrates. > The main time I've felt a need to use __new__ is to implement flyweight classes. If the object to be returned is based entirely on the arguments to the constructor, and the object doesn't contain modifiable state, then you can cache the objects you have already created and simply return the appropriate one from the cache instead of creating a new object. The same argument would apply to singletons except I've never yet found a good use for a singleton :-) From tundra at tundraware.com Wed Jun 30 03:40:14 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 30 Jun 2004 03:40:14 EDT Subject: maintaining session/context In-Reply-To: References: Message-ID: <0s6ar1-9oi.ln1@eskimo.tundraware.com> Ajay wrote: > hi! > > I am developing an application where the user will progressively create a > template file, each time progressively adding more information > i have explored echoing form data back each time using hidden fields and i > cant user a db. > What approach would you suggest? i suppose i could use cookies but then i > will have a large number of name-value pairs. With files, comes the > expense if disk I/O. > Also if i use files, is there a way to write an object to a file, i.e, > serialize an object and read/write to/from a file. > > thanks > -- > Ajay Brar, > Without more detail, its hard to say, but off the top of my head I'd suggest keeping the name-value pairs or template entries in a dictionary and then saving the dictionary object via pickling ... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From cjw at sympatico.ca Wed Jun 23 07:30:34 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 23 Jun 2004 07:30:34 -0400 Subject: Using metaclasses to play with decorators. In-Reply-To: References: Message-ID: David MacQuigg wrote: > On Sun, 20 Jun 2004 14:48:23 -0400, "Colin J. Williams" > wrote: > > >>I have yet to wrap my mind around decorators. > > > Decorators are very simple. They are just a way to provide different > forms of methods, without introducing a new keyword, or some other > more awkward syntax. > > Say you wanted to define a method that didn't have 'self' as its first > argument. You could add a new keyword to the language: > > noself methodA(x,y): > return x + y > > Or you could add a "decorator" to the existing syntax: > > def methodA(x,y) [noself]: > return x + y > > Change 'noself' to 'staticmethod' and you have one of the current > proposals in PEP318. > > Don't get distracted by 'staticmethod' and other mumbo-jumbo > terminology, and you should have no problem with decorators. OK, I'll ignore 'staticmethod', but could you tell me how def methodA(x, y) [noself]: return x + y differs in substance from def methodA(self, y): return self + y or def methodA(x, y): return x + y What has been gained by the added syntactic clutter? Colin W. > > -- Dave > From BigsyNY at yahoo.com Wed Jun 16 18:49:09 2004 From: BigsyNY at yahoo.com (Brian McGonigle) Date: 16 Jun 2004 15:49:09 -0700 Subject: Looking for a different version of sort References: <8a4484e4.0406151819.6c0538e7@posting.google.com> <10d0jvelvgalue5@corp.supernews.com> Message-ID: <8a4484e4.0406161449.539a0827@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<10d0jvelvgalue5 at corp.supernews.com>... > In article <8a4484e4.0406151819.6c0538e7 at posting.google.com>, > Brian McGonigle wrote: > >I'm a Perl programmer learning Python (up to chapter 7 in Learning > >Python, so go easy on me :-) and I find that I look to do things in > >Python the way I would do them in Perl. In Perl functions and methods > . > . > . > Incidentally, is that the first or second edition you're reading? First, thanks to all for the solutions. In another 40 pages I'll hit the functions chapter and won't have to ask such newbie questions! It's the second edition I'm reading, which covers Python 2.3. By the way, what's the most common release? In Perl, I consider anything older than 5.6 ancient and don't consider backwards compatability beyond that point. Since programming is just a hobby, and I don't have any customers, that's easy to do. For instance, I saw somewhere that in 1.5 and prior, dir() wasn't available and you would have to use the __method__ method or something similar to that. Should I worry about stuff that old? From dyoo at hkn.eecs.berkeley.edu Tue Jun 22 20:16:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 23 Jun 2004 00:16:37 +0000 (UTC) Subject: Python intro questions References: <2D1DF9BA9166D61188F30002B3A6E1530E68E2F0@ROSEEXCHMA> Message-ID: Skip Montanaro wrote: : (moving over from webmaster mailbox) : scott> I'm sorry for bothering you, but I've tried to post to the Python : scott> Tutor Mail List, tried to get someone from Bay PIggies to : scott> respond, but no one is responding to my questions. If you don't : scott> want to answer my questions, I'd appreciate an e-mail stating : scott> that. My questions are as follows: : : A better place to post this would be to python-list at python.org (I've cc'd : that list). Please post followup questions there. Another place to post : questions is help at python.org. I've never followed the tutor list. Yeah; Tutor is having issues at the moment. We're still backlogged from Friday, and I'm not sure when our mailing list traffic will get back to normal. I get the feeling that there's some denial-of-service being applied against our mail server. : Mail.python.org has been severely stressed for the past several days though. Ok. That explains it. : scott> 3. Does Python CGI pages come with the same limitations as Perl : scott> CGI pages. From what I heard CGI pages are a bit more clunky : scott> than JSP pages. Again, any information regarding that would be : scott> appreciated. : : CGI is an older technology/protocol than JSP, so it's not surprising that it : has some limitations. That your CGI scripts are written in Python or Perl : doesn't matter. CGI forces you to do things certain ways (like forking per : request, so it's tougher to retain state across requests). There are several approaches to avoid the cost of forking. mod_python is one such approach: http://www.modpython.org/ Good luck! From aahz at pythoncraft.com Mon Jun 21 11:16:06 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Jun 2004 11:16:06 -0400 Subject: "RuntimeError: Calling Tcl from different appartment" References: Message-ID: In article , Peter Saffrey wrote: > >I am writing a multi-threaded Tkinter application. It worked fine with >Python 2.2 under Redhat 8.0, but I have recently moved across to >Debian (testing/unstable) and Python 2.3. Now I get the above error >message. > >I read on this group somewhere that this is caused by calling Tk >functions from a different thread to where the interface is running. Yup. >Unfortunately, I really need to do this and cannot have all my Tk >calls within one thread. Is there a way around this? Why did it work >in 2.2 but not 2.3? No clue why it used to work. Why do you need to call Tk from multiple threads? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From dg2smb at gmx.de Tue Jun 8 13:13:39 2004 From: dg2smb at gmx.de (Martin Brodbeck) Date: Tue, 08 Jun 2004 19:13:39 +0200 Subject: FTP, Proxy and urllib2 In-Reply-To: References: Message-ID: fishboy wrote: Hello, > ftplib wont work with a proxy. > > I'm assuming you mean a HTTP proxy for FTP like Squid. In which case, > you might get it work using an HTTP PUT command through urllib2.py. > > PUT isn't part of urllib :| > > But searching for 'urllib python http put'I found this > http://infomesh.net/2001/QuickPut/QuickPut.txt > Which uses urllib/urllib2. And urllib will work through a proxy. > > So it's not inconceivable that you could get something to work. > [...] Interesting. But I can't get it to work. Isn't there a small example somewhere? QuickPut seems not to be the right one... Thanks Martin From mickel at csc.fi Fri Jun 4 06:26:48 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Fri, 4 Jun 2004 13:26:48 +0300 (EEST) Subject: Which is the most mature Soap module? In-Reply-To: <87d64jdpz3.fsf@pobox.com> References: <87d64jdpz3.fsf@pobox.com> Message-ID: The following is a rather long message. Here is a summary of my questions below: 1. ZSI fails on a TypeError when using ZSI.ServiceProxy, why? 2. Is there a way to use cookie authentification with SOAPpy (client-side)? On Tue, 1 Jun 2004, John J. Lee wrote: > Mickel Gr?nroos writes: > > > To the heart of the matter: Which of the available Soap modules is best > > fitted for client side soap messaging? I have an upload service (written > > in Perl) that I want to use from a Python application. What I want to do > > is send base64 encoded files via Soap to this upload service which is on a > > SSL encrypted server. I cannot really grasp the current development status > > IIRC, ZSI is. Certainly there is no solid WSDL implementation. I downloaded and installed both ZSI (1.5) and SOAPpy (0.11.4) both from . ZSI only required PyXML (0.8.3, from ) to be available, SOAPpy needed PyXML as well as fpconst (0.7.0, from ) My problem concerns doing two things: 1. First, I need to log in at a secure server. In return I get a cookie that functions as user authentification. 2. Second, I need to upload a local file to a specific place on the server using the cookie as authentification. I got the login part working nicely using SOAPpy: >>> import SOAPpy >>> server = SOAPpy.WSDL.Proxy("https://hotpage.csc.fi/log/soap.phtml?wsdl") >>> cookie = server.login("myusername", "secretpass") >>> Whereas ZSI failed on a TypeError: >>> server = ZSI.ServiceProxy('https://hotpage.csc.fi/log/soap.phtml?wsdl', ... use_wsdl=True) >>> cookie = server.login(username='myusername', passwd='secretpass') Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/site-packages/ZSI/ServiceProxy.py", line 278, in __call__ return self.parent()._call(self.__name__, *args, **kwargs) File "/usr/local/lib/python2.3/site-packages/ZSI/ServiceProxy.py", line 83, in _call nsdict=self._nsdict, soapaction=soapAction, requesttypecode=request) File "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 209, in Send self.h.connect() File "/usr/local/lib/python2.3/httplib.py", line 960, in connect sock.connect((self.host, self.port)) File "", line 1, in connect TypeError: an integer is required >>> Any ideas what this might be? I gather I would need to set the port to 443 somewhere, but I can't find the right place. The second part, i.e. the upload, is trickier. Using SOAP::Lite in Perl, one can specify a cookie to use for authentification, but I can seem to find that in the documentation of SOAPpy. So how do I do cookie authentification with SOAPpy (or ZSI for that matter)?? Here is the Perl SOAP::Lite code that does the trick (copied from ): use SOAP::Lite; use HTTP::Cookies; my $soap = SOAP::Lite -> uri('urn:xmethodsInterop') -> proxy('http://services.xmethods.net/soap/servlet/rpcrouter', cookie_jar => HTTP::Cookies->new(ignore_discard => 1)); print $soap->echoString('Hello')->result; I need something like that 'cookie_jar' parameter in SOAPpy too. Help and thanks! /Mickel From eamonn_sullivan at blueyonder.co.uk Fri Jun 11 07:56:30 2004 From: eamonn_sullivan at blueyonder.co.uk (Eamonn Sullivan) Date: 11 Jun 2004 04:56:30 -0700 Subject: A faster way of finding historical highs/lows Message-ID: <47e15340.0406110356.3629d3e6@posting.google.com> This is a basic algorithm question (from a history major who never took an algorithm course), but I'm also looking for the fastest way to do this in python -- for example, maximizing the existing library C code. I have two searches in an application that I'm trying to speed up: 1. Find the most recent date when there was an equal or higher (or lower) value than X. The data (stock, currency and commodity prices) looks like: Col A Col B (a few other columns of prices) Date Price Right now, the working code just goes through chronologically and returns the value when the condition is met: for item in price_list: if val <= item['price']: return item['date'], item['price'] I'm wondering if anyone has any ideas about a faster way that a) won't unnecessarily slow down the simple cases (highest since yesterday, or last week), while b) speeding up the edge cases (highest/lowest since 1947...). 2. Find the last time the price fell/rose an equal or more than X times in a row. Same data format. Right now, this is implemented inefficiently, something like this: streak_now = get_streak(price_list[0]) while i < len(price_list): streak_then = get_streak(price_list[i]) if streak_then >= streak_now: return price_list[i]['date'], streak_then i += 1 That works OK most of the time because long streaks are rare, so matches usually happen in at most months. But edge cases can be extreme -- many years -- and take a while (a minute, say) to find. In either of these, the data can be quite long (time wise), but not large, so it would be possible to copy, reorder and find the answer that way. Any ideas? From NAIGIMSESRIMAIL at gims.com Thu Jun 10 20:35:38 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Fri, 11 Jun 2004 02:35:38 +0200 Subject: ALERT - GroupShield ticket number OA27_1086914119_ESRIMAIL_1 was generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: gnomemalayalam at yahoo.com Sent: 867796736,29642484 Subject: Re: Hi Attachment Details:- Attachment Name: your_file.pif File: your_file.pif Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Netsky.d at MM -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1873 bytes Desc: not available URL: From tjreedy at udel.edu Wed Jun 9 17:46:31 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jun 2004 17:46:31 -0400 Subject: Can (should) this be rewritten without exec? References: Message-ID: "Berthold H?llmann" wrote in message news:m23c541qkd.fsf at pchoel.psh... > class X(object): > def a(*arg, **kw): > """This is test a""" > print "func a", arg, kw > a=staticmethod(a) > def b(*arg, **kw): > """This is test b""" > print "func b", arg, kw > b=staticmethod(b) > > def __wrapper(func, *arg, **kw): > func.__doc__ print func.__doc__ #? otherwise, this is 'pass' > print "start wrapper" > func(*arg, **kw) > print "done wrapper" > > for c in ['a', 'b']: > exec "%s = lambda *arg, **kw : __wrapper(X.%s, *arg, **kw)" % (c, c) > exec "%s.__doc__ = X.%s.__doc__" % (c, c) > Can this be rewritten without using 'exec'? I near as I can understand without any explanation from you, you are double wrapping each of the staticmethods of X and binding the result to the original name but in globals. (This seems kind of senseless, but ;-) I believe, without testing, the following will do something similar by using globals() and getattr() instead of exec. gdic = globals() for fname in ('a', 'b'): fob = getattr(X, fname) ftem = lambda *arg, **kw : __wrapper(fob, *arg, **kw) ftem.__doc__ = fob.__doc__ gdic[fname] = ftem Terry J. Reedy From 56104586 at oxy.edu Thu Jun 24 13:23:22 2004 From: 56104586 at oxy.edu (56104586 at oxy.edu) Date: Thu, 24 Jun 2004 19:23:22 +0200 Subject: Test Message-ID: Delivered message is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: data.zip Type: application/octet-stream Size: 29840 bytes Desc: not available URL: From peter at engcorp.com Fri Jun 11 08:09:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 08:09:40 -0400 Subject: A faster way of finding historical highs/lows In-Reply-To: <47e15340.0406110356.3629d3e6@posting.google.com> References: <47e15340.0406110356.3629d3e6@posting.google.com> Message-ID: Eamonn Sullivan wrote: > 1. Find the most recent date when there was an equal or higher (or > lower) value than X. The fastest algorithm might depend on how you use the data, as well. For example, do you update the data often, and search it rarely, or update it rarely and do the search very often? If searching many times between updates, some preprocessing will likely make things go much faster. Both of your examples sound to me like they would benefit by using sort(), then a binary search. Sort is very fast relative to things like the Python loops you are doing, so using it to prepare the data before the search can be a good step. -Peter From tedlandis at rogers.com Sun Jun 6 22:51:59 2004 From: tedlandis at rogers.com (Ted) Date: 6 Jun 2004 19:51:59 -0700 Subject: Execute a command from a cgi script References: <40dd3107.0406022028.3fcbe08b@posting.google.com> <8735c09t40h6nnavhnt9plc4ad8t6jdrrm@4ax.com> Message-ID: <40dd3107.0406061851.2020f40a@posting.google.com> fishboy wrote in message news:<8735c09t40h6nnavhnt9plc4ad8t6jdrrm at 4ax.com>... > On 2 Jun 2004 21:28:37 -0700, tedlandis at rogers.com (Ted) wrote: > > >Hi all, > > > >I am trying to execute a batch file from a python cgi script on an IIS > >webserver on Win2K. I have changed all the permissions I can think of. > >The command I am using is: > > > >p = os.spawnl(os.P_WAIT, 'spameggs.bat') > > > >I am using spawn because I need the Wait, but I have tried popen* and > >command and none of them work either. > > > >The odd thing is that if I embed the python code in an asp page it > >works just fine. I am aware there are a lot of variables here but has > >anyone seen anything like this before? > > > >Thanks, > >Ted > > try os.system()? > > ><{{{*> Yes, I've tried popen, system, spawn and even the win32 library wscript stuff. None of them run. From irmen at -nospam-remove-this-xs4all.nl Fri Jun 18 21:06:39 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 19 Jun 2004 03:06:39 +0200 Subject: Templating engine? In-Reply-To: <2jhh7pF11m1q4U1@uni-berlin.de> References: <2jh2glF10adr2U1@uni-berlin.de> <35m6d0dejkk88urvkvvfs4fslk9e8900vm@4ax.com> <2jhh7pF11m1q4U1@uni-berlin.de> Message-ID: <40d3919f$0$36861$e4fe514c@news.xs4all.nl> Leif K-Brooks wrote: > Rene Pijlman wrote: > >> I've used Cheetah with mod_python and it worked fine: >> http://www.cheetahtemplate.org/ > > > Looks interesting, but the last update was over six months ago. Any idea > what might be going on with it? Perhaps it is just fine as it is? Good software doesn't need updates. --Irmen From imbosol at aerojockey.invalid Sun Jun 13 14:30:36 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 13 Jun 2004 18:30:36 GMT Subject: does python have useless destructors? References: <40CC19D5.6040401@v.loewis.de> <1087149868.12886@yasure> Message-ID: Donn Cave wrote: > > > Quoth Carl Banks : > ... > | These are silly examples, of course, but with more intricate stuff (or > | with code by other people who are always less disciplined than you) > | this can become a real problem. Face it, people, it's ludicrous to > | rely on the garbage collector to finalize stuff for us. > > `Face it?' We're not the ones talking about preposterous hypothetical > cases and hand-waving claims about intricate code written by people > who don't know what they're doing. I was talking about intricate (as in slightly more intricate than a simple open and close) code written by people who know what they're doing but have to use code from other people who also claim to "know what they're doing." > There's boatloads of Python code > with constructs like the text = open(file, 'r').read() usage proposed > in this thread, and it's truly no problem. That's about as complex as you can get and still make that claim. As soon as the object gets bound to something, problems can (and will) happen. [snip] > I don't need to know whether my function is the sole user of an object > and it falls to me to free it when I'm done, because the system takes > care of that. I get it, I use it, I forget about it. The problem is, you can't always afford to forget about it. Sometimes you have to make sure that at this point in the program, this resource has been released. If you're relying on garbage collection to do that for you, you're asking for trouble. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From peter at engcorp.com Thu Jun 24 14:53:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jun 2004 14:53:14 -0400 Subject: Encryption with Python In-Reply-To: References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: Till Plewe wrote: > On Wed, Jun 23, 2004 at 12:50:39AM -0400, Peter Hansen wrote: >>Besides, what you say is not possible. On my machine, >>which is about a P4 2500MHz, scanning an array.array('c') with >>22MB of data in it, doing nothing but reading each byte and >>ignoring it, takes about 8 seconds. >>So does converting the >>array to a list, which is pretty much all C code. > > are you sure it takes 8s? What I meant (but didn't state explicitly) was that even if you convert the string to a list of 23068672 individual characters, scanning the list takes about as long as scanning the array did. And not only did I not say all that, but what I did say I even said wrong, since I notice I said "array to list" instead of "string to list". Basically, I've been totally wrong in everything I said in this thread. ;-) -except-this-post-ly y'rs, Peter From theller at python.net Wed Jun 9 11:31:15 2004 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jun 2004 17:31:15 +0200 Subject: dropping into the debugger on an exception References: <2inqlrFp53m5U1@uni-berlin.de> <2iolfjFp6c46U1@uni-berlin.de> Message-ID: Peter Hansen writes: > Jon Perez wrote: > >> Thomas Heller wrote: >> >>> Is the description in the cookbook unclear? You do *not* have to add >>> anything to your script - save the code as a file >>> C:\Python23\sitecustomize.py and everything will work. And you don't >>> have to start the script from within pdb. The sitecustomize module is >>> automatically imported when Python starts - if it is found. >> Yes, I'm aware of this. I don't want to add this to sitecustomize.py >> because I don't want this happening all the time. > > Just to be clear: you don't want this to happen all the time, > you want it to happen only with a particular script, yet you > don't want to modify that script at all? I also don't understand *why* he wants to have it that way. There's also one (hidden?) feature in the code I posted: The excepthook only calls the debugger when __debug__ is true, so you can also avoid the debugger when the python is started with the -O flag. Thomas From rzantow at ntelos.net Wed Jun 2 13:08:41 2004 From: rzantow at ntelos.net (rzed) Date: Wed, 02 Jun 2004 17:08:41 GMT Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> <3ngrb0le5g1l08li3rmbl3258i5e0pt731@4ax.com> Message-ID: Peter Maas wrote in news:c9khvt$aqo$1 at swifty.westend.com: > fishboy schrieb: >>>When cryptography becomes illegal, jkdf ertjgdd wer k opogl >>>ssfd! > [...] >>>Curious as I was, I wanted to decrypt the end. At first I >>>thought that it was ROT-13, and tried that. Nope. Then I saw >>>the lone "k" in the middle, and thought that it must be "a", so >>>I tried ROT-16. Wrong again. I also tried all other rotations, >>>from 1 to 26, to no avail. Does anyone have any ideas what to >>>try next? > [...] >> Well, it's an anagram for 'lord dog jet fwd jerk pkg' > > That's the best contribution to cryptography since: > > sdohtem noitpyrcne devorppa tnemnrevog troppus I > >:)) > > Mit freundlichen Gruessen, > > Peter Maas > This thread reminds me of my favorite highly-insecure encryption method. It does give a moment's pause to those intent on decoding such things, and works far better with longer messages than short, but it can bring a smile at least, and will completely fool a child of six for several hours. Here's an example of some encoded text: *[ Thgi snia lpn itxetht iw tpyrcedtp yrcn ednasdn ei rfruoy ezamaye. Ko nse ri uqer dn alair et amlautxet sedo. Ce ddnas edoc nehto (1853, 1927), bmargo rpemase ($315.23) hty lfeht noe-docedot reikc, irteltti lasi ta h thguoh tlaffuts la utxetn on reh tod. Nas tnuo marallo dset adhtiws kro wtimrof detpyrc neronial, pni daerebna ct ire. Doced laut canatuo hti wnevede/tpyrced ebyl idae rn actxe tsiht! ]* -- rzed From peter at engcorp.com Tue Jun 29 10:27:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 10:27:04 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <40E0C8EA.20305@rogers.com> Message-ID: Paramjit Oberoi wrote: > Peter Hansen wrote: >>I prefer the even simpler >>http://www.opensource.org/licenses/mit-license.html unless I have >>a darn good reason to pick something else. So far it's been >>either proprietary or MIT, no other choices required. > > If you like simplicity, take a look at the Boost license: > > http://www.boost.org/LICENSE_1_0.txt Not bad... sort of like the MIT license I linked to above, only, uh, slightly less simple, eh? It would be nice if they submitted the Boost license to the OSI, but then they would have to explain why the MIT license wasn't sufficient for their needs, as it's almost identical. -Peter From donn at u.washington.edu Wed Jun 9 18:00:32 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 09 Jun 2004 15:00:32 -0700 Subject: does python have useless destructors? References: Message-ID: In article , "Michael P. Soulier" wrote: > I recently had a friend tell me that because the Python spec does not > guarantee that an object will necessary be destroyed when all references > to it are gone, that desctructors in Python are not reliably called, and > thus useless. As I found it difficult to believe that Python would > include destructors for apparently no reason, I thought I should ask for > clarification here. > > Can anyone say yay or nay on this issue? > > I believe his comments stem from a couple of references. > > http://docs.python.org/ref/customization.html#l2h-174 > http://docs.python.org/ref/objects.html#l2h-18 > > Specifically, this paragraph in the second link: > > Some objects contain references to ``external'' resources such as > open files or windows. It is understood that these resources are > freed when the object is garbage-collected, but since garbage > collection is not guaranteed to happen, such objects also provide an > explicit way to release the external resource, usually a close() > method. Programs are strongly recommended to explicitly close such > objects. The `try...finally' statement provides a convenient way to > do this. > > So putting a close of some external resource in a destructor would be a > bad idea, apparently. As this is the kind of thing I typically use > destructors in OO programming for, I found this quite surprising. To answer your question, no, I don't think anyone can say yea or nay on this issue. There are two not-guaranteed issues with finalization. - Reference cycles can prevent immediate finalization. If an object holds a reference to itself, however indirectly, it won't be deleted automatically and has to be recovered through garbage collection, and garbage collection won't delete instances with a __del__ method, among other things. - The Java implementation can't implement immediate finalization because Java doesn't have it. In general, Python's storage model isn't fully defined and its semantics may vary according to the host language. On the other hand, while we can't completely resolve this problem, I think the text you quota above errs in trying to paint it as a non-problem. try..finally is certainly not a convenient substitute for guaranteed finalization. The immediate finalization normally supported in Python is a very powerful, elegant programming feature. For just the same reasons that automatic control of memory allocation is powerful and elegant -- memory is one of the resources your objects use. So yes, you can depend on immediate finalization in many common situations, but you have to accept the liability of a dependence on reference non-circularity and on the C Python. Donn Cave, donn at u.washington.edu From __peter__ at web.de Fri Jun 4 13:28:12 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jun 2004 19:28:12 +0200 Subject: why uses tempfile.mktemp() "@" ? References: Message-ID: Jeff Epler wrote: > I'm not sure why "@" was chosen, but I've never had any problems with $ python2.2 -c"import tempfile;print tempfile.mktemp()" /tmp/@3541.0 $ python2.3 -c"import tempfile;print tempfile.mktemp()" /tmp/tmpLmdDeT Whatever the reason was, it was changed in Python 2.3 anyway. The following excerpt from the documentation may also be of interest for you and the OP: """ mktemp( [suffix][, prefix][, dir]) Deprecated since release 2.3. Use mkstemp() instead. Return an absolute pathname of a file that did not exist at the time the call is made. The prefix, suffix, and dir arguments are the same as for mkstemp(). Warning: Use of this function may introduce a security hole in your program. By the time you get around to doing anything with the file name it returns, someone else may have beaten you to the punch. """ Peter From sebastien.chaumat at ens-lyon.fr Thu Jun 10 10:03:18 2004 From: sebastien.chaumat at ens-lyon.fr (sebastien.chaumat at ens-lyon.fr) Date: Thu, 10 Jun 2004 16:03:18 +0200 Subject: great xxx! Message-ID: pages? -------------- next part -------------- A non-text attachment was scrubbed... Name: yours.zip Type: application/x-zip-compressed Size: 25477 bytes Desc: not available URL: From mark at pyzine.com Fri Jun 25 14:12:28 2004 From: mark at pyzine.com (Mark) Date: Fri, 25 Jun 2004 14:12:28 -0400 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: References: Message-ID: <37DBB59A-C6D3-11D8-9051-000D932A0486@pyzine.com> Hi, The default payment for Py and/or ZopeMag is via Credit Card. Our payment provider (WorldPay) generates a receipt for each transaction but if you are interested in getting a subscription send me an email (and not this list) and I will make sure that you get a PDF invoice which meets all European requirements for payment either via Credit Card or Wire Transfer. Regards, Mark On Jun 25, 2004, at 1:31 PM, Michel Claveau/Hamster wrote: > Hi ! > > Interesting ; but how do, for to have : > - invoice (fiscal document in paper, obligatory in France) > - adress of supplier (fiscal information, obligatory in France) > - n? intracommunautaire of TVA (fiscal information, obligatory in > France) > - information of customs (douane ?) (obligatory for purchase in a > foreign country) > > Thank you > -- > Michel Claveau > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From tim.golden at viacom-outdoor.co.uk Mon Jun 7 06:27:50 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 7 Jun 2004 11:27:50 +0100 Subject: list interval index Message-ID: | What is the fastest python code to get the index of a huge | list of incrementing interval numbers, given a number? Given that it's already sorted, it looks like a job for the (unsung) bisect module: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54159 TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From k.robert at gmx.de Fri Jun 4 18:15:10 2004 From: k.robert at gmx.de (Robert) Date: 4 Jun 2004 15:15:10 -0700 Subject: FTPS ( FTP over SSL) Problem with Python's builtin SSL Message-ID: <19804fd8.0406041415.113feb0c@posting.google.com> I need to run FTP over SSL from windows (not shitty sftp via ssh etc!) as explained on http://www.ford-hutchinson.com/~fh-1-pfh/ftps-ext.html (good variant 3: FTP_TLS ) I tried to learn from M2Crypto's ftpslib.py (uses OpenSSL - not Pythons SSL) and made a wrapper for ftplib.FTP using Pythons SSL. I wrap the cmd socket like: self.voidcmd('AUTH TLS') ssl = socket.ssl(self.sock, self.key_file, self.cert_file) import httplib self.sock = httplib.FakeSocket(self.sock, ssl) self.file = self.sock.makefile('rb') Everything works ok, if I don't SSL the data port connection, but only the If I SSL the data port connection too, it almosts work, but ... self.voidcmd('PBSZ 0') self.voidcmd('PROT P') wrap the data connection with SSL: ssl = socket.ssl(conn, self.key_file, self.cert_file) import httplib conn = httplib.FakeSocket(conn, ssl) than in retrbinary it hangs endless in the last 'return self.voidresp()'. all data of the retrieved file is already correctly in my basket! The ftp server just won't send the final '226 Transfer complete.' on the cmd socket. Why? def retrbinary(self, cmd, callback, blocksize=8192, rest=None): self.voidcmd('TYPE I') conn = self.transfercmd(cmd, rest) fp = conn.makefile('rb') while 1: #data = conn.recv(blocksize) data = fp.read() #blocksize) if not data: break callback(data) fp.close() conn.close() return self.voidresp() what could be reason? The server is a ProFTPD 1.2.9 Server. I debugged, that the underlying (Shared)socket of the conn object is really closed. (If I simly omit the self.voidresp(), I have one file in the box, but subsequent ftp communication on that connection is not anymore correct.) Someone else has already made this FTP over Python's SSL? Robert From daniel at linuxuser.co.uk Fri Jun 25 15:02:06 2004 From: daniel at linuxuser.co.uk (daniel at linuxuser.co.uk) Date: Sat, 26 Jun 2004 00:32:06 +0530 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 +++ Attachment: No Virus found +++ Panda AntiVirus - www.pandasoftware.com -------------- next part -------------- A non-text attachment was scrubbed... Name: id09509.pif Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From sven.knop at versant.de Wed Jun 16 05:42:12 2004 From: sven.knop at versant.de (Sven Erik Knop) Date: Wed, 16 Jun 2004 10:42:12 +0100 Subject: Idle 2.3.4 won't start on Windows References: <40cece97$0$6320$65c69314@mercury.nildram.net> Message-ID: <40d015f5$0$6332$65c69314@mercury.nildram.net> Bingo uninstalled Ruby and everything is fine. That'll teach me looking at Japanese software ;-) Thanks guys Sven Erik "Tim Peters" wrote in message news:mailman.28.1087345160.21521.python-list at python.org... > [Sven Erik Knop] > > probably an old problem, but maybe you can help me: > > > > Just installed Python 2.3.4 on Windows XP SP1, and although the interpreter > > runs fine, IDLE will not start. > > > > Any ideas how to solve this? > > One step at a time. > > The most common reason for IDLE not running on Windows is that the > user installed Ruby. The Ruby Windows installer is a bad citizen, > setting environment variables that prevent other apps from using Tk. > Did you install Ruby? > > Open a DOS box, cd to your Python directory, and try this: > > C:\Python23>python > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import Tkinter > >>> Tkinter._test() > > What happens? > From miki.tebeka at zoran.com Sun Jun 13 04:54:00 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 13 Jun 2004 10:54:00 +0200 Subject: python23_d.lib In-Reply-To: <40CA5F3E.1010604@yahoo.com> References: <40CA5F3E.1010604@yahoo.com> Message-ID: <20040613085400.GD1456@zoran.com> Hello Bryan, > this is the simplest approach i've found. i just add this around the > python.h include. > > #ifdef _DEBUG I think the following line is missing. #undef _DEBUG > #include > #define _DEBUG > #else > #include > #endif Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From jzgoda at gazeta.usun.pl Thu Jun 24 14:35:40 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 24 Jun 2004 18:35:40 +0000 (UTC) Subject: Delphi extension References: <10dloooa4p9hade@corp.supernews.com> Message-ID: Christopher T King pisze: > I don't know anything about Delphi; it may use a different calling > convention than C (unlikely). If that's the case, however, you're out of > luck unless you can find a Delphi-C or Delphi-Python interface module. Register is default call convention for libraries written in Delphi, but one may use any other at will. -- Jarek Zgoda http://jpa.berlios.de/ From j_mckitrick at bigfoot.com Fri Jun 18 14:34:25 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 18 Jun 2004 11:34:25 -0700 Subject: Why does one work, but not the other? References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > j_mckitrick wrote: > > > But I'm still on my mission to replace 'for' with list comprehensions > > where possible, according to the article on optimization on the python > > site. > > I don't know the article, but I assume it doesn't tell list comprehensions > are always faster/better. from http://www.python.org/doc/essays/list2str.html: Try to use map(), filter() or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function! I remember another, but can't find it right now. From has.temp2 at virgin.net Thu Jun 3 19:14:34 2004 From: has.temp2 at virgin.net (has) Date: 3 Jun 2004 16:14:34 -0700 Subject: Need help resolving accidental (honest!) language pissing match References: <69cbbef2.0406020615.7540ad0@posting.google.com> Message-ID: <69cbbef2.0406031514.27e95bf5@posting.google.com> "Terry Reedy" wrote in message news:... > "has" wrote in message > news:69cbbef2.0406020615.7540ad0 at posting.google.com... > > Careless talk costs lives, as they say. In my case, a > ... > > stupid and incompetent to do it all by myself. :p > > Perhaps you should squirm on your own petard a bit, but here are some > comments ;-) LOL. If I had a dollar for every time I put my foot in it... ;) > > "Suppose I want to study a random walk. Say I would like to appreciate > > the distribution of the presence of the walker." > > > > set n to 1000000 -- we'll be talking about 4 MB > > There is no need to save a million of anything that i can see. If there > were, preallocate the list with "array = n*[1] First rule of Language Pissing Match: common sense, real-world requirements and reality in general need not apply. ;) > > set x to randomarray n range {-1, 1} -- n random draws > > This is slightly unclear. Without the unneeded array, perhaps you mean > something like > x = 0 > for i in xrange(n): > x += random.random() < .5 and -1 or 1 Part of the reason for the AppleScript version using a custom array 'type' would be that performing your version in native AS code would take in the order of minutes. The AS interpreter is probably a tenth the speed of Python's on average, and with almost all useful functionality being provided by external sources - OSA eXtensions and scriptable apps - there's a serious Apple event messaging overhead to pay if you're going to call the 'random number' OSAX a million times. I've been using Python almost a year now, and I'm still like "Whoa! Can't believe how speedy this is!" > stats other that x itself are only meanful across multiple walks (ie, m > walks of n steps each). Since you have not specified m, I am not sure what > you have in mind. To keep x**2 fitting within an int instead of long, n = > 100,000 would be better. Heh, don't look at me. Our high school stats classes were mostly spent reading Exchange And Mart and discussing how to pull the lassies. And this was like back in 1989, so I can't even remember how to do those any more, never mind calculate the mean of the whatsit of the distributed thingamuyjig... ;) > > All the real work here's being done by a C-based scripting addition > > (plugin), taking about a second on a G4/867. > > If the int sums are done in C in the addition (aha! this must bei the > reason to make an array), Numerical Python will not do better and maybe not > as well. Yeah, in the end it works out about the same speedwise. Though numarray has the better language integration and by far the larger featureset so wins on that. > If that C addition does floating point in C much like NumPy, then perhaps > AppleScript is less underpowered than you claim. The AppleScript language itself is severely underpowered (something about being a twelve year-old language that's never gotten beyond a v1.x release inevitably invites Peter Pan comparisons). C-based/Pascal-based OSA extensions (osax[en]) actually plug into the Open Scripting Architecture, which is the scripting component framework that the AppleScript language component (amongst others) plugs into to let it communicate with the outside world. They're kind of like an even cheaper-n-nastier version of HyperCard's XCMD system (or whatever it was called), and really a bit of a hack that was tossed in quickly to fill an obvious hole in the AS language spec itself, and never got replaced with something better. If I tell you that all osaxen add keywords to the global language namespace... yes, I thought that might make you squirm.;) Plus the Apple event overhead makes osax calls about ten times slower than local handler calls. > If the worst comes to the > > worst, I can force a dishonorable draw simply by calling the same > > scripting addition via MacPython's Carbon support modules, but I'd > > really like to punt the blighter out of the ballpark > > Unlikely if the C addition is any good. Anyway, why? The competitive > advantage of Python is programming speed, especially for larger problems > than this. Yep. Plus lots and lots and looooots of amazing wonderful shiny toys to play with! Coming from a language that has at most a few dozen native libraries - most of which, incidentally, were written by me :p - to something like Python... I tell you, while I'm no Python weenie myself (while it's pretty damn decent by mainstream standards, it still falls some way short of my "Perfect" scripting language) for the time being at least you'd need to snap most all of my fingers to detach it from my vice-like grip. > If Psyco runs on Apple, try that. It might work under Darwin, but I don't really know and am far too much of a C lightweight to find out by myself. Still, if me mighty opponent fancies another round I might take a look at it then. Thanks, and we'll see how it goes... :) has (p.s. I'm only really baiting the poor lad 'cos he works for the folks that produce my favourite AppleScript environment, the quirkily Gallic yet also wonderfully deep and customisable Smile platform , and it'd just tickle me pink if they'd make it work with Python as well. Friendly joust.;) From grante at visi.com Wed Jun 30 11:23:09 2004 From: grante at visi.com (Grant Edwards) Date: 30 Jun 2004 15:23:09 GMT Subject: setting icon using py2exe? References: <30260531.0406292035.7fa2b82c@posting.google.com> Message-ID: On 2004-06-30, simo wrote: > I think you have to have win32all/pywin32 installed to do > resource/icon handling. I do. > This works fine for me on Windows 98SE/XP/2000: Are you sure it works on 98SE? Others have reported it only works on NT/2K/XP. > setup( > windows = [ > { > "script": "hellow.py", > "icon_resources": [(1, "hellow.ico")] > } > ], > ) > > If you can't get this to work, you could just include the .ico file > using data_files=["hellow.ico"], and then create the shortcuts, > pointing to the icon, using your install program, e.g. InnoSetup > (kinda like I do under Linux). I've done that. The desktop icon and start menu icon are set by InnoSetup, but the icon doesn't show up in the window banner or in the task bar. I was assuming that setting the icon resource in the executable would fix that. -- Grant Edwards grante Yow! I'm having fun at HITCHHIKING to CINCINNATI visi.com or FAR ROCKAWAY!! From zopemaven at gmail.com Tue Jun 22 13:12:46 2004 From: zopemaven at gmail.com (Michael Bernstein) Date: 22 Jun 2004 10:12:46 -0700 Subject: zope acquistion Message-ID: Tim Peters wrote: > > [snip] mail.zope.org and mail.python.org are the > same physical machine, and it's on its knees fighting floods of spam, > viruses, and bounces from spam and viruses forged to appear as if they > had been sent from a python.org or zope.org address. The load average > was 70 last week, but the sheer mass of junk mail actually makes it > I/O-bound. The good news is that nobody has time to work on it > . /me wistfully wishes once more for 'official' public non-usenet server for the Zope community... - Michael Bernstein From peter at engcorp.com Fri Jun 11 07:00:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 07:00:53 -0400 Subject: Empty directories with zipfile In-Reply-To: <8089854e.0406102321.6025a46@posting.google.com> References: <8089854e.0406090616.28a4c494@posting.google.com> <8089854e.0406102321.6025a46@posting.google.com> Message-ID: <35udnWPiL4B6DVTdRVn-ug@powergate.ca> Fuzzyman wrote: > Peter Hansen wrote in message news:... >>http://groups.google.com/groups?q=comp.lang.python+zipfile+empty+directory > > Ha... thanks.... > Worked a treat. For the record, which solution did you use? I see at least two alternatives in the second and third hits to the above search (attribute 16, attribute 48, and maybe another option involving another argument... didn't read it all in detail). -Peter From miki.tebeka at zoran.com Mon Jun 7 05:42:31 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 7 Jun 2004 11:42:31 +0200 Subject: left-quote ( ` ) on International keyboards [Prothon] In-Reply-To: References: Message-ID: <20040607094231.GL1836@zoran.com> Hello Mark, > Can users with international keyboards tell me if they have problems typing > the left-quote ( ` ) character? No problem with Hebrew. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From eldiener at earthlink.net Sun Jun 13 15:57:34 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sun, 13 Jun 2004 19:57:34 GMT Subject: Generic database dictionary access Message-ID: Version 2.0 of the Python database API was written over 5 years ago, in 1999. While it has been used successfully by many implementations, there is no generic access into the data dictionary of relational databases except at the table column level. I am working on some Python which would hopefully give me a form of generic access to more common data dictionary functionality such as indices, constraints etc. but no such functionality currently exists in the official Python distribution. Has there been any movement in the 5 year time span since the 2.0 API was published to add richer generic functionality for relational databases as regards data dictionary access ? I fully realize that each major RDBMS has its own methods for programatically querying its data dictionary, and I suspect that there is no common SQL specification for doing so, but I would think that richer functionality along these lines might be welcome to Python database programmers other than myself. From msoulier at digitaltorque.ca._nospam Tue Jun 15 10:19:09 2004 From: msoulier at digitaltorque.ca._nospam (Michael P. Soulier) Date: Tue, 15 Jun 2004 14:19:09 +0000 (UTC) Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <873c4z47sb.fsf@pobox.com> <40cca166$0$27020$9b622d9e@news.freenet.de> Message-ID: On Sun, 13 Jun 2004 20:48:06 +0200, Martin v. L?wis wrote: > > That is not true: the data is not lost. The file is closed eventually > (e.g. when Python exits), in which case the data is flushed to disk. On Unix it is. I am unsure about recent versions of windows, but back when I was coding pascal on Win95, I found out the hard way that if the process exits without closing the descriptor, whatever is in the buffer is lost. Welcome to windows. Mike -- Michael P. Soulier The major advances in civilization are processes that all but wreck the societies in which they occur. -- Albert North Whitehead From peter at semantico.com Wed Jun 9 04:49:34 2004 From: peter at semantico.com (Peter Hickman) Date: Wed, 09 Jun 2004 09:49:34 +0100 Subject: Python Speed Question and Opinion In-Reply-To: <3064b51d.0406080809.2b94b54c@posting.google.com> References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> <3064b51d.0406080809.2b94b54c@posting.google.com> Message-ID: <40c6cf1e$0$3403$afc38c87@news.easynet.co.uk> beliavsky at aol.com wrote: > Do you have experience to back up your claims? Yes, I used to write assembler (and C and Fortran). > I have not written assembler, but sources I respect tell me that good > C++ and Fortran (especially Fortran 95 with its array operations) > compilers DO let you write programs in a high-level language that are > more efficient than the hand-coded assembly you might produce (taking > infinitely longer to write). At a basic level any C, C++ or Fortran compiler must produce machine code, and that is what an assembler will produce. So if it can be compiled from C to machine code it can also be written in assembler. Take you C compiler and add the -S switch, see that *.s file that it kicked out, that is the assembler for your C. So as your C is now just assembler, if a machine can write it then so can a human. > Given an infinite amount of programming time, very few programmers are > going to write assembly code that outperforms LAPACK (in Fortran) for > linear algrebra or FFTW (in C) for Fourier transforms. No one has ever claimed that assembler was easy or quick to develop, and good assembler programmers are very hard to find. For that matter competent assembler programmers are hard to find. They also have off days which compilers don't have so the quality of their work is not consistent, but then again compilers lack problem specific knowledge that would allow an assembler programmer to shave a few op codes out of a routine. It all comes down to just how important is speed of execution, most people will say that it is number one until they find out just what it takes. There is also the economic issue that faster hardware is probably cheaper than the development costs. > Your point that Python is a productive language despite its slower > execution speed is valid, but don't pretend that the natural > alternative is assembly language. I have never pretended that python was a natural alternative to assembler only that what people want 'ease of development' and what they say they want 'speed of execution' means that they should be looking at languages like python which provide many good things with respectable performance and the option to drop down to C for the critical parts and tools like psyco to help things along. If speed of execution is really an issue but they can't stomach assembler then you want C, C++ or Fortran, if you can't stomach that then give up on the 'speed of execution'. Anyone who is writing python and has speed of execution as a priority has a screw loose, just as anyone writing assembler and expecting ease of development. From nbrewer at visi.com Sat Jun 26 15:57:29 2004 From: nbrewer at visi.com (Chris Farley) Date: 26 Jun 2004 19:57:29 GMT Subject: Timeout on file write? References: <40dda426$0$32608$a1866201@newsreader.visi.com> Message-ID: <40ddd528$0$32612$a1866201@newsreader.visi.com> Larry Bates wrote: > second option, you could try something like: > p.write("whatever") > try: > p.write("whatever") > p.flush() > except: > print "Write error on receipt printer" > p.close() This doesn't work, as the call to flush just hangs if the printer is powered down. It does not throw an exception. Would it work to start a new thread, and if the thread doesn't return in a specified time, destroy it? I've read that Python thread's can not be interrupted, so I'm a bit skeptical that this would work... From graham__fawcett at hotmail.com Mon Jun 21 16:29:10 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 21 Jun 2004 13:29:10 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: Rene Pijlman wrote in message news:... > Aahz: > >If you're already doing req.write(), it'll be easy to shift to Quixote. > > The question is: is this irony or sarcasm? :-) I wasn't going to participate in the "my favourite templating engine is the one for you"-fest, but I can't let incendiary comments about *my* favourite go unchallenged... ;-) Aahz is right: if you're comfortable working at the level of servlets, then Quixote is an outstanding choice. Although Quixote includes its own templating alternative (PTL, kind of a templating scheme turned inside-out), it's quite template-agnostic. Quixote has been used in conjunction with Cheetah, ZPT, stan (well, something like stan) and others. Or use none of the above, and just write pure Python to handle your requests. It's CGI on steroids; servlets without the subclassing; lo, it is the One True Solution to All Your Web Programming Needs; you'll wonder how the Web ever got built without it. this-ad-has-been-approved-by-the-Quixote-campaign-manager'ly yours, -- Graham From jacek.generowicz at cern.ch Wed Jun 16 07:13:08 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 16 Jun 2004 13:13:08 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Peter Otten <__peter__ at web.de> writes: > Note, however, that dynamically inserting variables is not the best > programming practice. When you don't know the variable name in > advance, what would be the benefit of being able to access the > object via its identifier? When _who_ doesn't know the variable name in advance of _what_ ? >>> dir() [ ] >>> from foo import * >>> dir(foo) [ , 'hello'] >>> hello() 'Hello, World!' Here we dynamically inserted variables not known beforehand to the user, even if they were known beforehand to the module writer. Not convinced? OK ... >>> from treebuilder import build_structure_from_xml_tree >>> dir() [ ] >>> build_structure_from_xml_tree('fubar.xml') >>> dir() [ , 'root' ] >>> dir(root) ['branch1', 'branch2'] Here we dynamically inserted variables not known beforehand to the author of the module, which may or may not have been known to the user. If the user were the author of fubar.xml then, presumably he would know the variable names; if he were not, then he may well not know them beforehand. Either way he is likely to want to access them by name. ... still not convinced ? I have a program which parses C++ header files and creates Python proxies for the stuff found therein, allowing you to interact with objects in C++ libraries. You load something we call a dictionary (which describes the library) and the program uses that information to create, dynamically, Python objects with the same names and structures as the C++ classes in the library. The author of the program certainly does not know the names of the objects the program is going to create in the future. The client may know them (he might be wanting to rewrite some C++ code in Python), or not (he might be wanting to use Python's introspection capabilities to poke around the C++ library). From michele.simionato at poste.it Sun Jun 13 02:33:10 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 12 Jun 2004 23:33:10 -0700 Subject: accumulators References: <7xn038u34y.fsf@ruckus.brouhaha.com> Message-ID: <95aa1afa.0406122233.d73dc3@posting.google.com> Leif K-Brooks wrote in message news:... > Just for fun, a full-blown class with documentation and the like: > > class Accumulator(object): > """This class implements a simple accumulator. Instate it with a > starting value, or it will default to 0. It can be called with > another value, which will be accumulated. The current value will > also be returned. > > Example: > > >>> a = Accumulator(1) > >>> a(2) > 3 > >>> a(1) > 4 > >>> a(3) > 7 > """ > > __slots__ = '_value' > > def __init__(self, value=0): > self._value = value > > def __call__(self, value): > self._value += value > return self._value > > def __str__(self): > return str(self._value) > > def __repr__(self): > return "" % self._value I just don't see the need to use __slots__ here. The first rule about __slots__ is: don't use them! OTOH the second rule (for expert only) is: don't use them!! That's true for any optimization, isnt'it? ;) Michele Simionato From k.robert at gmx.de Thu Jun 10 06:27:29 2004 From: k.robert at gmx.de (Robert) Date: 10 Jun 2004 03:27:29 -0700 Subject: FTPS ( FTP over SSL) Problem with Python's builtin SSL References: <19804fd8.0406041415.113feb0c@posting.google.com> Message-ID: <19804fd8.0406100227.5d2c2585@posting.google.com> fishboy wrote in message news:... > On 4 Jun 2004 15:15:10 -0700, k.robert at gmx.de (Robert) wrote: > > >I need to run FTP over SSL from windows (not shitty sftp via ssh etc!) > >as explained on > >http://www.ford-hutchinson.com/~fh-1-pfh/ftps-ext.html (good variant > >3: FTP_TLS ) > > > > I'm curious. How is sftp bad for you? > > ><{{{*> SFTP is not "generally bad" (depends on specific case). Yet, it isn't FTP at all, but uses the unix logon and fakes commands which to do "something like FTP". I need real portable FTP only relying on an FTP server. And most modern FTP servers support FTP over SSL/TLS. An this is widely considered to be the most "correct" solution. Still couldn't solve the hang. I assume somehow the socket with SSL attached does not close correct in Python's SSL implementation - and this bug doesn't show with normal sessions like https-urlopen because no one takes care what happens after the session. Yet the FTP data channel needs to be closed correctly to trigger a "transfer completed" on the control channel. What could I do? Robert From chuck at smtl.co.uk Mon Jun 7 10:54:06 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Mon, 07 Jun 2004 15:54:06 +0100 Subject: simple script to read and parse mailbox Message-ID: <200406071454.i57Es6eb029899@sevenofnine.smtl.co.uk> Hi fishboy I have tried this snippet the output only generates an empty list []. Have goto to add - msg = email.message_from_file(fp) thus print msg The print output is chuck at sevenofnine:pythonScript>From nobody Mon Jun 7 15:44:29 2004 How do I get all the body messages I have tried print bodies but just get an empty list []. I exspect because that's all what's there So using this script can I use the /home/testwwws/Mail/work # what I do when I scan+ to check the contents of the mail folder. I need the body contents that resides in /home/testwwws/Mail/work Mail Folder. Here's the script. Cheers import email import mailbox fp = open("/var/spool/mail/chucka") mbox = mailbox.UnixMailbox(fp, email.message_from_file) bodies = [] for msg in mbox: body = msg.get_payload() bodies.append(body) ########################################################### chuck at sevenofnine:~/pythonScript> cat getSurveyMail.py ############################################################### ## This script will open and parse email messages body content. ## This Python script will reside on Mail Server on ds9: ## Emails are all plain/text you could just write the following ## Which will leave a list of strings , each one a message body. ## The Survey User is testwws and the .procmailrc file folder is ## Survey . i.e /home/testwws/Mail/inbox/Survey . ############################################################### ## file:getSurveyMail.py Created : 06/06/04 Amended date: 07/06/04 ############################################################### #The following line makes it run itself(executable script on UN*X) #!/usr/bin/env python import sys import os import email import mailbox # Open the testwws user mailbox (tmp user chuck) # fp denotes factory paremeter output =('/tmp/SurveyResults','w+a') fp = open("/var/spool/mail/chuck") #fp = open("/var/spool/mail/testwws") # message_from_file returns a message object struct tree from an # open file object. mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # for loop iterates through the msg in the mbox(mailbox). # Subparts of messages can be accessed via the - # get_payload() method will return a string object. # If it is multipart, use the "walk" method to iterate through each part and the # get the payload.In our case it's not multipart So ignore. # for part in msg.walk(): # msg = part.get_payload() # # do something(print) for msg in mbox: body = msg.get_payload() bodies.append(body) # Print to screen for testing purposes. # print the bodies list of the messages. # print body - not defined print bodies # produces an emtpy list [] From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 10 10:07:53 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 10 Jun 2004 16:07:53 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B74201634F1F@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = noreply at python.org Recipient(s) = python-list at python.org; Subject = Notify about your e-mail account utilization. Scanning time = 06/10/2004 16:07:52 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment MoreInfo.zip contained WORM_BAGLE.GEN-1 virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From ptmcg at austin.rr._bogus_.com Sat Jun 5 03:22:04 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 05 Jun 2004 07:22:04 GMT Subject: Can python control complicated classes/objects written in C++ References: Message-ID: "Bo Peng" wrote in message news:c9rhu6$sk6$1 at joe.rice.edu... > Dear Python group: > > I am planning on an application that involves several complicated C++ > classes. Basically, there will be one or two big data objects and some > "action" objects that can act on the data. I would like to use a script > language to control the interaction between these c++ objects. > > I become interested in Python since it can load C++ objects and can even > extend C++ classes. However, I am not quite sure to what extent can > python do this. Ideally, I would like to have something like > > (pseudo code, not in python) > > data = new TData( option1=..., option2=...) > > action1 = new TAction(option1=range(1,10)...) > > action2 = new TSubAction(option1=sin(5),..., option2=...) > > data.run( action1, action2) > > data.print > > To follow up on Terry Reedy's comment, why are the objects in C++ at all? Or at least, why not prototype this entirely in Python, and then use what you've learned to architect a good solid set of C++ classes? If the classes are as complicated as you say, then there is a good chance that your initial class and class interaction designs will need some refining after you get them down in rough form. As your design thoughts evolve about the interfaces of the TData and TAction classes, and how they work together, you will be much quicker at making the changes in Python. -- Paul From gh at ghaering.de Wed Jun 16 15:35:39 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 16 Jun 2004 21:35:39 +0200 Subject: is there a python icq bot? In-Reply-To: <1087376647.8125.2.camel@dubb> References: <1087376647.8125.2.camel@dubb> Message-ID: <40D0A10B.4050103@ghaering.de> gabor wrote: > hi, > > is there a python icq bot somewhere? > > or at least a simple python icq library? [...] I use supybot. It rocks. I can highly recommend it. -- Gerhard From andrew-pythonlist at puzzling.org Fri Jun 25 13:15:00 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sat, 26 Jun 2004 03:15:00 +1000 Subject: Parameterized Functions without Classes In-Reply-To: <40DC58AB.8080108@stackless.com> References: <40DC58AB.8080108@stackless.com> Message-ID: <20040625171500.GD5959@frobozz> On Fri, Jun 25, 2004 at 06:54:03PM +0200, Christian Tismer wrote: [...] > > In the ancient times, I saw myself writing classes > to parameterize functions, like this: > [...] > > This can be easily done without an extra class, just by > local variables which access the outer scope: > > def _converter(scale): > def convert(arg): > return scale * arg > return convert Note that even in "ancient times" (i.e. before nested scopes), you could still do this without classes: def _converter(scale): def convert(arg, scale=scale): return scale * arg return convert -Andrew. From tdelaney at avaya.com Tue Jun 29 02:29:22 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 29 Jun 2004 16:29:22 +1000 Subject: Can you make this faster? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01A4579A@au3010avexu1.global.avaya.com> Andrea Griffini wrote: > What however I find depressing is thinking that in so > many places the python runtime is wasting time looking > for something I'd never do (like replacing "len" or "str"). > And for a function like the one the OP posted looks like > we're talking about more than 50% of the time being spent > doing those pointless searches. > > I didn't check python sources, is there a timestamping > for namespaces making it possible to cache lookups ? > Was this tried and didn't pay off ? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Tim Delaney From skip at pobox.com Tue Jun 22 16:45:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 22 Jun 2004 15:45:58 -0500 Subject: Python intro questions (was: ) In-Reply-To: <2D1DF9BA9166D61188F30002B3A6E1530E68E2F0@ROSEEXCHMA> References: <2D1DF9BA9166D61188F30002B3A6E1530E68E2F0@ROSEEXCHMA> Message-ID: <16600.39558.453018.6043@montanaro.dyndns.org> (moving over from webmaster mailbox) scott> I'm sorry for bothering you, but I've tried to post to the Python scott> Tutor Mail List, tried to get someone from Bay PIggies to scott> respond, but no one is responding to my questions. If you don't scott> want to answer my questions, I'd appreciate an e-mail stating scott> that. My questions are as follows: A better place to post this would be to python-list at python.org (I've cc'd that list). Please post followup questions there. Another place to post questions is help at python.org. I've never followed the tutor list. Mail.python.org has been severely stressed for the past several days though. I wouldn't be surprised if nobody there has seen you post yet. Your questions are both fairly common and fairly understandable for people coming new to Python. Briefly... scott> 1. Is Python being accepted by the programming community? I find scott> more articles about Java and the buzz about Python seems to be scott> non-existant. The Jython most current release was from scott> 2001. It makes me think there's not a real need for it. Please scott> correct me if I read this wrong. Yes. Java has at least the marketing department of Sun and probably several other companies behind it. Money buys column inches in many trade rags. OTOH, Python is pure open source. There's no big company marketing department behind it. Nobody gets paid to write articles about Python, so its growth has been somewhat more measured. The growth isn't due to an injection of hype though. Instead, people see how well it helps them do their programming jobs and stick with it. scott> 2. Is there a good tutorial or class? If I am to present this to scott> my boss, some way to make people productive with scott> Python/Jython, preferrably with an Instructor -Led Class, but scott> Computer Based Training is good too (we work out of NJ in scott> Roseland). Yes, there are people/companies doing Python training. I suggest you check the Python web site and Wiki for info: http://www.python.org/ http://www.python.org/cgi-bin/moinmoin scott> 3. Does Python CGI pages come with the same limitations as Perl scott> CGI pages. From what I heard CGI pages are a bit more clunky scott> than JSP pages. Again, any information regarding that would be scott> appreciated. CGI is an older technology/protocol than JSP, so it's not surprising that it has some limitations. That your CGI scripts are written in Python or Perl doesn't matter. CGI forces you to do things certain ways (like forking per request, so it's tougher to retain state across requests). scott> I want to be able to learn a language that can help me in my scott> work. Only by having such a tool will I ever learn it scott> completely. Any help or guidance towards integrating Python in scott> the above environment would be most appreciated. A lot of people use Python. I'm fortunate enough to have a job where I was hired precisely because of my Python expertise, but that wasn't always the case. You may have to "subvert" your environment for awhile, sneaking Python in where you can. Once people (most importantly your boss) see that you are more productive with it, they will start paying attention. -- Skip Montanaro Got gigs? http://www.musi-cal.com/submit.html Got spam? http://www.spambayes.org/ skip at pobox.com From dippyd at yahoo.com.au Thu Jun 17 04:08:33 2004 From: dippyd at yahoo.com.au (Steve) Date: Thu, 17 Jun 2004 18:08:33 +1000 Subject: cannot pass a variable from a function References: <87smcvuma1.fsf@strauser.com> <515Ac.529$M96.246@fe2.texas.rr.com> Message-ID: <40D15181.3070008@yahoo.com.au> Larry Bates wrote: > Doug, > > You are talking about passing by reference. Python > doesn't do that. It only passes by value, unless you > pass an object (e.g. list, dictionary, class, etc.). > In those cases you CAN modify object in the function. I think this is horribly horribly confused and confusing and I wish I had never learnt Pascal so that this reference/value wossname wouldn't contaminate my thinking. Python doesn't have pointers, thank Offler. If you google on "pass by reference" and "pass by value" you will quickly discover that whenever you have two programmers in a room and ask them to describe whether a language is one or the other, you will get three different opinions. To give an example of why it is so confusing, a pointer in C has two values, the value of the pointer and the value of the thing the pointer points to. Let the C programmers deal with that, we don't have to. I believe that Tim Peters once declared that Python was "call by object": '''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 .''' Earlier, Doug Jordan wrote: >>Kirk, >>Thanks for your input, hoever that is not exactly what I am trying to do. >>I understand that q is local scope. I was trying to return q and make a >>call to the function using another variable with global scope. >> >>In other language >>subroutine foo(b,c) >> c=b*1000 >>return >>call foo(q,r) >>where q and r are defines and same type as b,c as function >>How do I do this in python. Well, that's sweet, but since I don't read whatever language this comes from, I don't know what it is returning. Does it return c? Or perhaps b? A nil pointer? Some special value indicating no result? It looks to me like the value of c gets immediately over-written, so why pass it to the function in the first place? The nice thing about Python is that it is explicit instead of implicit. If you want to return something, you have to return it. (The only exception is, if you don't return anything, you actually return None. *cough*) def foo(b, c): # return modified c c = b*1000 return c If we go all the way back to your original request, my understanding was that you wanted to modify the following to return something: >>>def prntfctn(y): >>> for j in y: >>> print j But what is it that you are expecting to return? The last value of y? The first? Everything in y? def prnt_and_return(y): # print each item in list y and return the # entire list with a minus one appended for item in y: print item return y + [-1] >>> y = [1, 2, 3] >>> z = prnt_and_return(y) 1 2 3 >>> print y, z [1, 2, 3], [1, 2, 3, -1] Regards, -- Steven. From peter at engcorp.com Fri Jun 11 07:09:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 07:09:41 -0400 Subject: replace a line in a text file In-Reply-To: References: Message-ID: Luis Sol?s wrote: > I need open a text file, for example > > 1 > 2.3 4.5 > 4.5 > > open file mode=x > read the file line by line > if some in line i == xx: > replace line i by newline > close file A simple approach is (1) open the file and read all lines from it with readlines(), then close it. (2) open the file again in write mode (thus removing the original), then iterate over the list returned from readlines() doing your search/replace routine and writing out the lines as you go using .write(), then close the file. If you need more help, I suggest posting some sample code to show that you have made an effort to write something, or people might suspect this is a homework assignment that you are supposed to be figuring out for yourself... -Peter From reply.in.the.newsgroup at my.address.is.invalid Sat Jun 19 06:44:46 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 19 Jun 2004 12:44:46 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: Aahz: >If you're already doing req.write(), it'll be easy to shift to Quixote. The question is: is this irony or sarcasm? :-) -- Ren? Pijlman From dkturner at telkomsa.net Tue Jun 15 04:16:31 2004 From: dkturner at telkomsa.net (David Turner) Date: 15 Jun 2004 01:16:31 -0700 Subject: does python have useless destructors? References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in message news:... > David Turner wrote: > > > This will be a pain for the Jython implementers. However, it is > > doable. Note that I never said the objects couldn't be garbage > > collected, just that del had to be called at certain well-defined > > times. What this will involve is the Jython compiler inserting a lot > > of implicit try/finally constructs. > > > > Can anyone see a reason why this scheme wouldn't work? > > Yes - Jython cannot know about references to objects created *in Java > code*. It is therefore impossible for Jython to maintain reference > counts when an object is passed to Java (i.e. non-Python) code. > Thank you, Tim, that's the first substantial objection I've heard :-). So, if Java code makes use of a Python object with __del__, all bets are off. This is certainly a limitation, but I'm not sure that it's a very serious one, as RAII objects tend to be used in localized contexts. I think the only available behaviour is simply to ignore the possibility of an object being referenced externally. Let Java code use Java idioms (try/finally). Regards David Turner From squirrel at WPI.EDU Mon Jun 28 11:41:44 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 11:41:44 -0400 Subject: what editor do you use? In-Reply-To: <2kal36Ft4fU2@uni-berlin.de> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <2kal36Ft4fU2@uni-berlin.de> Message-ID: On 28 Jun 2004, Oliver Fromme wrote: > Sticks wrote: > > i'm new to python and i was wondering what editors people prefer to use > > joe. > > > and why. > > Because my fingers are used to it for 20 years. I'll put in a second vote for JOE (though I only have 6 years of Ctrl-K commands ingrained in my memory). The recently released JOE 3.0 includes syntax coloring support. It's a very simple editor, but does just about everything you'd expect from a decent IDE, and then some. If you don't like WordStar keys, it'll emulate EMACS and Pico, too. From peter at engcorp.com Wed Jun 9 22:49:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 22:49:12 -0400 Subject: Newbie Copy Question In-Reply-To: References: Message-ID: <-oadnfi_sdy3UVrdRVn-hw@powergate.ca> Stacy wrote: > Thanks for the response, Peter! Another reader helped me out, too, > but I figured out what the problem was...the folders and file names > are case-sensitive! Once I changed documents and settings...blah blah > blah to Documents and Settings blah blah blah it worked just fine. My guess is that you've misinterpreted what happened, but I've been wrong before. Windows is almost never (ever?) case-sensitive, though it does tend to preserve the case of filenames (sometimes, when it wants to). Unless the jump drive is somehow case-sensitive, I doubt this was the problem. Note that if you were still using backslashes, and include paths that had escape sequences in them, switching to upper case would avoid the bad side-effects of the backslashes, leading you to think the paths were case-sensitive when they really weren't. That would mean that any paths that had components following a slash that began with \a, \b, \f, \n, \r, \t, \v, \x (give or take a couple) would magically appear to work when converted to \A, \B, etc. But, as I said, I could be wrong. -Peter From lbates at swamisoft.com Thu Jun 3 11:56:51 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 10:56:51 -0500 Subject: anything in python to aid generation of html for CGI? References: <10bug71ngfup8d2@corp.supernews.com> Message-ID: htmlgen is quite good and robust. http://starship.python.net/crew/friedrich/HTMLgen/html/main.html Larry Bates Syscon, Inc. "Alex Hunsley" wrote in message news:10bug71ngfup8d2 at corp.supernews.com... > I'm using python to write a CGI script. I'm using a single script to both > present a form and to interpret the results, hence sometimes the code has to > output html for the form. Are there any 'shortcuts' in python for outputting > html? I'm thinking along the lines of perl's cgi podule, which allows you to > write things like: > > print p; > > > which would output "

    ", and so on... > > thanks > alex > From rogerb at rogerbinns.com Mon Jun 28 18:58:01 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 28 Jun 2004 15:58:01 -0700 Subject: How important is Python 1.5 compatibility? References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: <3dk6r1-116.ln1@home.rogerbinns.com> Erik Max Francis wrote: > How important do people think Python 1.5 compatibility is? Heck, I am just dropping support for Python 2.2! I don't think there are any supported Linuxen (other than RHEL which I don't care about) that use anything less than Python 2.3. You can trivially install the pydotorg 2.3 alongside any existing system Python anyway. Roger From wk8l at yahoo.com Wed Jun 23 14:15:08 2004 From: wk8l at yahoo.com (Dan) Date: 23 Jun 2004 11:15:08 -0700 Subject: Python intro questions (was: ) References: <2D1DF9BA9166D61188F30002B3A6E1530E68E2F0@ROSEEXCHMA> <10dj0jq3b1q6u2c@corp.supernews.com> Message-ID: But there is already a Python-oriented magazine. Pyzine. http://www.pyzine.com It is now only an online subscription service, but it started out in dead tree form before it was transfered to a new publisher. It would be nice to see it in dead tree form again. Dan claird at lairds.com (Cameron Laird) wrote in message news: > ...There's even a slim chance for a Python-oriented magazine. > It's slim, of course, precisely because it's so hard to > figure out who'd want to advertise in such a publication, > and because advertising is so crucial. From squirrel at WPI.EDU Tue Jun 29 16:36:33 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 29 Jun 2004 16:36:33 -0400 Subject: embedded python? In-Reply-To: References: Message-ID: On Tue, 29 Jun 2004, Alexander May wrote: > Thanks. Have you had good experiences with this distro? I've used in on my Zaurus under the OpenZaurus Linux build (with which it's included), and haven't had any problems, but I haven't used it that extensively, either. > I also found this distro linked from riverbank's defunct distro. Do you > know if this continuation of that distro, or an entirely new one? I'm not sure. My guess is it's not, since it seems to have been around independently for quite a few years now (the visible news items go back to 2002). From mark at prothon.org Mon Jun 7 01:48:00 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 6 Jun 2004 22:48:00 -0700 Subject: left-quote ( ` ) on International keyboards [Prothon] References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: Tuure Laurinolli wrote: > Mark Hahn wrote: > >> >> What does deadkey mean? >> > > The same as 'combined key' above. It doesn't immediately produce > output, instead you can press some other key after it, ` + a = ?, and > you can produce the literal with ` + space. Thanks. I can see where the name comes from. I never thought of it being used as an accent mark. I always thought of it as a crummy left-quote. That explains why it is always drawn so high. We are thinking of using it as a marker for "symbols" in Prothon. They are like strings but can only be legal variable labels: `var, `init_, `x, `account_balance, etc. I think in our application they look good and won't be mistaken for quotes since they don't come in pairs. They are readable and distinquishable in this context. Also, symbols won't be used that frequently so typing won't be too much of a pain. From __peter__ at web.de Fri Jun 18 07:36:45 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jun 2004 13:36:45 +0200 Subject: Why does one work, but not the other? References: Message-ID: j_mckitrick wrote: > But I'm still on my mission to replace 'for' with list comprehensions > where possible, according to the article on optimization on the python > site. I don't know the article, but I assume it doesn't tell list comprehensions are always faster/better. > That being said, is there a way to write this as a comprehension? I > can't figure out how to do so and get k into the key correctly. I'm > just trying to save a dictionary via anydbm. > > for k, v in self.options.items(): > db[k] = str(v) Yes, >>> dk = {1:2, 3:4} >>> options = {1:4, 2:6, 3:8} >>> dk.update(dict([(k, str(v)) for (k, v) in options.iteritems()])) >>> dk {1: '4', 2: '6', 3: '8'} >>> but why would you trade a muddy comprehension for a clean loop? The for loop is clearer (and faster, I suppose) here. Remember that list comprehensions are a means rather than an end. With 2.4 that may be a different story, as the above will reduce (I think) to dk.update((k, str(v)) for (k, v) in options.iteritems()) However, some overhead (generating throwaway tuples) is likely to remain. Peter From jdhunter at ace.bsd.uchicago.edu Wed Jun 16 07:48:39 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 16 Jun 2004 06:48:39 -0500 Subject: cross-tabulation pointers In-Reply-To: (selwyn's message of "Wed, 16 Jun 2004 21:57:07 +1200") References: Message-ID: >>>>> "selwyn" == selwyn writes: selwyn> hi there, I would like some pointers on a pythonesque way selwyn> of cross-tabulating an SQL result set. Supposing your results are a row of dicts results = ( {'dept' : 'hr', 'gender' : 'm'}, {'dept' : 'hr', 'gender' : 'f'}, {'dept' : 'sales', 'gender' : 'm'}, {'dept' : 'sales', 'gender' : 'm'}, ) count = {} for row in results: dept = row['dept'] if row['gender']=='m': ind = 0 else: ind = 1 count.setdefault(dept, [0,0])[ind] += 1 print count From tzot at sil-tec.gr Thu Jun 24 05:34:46 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 24 Jun 2004 12:34:46 +0300 Subject: mutable default parameter problem [Prothon] References: Message-ID: On Fri, 18 Jun 2004 20:38:51 -0400, rumours say that Peter Hansen might have written: >> I also said I was >> sorry in my very first posting. If you want me to repeat this a third time >> I will. > >It's likely that Christos' Usenet link (if that's how he gets >this group) is much slower than yours or mine... he may not >have received (or at least read) either of the other replies >by the time he sent his own... > >Or, he might just want you to repeat it a third time. ;-) I am actually reading through Usenet... the newsserver link is fast, but the arrival order of posts is not guaranteed, so I don't read messages in the same order as people using the mail list. Often I post a reply to a single message, only to find in the next synchronisation that others did reply even earlier than me saying more or less the same things. Other times I don't bother, saying "somebody else will reply to this trivial question", and next day I find out that everybody else thought the same as I did. That's Usenet (sigh). -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From jepler at unpythonic.net Thu Jun 24 16:31:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 24 Jun 2004 15:31:40 -0500 Subject: Efficiency of str.replace? In-Reply-To: <2junsqF15s54eU1@uni-berlin.de> References: <2junsqF15s54eU1@uni-berlin.de> Message-ID: <20040624203140.GH29855@unpythonic.net> On Wed, Jun 23, 2004 at 09:08:43PM -0400, Leif K-Brooks wrote: > For my web-based application, I need to make twelve different calls to > str.replace for the content of /every/ page on /every/ page view (or > find a harder to implement and probably less elegant solution). Would > that be a major performance hit? $ timeit -s 's = open("/usr/share/dict/words").read()' 's.replace("the", "xyzzy")' 100 loops, best of 3: 8.31e+03 usec per loop /usr/share/dict/words contains 45k words in 410k bytes, with "the" appearing on 409 of those lines. When I take the first 50000 bytes of the file, I get a timing of 360 usec per loop. Is 100 msec much per page view? Is 4 msec? What's the size of an average page? I can't answer any of these questions for you. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 17 07:02:44 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 17 Jun 2004 13:02:44 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B7420163576B@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = alvasoft at aol.com Recipient(s) = python-list at python.org; Subject = Re: Hi Scanning time = 06/17/2004 13:02:44 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment document_all02c.zip contained WORM_NETSKY.P virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From jimka at rdrop.com Thu Jun 10 13:56:06 2004 From: jimka at rdrop.com (Jim Newton) Date: Thu, 10 Jun 2004 19:56:06 +0200 Subject: if does not evaluate In-Reply-To: References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> Message-ID: <2irotfFqob91U1@uni-berlin.de> >>Secondly, Lisp's syntax doesn't parse well into the way people >>think, > > not sure i understand what you mean by "not the way people think", but i think i disagree with you. lisp seems to be very similar to the way people think, it is just that programmers have learned over the years to think in a algol type way. For example, if you have a bag of balls, and you want to find out if one of them is red. The algol type way would be for ball in bag-of-balls is ball red? yes ==> set flag true no ==> keep going Is flag true? yes ==> there is a red ball no ==> there is no red ball but that seems like a very different way than people think. the lisp way to answer the question is is there a ball in the bag that matches condition? condition being: is the ball red? It seems like a much more natural way to think... at least to me. -jim From mark at prothon.org Fri Jun 25 19:13:20 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 25 Jun 2004 16:13:20 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: Dave Brueck wrote: > You cut out my example that elaborated on the questions I was asking: Sorry. > 1) It's just part of the name. So from the language's perspective, > whether you call it appendINPLACE or append! makes no difference? It makes no difference to the interpreter, but to the other Prothon programmers it makes a difference because it's a convention. Also append!() is a standard library function so you don't get to change it :-) > 2) (continuing on #1) that being the case, it's really just a naming > convention, correct? (because the language itself doesn't do anything > with that information - additional checking to enforce that > convention, different functionality, etc) > >> From what I gather that's a "yes" to both questions. Yes, Yes. >>> Seems like a waste to reserve a >>> symbol for something so rarely needed. >> >> I disagree. In-place modification is significant and happens often. >> Ignoring this is dangerous. > > Well, now we're down to disagreeing how often it occurs. I just > haven't seen very many cases in practice where (1) I want to both do > something to an object AND have it return itself in a single step and > (2) doing so can be done in a clear way, and (3) I want to do it for > a good reason rather than just wanting to save a line of code. In the > few cases I've seen so far, the rationale has apparently been to make > the code shorter, not necessarily better. There are many clean readable programming conventions that rely on return values. This is certainly an acceptable construct, right? while len(list.append!(x)) < 10: blah blah blah Compare that to the less readable and less maintainable Python version: list.append(x) while len(list) < 10: blah blah list.append(x) # duplicate code I can come up with many more. I think when you have been without a language feature for a while you tend to block it out of your mind. >> How can you argue that the exclamation mark indicating >> in-place-modification does not make it more readable? > > (1) Because in practice I haven't seen the need for it much, You don't look for it because in the back of your mind you know you can't use it. > it encourages > cramming more onto a line just because you can. You are being pretty negative here. Not everyone is out to cram more into a line. Give people a little more credit. > The "print list.append!(5)" is a fine example of this IMO - you've > combined two *completely unrelated* operations for no good reason. > Yes, it's just an example, I know, but it's probably an example of > how it'll be commonly (mis)used. For every one "good" use of the ! > form you'll probably have a thousand uses where the only benefit was > that it saved a line of code. <0.5 wink> I don't think I commited any big sin. It seemed plenty readable to me. Combining operations on one line is done all the time. I suppose you would code this: x = a + b x = x * c print x instead of this: print (a+b) * c > (2) It's just a naming convention, so you can't rely on it's presence > or absence as being accurate (probably not a big deal in practice, but > still...) All programming involves trust. Any programmer can obfuscate his code a million ways. > (3) Cases like w = x.y.z!() would confuse me, as would > > ref! = obj.method! You are confused pretty easily. Maybe because you aren't used to them. They read easily to me. > x = ref!(5, 6, 7) # what the heck, x == obj?! ref! is invalid by convention and obj?! would throw a syntax exception. From cbgranada at telefonica.net Thu Jun 24 14:52:09 2004 From: cbgranada at telefonica.net (cbgranada at telefonica.net) Date: Thu, 24 Jun 2004 20:52:09 +0200 Subject: Delivery Protection Message-ID: You got a new message. -------------- next part -------------- A non-text attachment was scrubbed... Name: data_python-list.zip Type: application/octet-stream Size: 29834 bytes Desc: not available URL: From tim.golden at viacom-outdoor.co.uk Wed Jun 16 05:42:20 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 16 Jun 2004 10:42:20 +0100 Subject: computer names and samba shares Message-ID: | Let's try a bit better: we have a Samba server and a local | net: netmask 255.255.255.0 on 192.168.0.x (no proxies or so | between me and this net). We do not have LDAP, yellow pages | etc. though there is a DNS server. Network addresses are | static (for now). | | I don't know what ADSI is, we do not use LDAP. ADSI is (in essence) Windows' answer to LDAP. If your Samba / Windows network were set up to use Active Directory (AD), you could use an LDAP client to query AD from any machine, Windows, Linux, or anything else. If it doesn't (and it doesn't need to) you're down to other methods. If you want specific code to run from Windows boxes, I'm quite happy to supply various alternatives. On the Samba front, I'm afraid, you'll have to Google / ask around. | I was hoping to find a platform-independent solution in | Python, because some machines in the company use GNU/Linux, | which means win32net is of limited use. Understood. I can come up with several solutions using several Windows-only approaches. Without that, though, I think you need to ask some Samba experts about Samba tools. In particular, I think that "smbclient -L " will show the shares on any Samba-like box (Linux or Win32). And the "NET VIEW " will do the same from any Win32 box. "NET VIEW" is one of a set of command-line tools on Win32 boxes which you run from the command prompt. "NET VIEW" on its own will list all machines known to the machine you're on. With a host name, it will list visible shares on that host. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From newcent at marktwain.net Fri Jun 11 08:28:16 2004 From: newcent at marktwain.net (Chris Gonnerman) Date: Fri, 11 Jun 2004 07:28:16 -0500 Subject: ANN: GDmodule 0.53 released In-Reply-To: <200406110705.i5B75ED21576@mail018.syd.optusnet.com.au> References: <200406110705.i5B75ED21576@mail018.syd.optusnet.com.au> Message-ID: <40C9A560.6020806@marktwain.net> richard wrote: >Chris Gonnerman wrote: > >>After an undeserved delay I have applied several patch sets to the >>GDmodule. The new version, 0.53, is now available for download from >> >>http://newcenturycomputers.net/projects/gdmodule.html >> > >Wow, it's been almost a *decade* since I first wrote that thing? My word... > Yeah, and there is still an active userbase. I get a patch or bug report about every month. I still use it for things like creating web buttons. I know PIL does TrueType fonts but I never seem to be able to find the example code when I want it, and it's just so easy in GD. -- Chris. -------------- next part -------------- An HTML attachment was scrubbed... URL: From km at mrna.tn.nic.in Mon Jun 28 16:39:42 2004 From: km at mrna.tn.nic.in (km) Date: Tue, 29 Jun 2004 02:09:42 +0530 Subject: python desktop In-Reply-To: References: Message-ID: <20040628203942.GB25470@mrna.tn.nic.in> well i meant desktop environment created using python regards, KM ----------------------------------------------------------------- On Mon, Jun 28, 2004 at 10:49:33AM -0300, Batista, Facundo wrote: > [km] > > #- Are there any plans for a pure python desktop for linux ? > #- are there any similar projects ? > > What is a "pure python desktop"? > > . Facundo > > -- > http://mail.python.org/mailman/listinfo/python-list From tdwdotnet at gmail.com Tue Jun 29 12:30:13 2004 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 29 Jun 2004 17:30:13 +0100 Subject: sending of mail (smtp) - connection refused - but smtp server is running! In-Reply-To: <10e2v1446n95e4b@corp.supernews.com> References: <10e2v1446n95e4b@corp.supernews.com> Message-ID: <9afea2ac040629093063c3c1@mail.gmail.com> On Tue, 29 Jun 2004 15:26:41 +0100, Alex Hunsley wrote: > > I am using the smtp module to send emails via a local SMTP server on our network. > I am failing with "connection refused" error, even though we definitely have an > smtp server running on port 25! > > the code is like this: > > me = 'ahunsley at companyname.com' > you = 'someonelse at companyname.com' > msg['Subject'] = '*** alert' > msg['From'] = me > msg['To'] = you > > s = smtplib.SMTP('192.168.1.105') > s.connect() > s.sendmail(me, [you], msg.as_string()) > s.close() > > print "Email sent." > > When I run this code, I get: > > Traceback (most recent call last): > File "C:\Python23\check.py", line 58, in -toplevel- > s.connect() > File "C:\Python23\lib\smtplib.py", line 302, in connect > raise socket.error, msg > error: (10061, 'Connection refused') > Try this s = smtplib.SMTP('192.168.1.105') failed = s.sendmail(me, [you], msg.as_string()) s.quit() From kenneth.m.mcdonald at sbcglobal.net Tue Jun 15 18:21:45 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Tue, 15 Jun 2004 22:21:45 GMT Subject: Is it possible to have instance variables in subclasses of builtins? Message-ID: I've recently used subclasses of the builtin str class to good effect. However, I've been unable to do the following: 1) Call the constructor with a number of arguments other than the number of arguments taken by the 'str' constructor. 2) Create and use instance variables (eg. 'self.x=1') in the same way that I can in a 'normal' class. As an example of what I mean, here's a short little session: >>> class a(str): ... def __init__(self, a, b): ... str.__init__(a) ... self.b = b ... >>> x = a("h", "g") Traceback (most recent call last): File "", line 1, in ? TypeError: str() takes at most 1 argument (2 given) >>> (hmm, on reflection, I shouldn't have used 'a' as a parameter to __init__--but that's merely bad style, not the cause of the error :-) ) On the other hand, this example works: >>> class b(str): ... def __init__(self, x): ... str.__init__(x) ... >>> x = b("h") >>> x 'h' >>> Is it possible to circumvent the above restrictions? Thanks, Ken From theller at python.net Wed Jun 9 03:35:18 2004 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jun 2004 09:35:18 +0200 Subject: tp_getattrfunc, access members that are a list References: Message-ID: Torsten Mohr writes: >>> Can anybody describe me how i can access the array d[8] >>> as a list? I'd like to get AND set values in there. >> >> I don't think you can expose them as a list, but you should look into >> structmember.h, and it's PyMemberDef to expose the items separately. > > Hi, > > i've looked into structmember.h, but nothing (like e.g. a flag) > can mark that member as an array. > Also, i can't just export every single array member, as i need > to access them indexed, e.g. in a for() for clearing, for > setting calculated values, ... > > In the documentation i read that accessing arrays should be done > by getattr/setattr functions. This must be possible somehow... Ok, structmember.h was the wrong hint - it is used to expose heterogenous fields. For sequence like behaviour, you must implement PySequenceMethods: sq_length, sq_item, sq_add_item for example. Thomas From cgadgil_list at cxoindia.dnsalias.com Tue Jun 8 22:44:19 2004 From: cgadgil_list at cxoindia.dnsalias.com (Chetan Gadgil) Date: Wed, 9 Jun 2004 08:14:19 +0530 Subject: Perlish dictionary behavior In-Reply-To: <72976037.0406081653.71d4a634@posting.google.com> Message-ID: <002201c44dcb$aea36460$5b0aa8c0@cxodt03> >>> class AllThingsStartAtZero(dict): ... def __getitem__(self, key): ... return dict.get(self, key, 0) ... > -----Original Message----- > From: > python-list-bounces+cgadgil_list=cxoindia.dnsalias.com at python. > org > [mailto:python-list-bounces+cgadgil_list=cxoindia.dnsalias.com > @python.org] On Behalf Of Fred Allen > Sent: Wednesday, June 09, 2004 6:24 AM > To: python-list at python.org > Subject: Re: Perlish dictionary behavior > > > Mr. Brewer: > > I fruitlessly tried your "thing counter", as you can see below. > > >>> class AllThingsStartAtZero(dict): > ... def getitem (self, key): > ... return dict.get(self, key, 0) > ... > >>> thingCounts = AllThingsStartAtZero() for thing in > >>> ('a','b','c','d','a'): > ... thingCounts[thing] += 1 > ... > Traceback (most recent call last): > File "", line 2, in ? > KeyError: 'a' > >>> thingCounts > {} > > Reason tells me it should work for me using... > > PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 > bit (Intel)] on win32. > > ...as it did for you. The runtime interpreter, however, says > otherwise. Can you see what I've done wrong...I can't? > > With thanks in advance, I am, > > Respectfully yours, > > Fred Allen > -- > http://mail.python.org/mailman/listinfo/python-list > From heikowu at ceosg.de Mon Jun 28 19:22:50 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 29 Jun 2004 01:22:50 +0200 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? In-Reply-To: <78b6a744.0406261444.2704ba99@posting.google.com> References: <78b6a744.0406250737.310f31da@posting.google.com> <10dpicb9rjib2bb@news.supernews.com> <78b6a744.0406261444.2704ba99@posting.google.com> Message-ID: <200406290122.50670.heikowu@ceosg.de> Am Sonntag, 27. Juni 2004 00:44 schrieb george young: > Null Object seems like a perfect fit for this. I was unaware of it. > I read the original GOF book, but not much since then on patterns. > Thnks very much! What I actually think you want is to have a look at __nonzero__... This special member is called first time round, before trying to call __len__. Say you have the following class: class xyz: def __nonzero__(self): return True def __len__(self): return 0 then if xyz(): print "Yes!" will print yes, although len(xyz()) == 0. HTH! Heiko. From gpicon at gmail.com Thu Jun 17 16:22:12 2004 From: gpicon at gmail.com (Gustavo Picon) Date: Thu, 17 Jun 2004 15:22:12 -0500 Subject: Parsing by Line Data In-Reply-To: References: Message-ID: Quick and dirty solutions, with no error checking: # method 1: list of strings i = -1 r = [] for l in file(somefile): if l.startswith('01'): i+= 1 r.append(l[2:].rstrip()) else: r[i] = '%s%s' % (r[i], l[2:].rstrip()) print r # method 2: list of lists i = -1 r = [] for l in file(somefile): if l.startswith('01'): i+= 1 r.append([l[2:].rstrip()]) else: r[i].append(l[2:].rstrip()) print r Regards. On Thu, 17 Jun 2004 10:17:58 -0700, python1 wrote: > > Having slight trouble conceptualizing a way to write this script. The > problem is that I have a bunch of lines in a file, for example: > > 01A\n > 02B\n > 01A\n > 02B\n > 02C\n > 01A\n > 02B\n > . > . > . > > The lines beginning with '01' are the 'header' records, whereas the > lines beginning with '02' are detail. There can be several detail lines > to a header. > > I'm looking for a way to put the '01' and subsequent '02' line data into > one list, and breaking into another list when the next '01' record is found. > > How would you do this? I'm used to using 'readlines()' to pull the file > data line by line, but in this case, determining the break-point will > need to be done by reading the '01' from the line ahead. Would you need > to read the whole file into a string and use a regex to break where a > '\n01' is found? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gustavo Picon http://slashcore.com/tabo/ From nbrewer at visi.com Wed Jun 30 01:25:32 2004 From: nbrewer at visi.com (Chris Farley) Date: 30 Jun 2004 05:25:32 GMT Subject: Timeout on file write? References: <40dda426$0$32608$a1866201@newsreader.visi.com> <47r2r1-cs8.ln1@valpo.de> Message-ID: <40e24ecc$0$95558$a1866201@newsreader.visi.com> Mathias Waack wrote: > The simplest way would be to use a timeout as described in the python > lib docs, have a look at the signal module. Thank you, that's exactly what I needed! From dyoo at hkn.eecs.berkeley.edu Fri Jun 25 03:14:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 25 Jun 2004 07:14:07 +0000 (UTC) Subject: Compilers/Interpreters books? References: Message-ID: Ognen Duzlevski wrote: : Hrvoje Blazevic wrote: :> Hrvoje Blazevic wrote: :>> Are there any good books on Interpreter/Compiler construction, using :>> Python as a defining language out there? Something like Essentials of :>> Programming Languages 2e ? : I am not sure if there is a book on compiler construction that addresses the implementation in : Python though. I think it is more important for you to be familiar with the theory behind compilers and the : implementation should then be easier, regardless of the language. Others have already pointed out the basic literature. Agreed; a lot of the concepts of interpreters have little to do with the defining language. Essentials of Programming Languages makes this point clear, as the material can be easily translated to another language like ML. (And at times, it feels like EOPL was originally written with ML in mind... *grin*) You may want to look at Structure and Interpretation of Computer Programs: http://mitpress.mit.edu/sicp/ I had written a translation of the Scheme interpreter into Python a long long time ago; I think it still runs, though. *grin* Here's a link: http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/ From p_s_oberoi at hotmail.com Tue Jun 8 09:33:54 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 08 Jun 2004 08:33:54 -0500 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> Message-ID: > Jacek already made this point, but I'll make it again. Assembler > is sometimes *not* the way to write the fastest code. (Though > sometimes it is.) Optimizing compilers for some languages such as > C can actually produce *faster* code by choosing combinations of > opcodes and side-effects that even an assembly programmer would be > nuts to use in most cases, largely because it would make the code > even more obscure than it already is but also because they might not > even think of it. Very true, and I would replace the "sometimes not the way to write the fastest code" with "almost never...". Especially when optimizing code for a modern processor, a compiler will be much better at reordering instructions so that they pass through the execution pipeline more smoothly. If you are writing a critical 20-instruction inner loop and are willing to spend hours, if not days, experimenting with different instruction sequences, you may be able to get slightly better performance than the code generated by the compiler; but in most other cases it's best to leave it to the compiler. -param From grey at despair.dmiyu.org Thu Jun 3 10:47:27 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 14:47:27 GMT Subject: python vs awk for simple sysamin tasks References: Message-ID: On 2004-06-03, Roy Smith wrote: > Neither of these are really tasks well suited to python at all. Individually, no. Combined, yes. > I'm sure you could replicate this functionality in python using things > like os.walk() and os.stat(), but why bother? The result would be no > better than the quick on-liners you've got above. Not true. The above one liners are two passes over the same data. With an appropriate script you could make one pass and get both results. Sure you could do that in shell but I'm of the opinion that anything other than one liners should never be done in shell. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From jacek.generowicz at cern.ch Fri Jun 4 09:49:12 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 04 Jun 2004 15:49:12 +0200 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: > Critcl I'm not having much luck with google on this one. From guy at NOSPAM.r-e-d.co.nz Tue Jun 29 08:24:17 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Wed, 30 Jun 2004 00:24:17 +1200 Subject: unicode and shelve Message-ID: Hello, When I try and create a unicode key with a shelve I get the following error: "TypeError: String or Integer object expected for key, unicode found" Is there anyway I can use unicode keys with shelve's? TIA, Guy From grante at visi.com Thu Jun 3 11:58:12 2004 From: grante at visi.com (Grant Edwards) Date: 03 Jun 2004 15:58:12 GMT Subject: speed problems References: Message-ID: On 2004-06-03, Roel Schroeven wrote: > Axel Scheepers wrote: > >> Another difference might be while( ) and line in lf.readlines(). >> The latter reads the whole file to memory if I'm not mistaken as the former >> will read the file line by line. Why that could make such a difference I >> don't know. > > line in lf also reads the file line by line, if you're using 2.3. In 2.1 > or 2.2 you can use xreadlines for that. I don't if it makes any > difference in performance though, for small files. I would suspect that reading the entire file at once would yeild slightly better performance for non-huge files. -- Grant Edwards grante Yow! My ELBOW is a remote at FRENCH OUTPOST!! visi.com From ramen at lackingtalent.com Tue Jun 8 14:18:31 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 08 Jun 2004 18:18:31 -0000 Subject: Callbacks to generators References: Message-ID: In article , Robert Brewer wrote: > Dave Benjamin wrote: >> Is there a straightforward way to create a generator from a >> function that takes a callback? [..snip..] > > You're not the first to tackle this problem: > > http://mail.python.org/pipermail/python-list/2003-December/197828.html > > ...but no solution forthcoming. Oh well, thanks for the useful link. That thread was illuminating. I ended up switching to an iterator object, implementing "__iter__" and "next" in a class that wraps around the process. This required a bit of reworking since the algorithm changed from a push model (which I would consider callbacks and generators to be) to a pull model. Thanks, everyone, for the helpful responses. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : i'm half drunk on babble you transmit - soul coughing / true dreams : From jepler at unpythonic.net Thu Jun 3 11:30:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 3 Jun 2004 10:30:40 -0500 Subject: Optimizing multiple dispatch In-Reply-To: References: Message-ID: <20040603153040.GJ19278@unpythonic.net> Pyrex is just a translator, there's no dependency on a Pyrex library or include file when you actually want to compile the generated .c On Thu, Jun 03, 2004 at 04:55:19PM +0200, Jacek Generowicz wrote: > Jeff Epler writes: > > > Avoding map() may help: > > tuple([type(a) for a in args]) > > Nonononononooooo! :-) [...] > > ... hmm, map is faster than listcomp. my mistake! > > :-) > > I've asked for optimization advice a few times here, and usually the > responses include "replace map with a list comprehension" ... and yet > the map is always faster. I wonder where people get this idea that map > is slow ... until this started happening I had always assumed that > "everyone" knows that the map/reduce/filter family are the fastest > Python looping constructs. No message about optimization should be without one downright wrong suggestion. The common wisdom about listcomp speed may apply when the body doesn't include a function call, but the map version would include a lambda: $ timeit 'map(lambda x:x+1, range(100))' 1000 loops, best of 3: 230 usec per loop $ timeit '[x+1 for x in range(100)]' 10000 loops, best of 3: 156 usec per loop Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve.menard at videotron.ca Thu Jun 10 13:16:04 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Thu, 10 Jun 2004 13:16:04 -0400 Subject: Distutil question Message-ID: I built a extension module that I'd like to distribute via distutil. It consists of a bunch of cpp and hpp files. my setup.py files looks like this : from distutils.core import setup, Extension import os, os.path cpp = [] hpp = [] for i in os.listdir("src/native"): if i[-4:] == '.cpp' : cpp.append( "src/native/"+i) elif i[-4:] == '.hpp' : hpp.append( "src/native/"+i) e = Extension("_jpype", cpp, include_dirs=[os.getenv("JAVA_HOME")+"/include", os.getenv("JAVA_HOME")+"/include/win32"] ) setup( name="JPype", version="0.2.1p1", description="Python-Java bridge", author="Steve Menard", author_email="devilwolf at users.sourceforge.net", url="http://jpype.sourceforge.net/", packages=["jpype"], package_dir={"jpype": "src/python/jpype"}, ext_modules=[e] ) now, if I add the hpp list to the extension sources, I get an error that it does not know what to do with the hpp files. How do I go about distributing those files so that a source dsitribution will compile properly? should I rename them to .h files instead? Thanks for your help, Steve From fumanchu at amor.org Tue Jun 8 12:46:49 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 8 Jun 2004 09:46:49 -0700 Subject: Testing whether imported function failed Message-ID: brianc at temple.edu wrote: > I have to make a lot of calls to a C++ library binded to python. > The problem is that the functions/methods don't raise > exceptions when they fail to do their job. Instead they return > a 0 for a failure and a 1 for a successful completion. > >>> do_something(object) > 1 > >>> do_something(object) > 0 > > I spent two days tracking down a bug that could have easily > been found if the call loudly failed. Is there anyway to > blanket test this integer 1/0 output so I can catch these > errors before they become untraceable? If *all* the functions have that behavior, you can wrap the C module with another module easily. For example, given a simple module clib.py: def do_something(obj): if obj: return 1 else: return 0 ...you can wrap it with another module (clibwrap.py) like this: import clib class LoudException(Exception): pass def wrap(func): def wrapper(*args, **kwargs): success = func(*args, **kwargs) if not success: raise LoudException return wrapper for name in dir(clib): func = getattr(clib, name) globals()[name] = wrap(func) del func ...then in client code, write: >>> import clibwrap >>> clibwrap.do_something(1) >>> clibwrap.do_something(0) Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\Lib\site-packages\clibwrap.py", line 9, in wrapper raise LoudException LoudException If not every function in the original module has the 1/0 behavior, you can do it selectively rather than generically in clibwrap.py. Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From skchim0 at engr.uky.edu Tue Jun 22 18:29:37 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Tue, 22 Jun 2004 18:29:37 -0400 Subject: FFT with Python Message-ID: <017601c458a8$66cbf890$559ea380@D4XN6B41> Hi All, Did anyone compute FFT - Fast Fourier Trans using Python ? I am looking for a simple Python package which can do spectral analysis for me. Can someone help me get such a package ? Thanks Regards, Satish Chimakurthi -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at evpopov.com Fri Jun 25 03:47:42 2004 From: google at evpopov.com (popov) Date: 25 Jun 2004 00:47:42 -0700 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> Message-ID: <7eecf173.0406242347.74c7b7e9@posting.google.com> Have you tried yapsnmp: http://yapsnmp.sourceforge.net/ ? It is a Python wrapper around net-snmp, so should be fast. It also claims to be thread-safe. The problem you could have is that it's advertised as a posix module only. But the wrapper is built using SWIG, so it should be possible to build it for Windows without too much hassle. Note that I've never used it myself, so can't comment on the package itself. However, I will have to do some snmp coding soon, and it's the first one I will try. From miki.tebeka at zoran.com Tue Jun 15 02:20:09 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 15 Jun 2004 08:20:09 +0200 Subject: newbie question-multidimensional arrays In-Reply-To: References: Message-ID: <20040615062008.GB1996@zoran.com> Hello Doug, > How do you define and access multidimensional arrays in Python? I am new > to python and come from a C and FORTRAN background and I am not sure how to > define an array without giving the contents of the array. Any help will be > appreciated. I would like to be able to read and manipulate > multidimensional arrays using a nested loop. I cannot find anything in the > documentation to help me. Python lists are arrays that can hold anything including other lists. This makes them a multidimensional arrays as well. For example: def gen_2darray(m, n, initial=0): '''Generate two dimensional array We can't use [[] * n] * m since the internal arrays will point to the same array. ''' arr = [None] * m for i in range(m): arr[i] = [initial] * n return arr a = gen_2darray(10, 10) a[4][5] If you need fast computation with arrays have a look at numpy project. HTH. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From rupole at hotmail.com Tue Jun 22 01:08:50 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 22 Jun 2004 01:08:50 -0400 Subject: Windows XP - cron or scheduler for Python? References: Message-ID: <40d7bb06_5@127.0.0.1> You can retrieve the startup error code using the Pywin32 package. (requires build 201) import pythoncom, win32api from win32com.taskscheduler import taskscheduler ts=pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None, pythoncom.CLSCTX_INPROC_SERVER,taskscheduler.IID_ITaskScheduler) task=ts.Activate('your task name') exit_code,startup_error_code=task.GetExitCode() print win32api.FormatMessage(startup_error_code) hth Roger "Jay Donnell" wrote in message news:a6fdfd6b.0406211455.6bd70abf at posting.google.com... > > 2) Always call Python and have it run the application. > > Don't just try to run progname.py. > > How would one do this. I'm a unix geek having the same problems as the > op, but I'm on windows 2000. The status simply says "couldn't start". > Any other ideas would be appreciated as well. From nc-jantzegu at netcologne.de Sun Jun 6 20:07:57 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Mon, 7 Jun 2004 02:07:57 +0200 Subject: C compiler written in Python References: Message-ID: From: "Thomas Guettler" writes > > Cool. Next goal could be to > compile python with it. > > Thomas > > And the goal after could be to get rid of C :-) Yes I really think about this: Let us start from the bottom Let us start with Assembler. Maybe High Level Assembler with clever macros. Add higher datatypes if possible (I wish list and dict). Build an environment that allows you to generate and execute assembler at runtime This could be the basic building block for clever JIT virtual machines (something like parrot - but small, lightweight please - if possible) Higher level languages on top of this machine will go the Psyco/JIT way- taking the best of Compiler and Interpreter technology. This means: not all can be compiled at compile-time, so compile again at hot-spots in the beginning of loops when type-information is available, save the compiled stuff and use it as long the loop repeats ... regards G?nter From dkturner at telkomsa.net Mon Jun 14 11:00:07 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 08:00:07 -0700 Subject: does python have useless destructors? References: <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: Marcin 'Qrczak' Kowalczyk wrote in message news:... > On Mon, 14 Jun 2004 00:00:39 -0700, David Turner wrote: > > > The D programming language somehow contrives to have both garbage > > collection and working destructors. So why can't Python? > > What happens in D when you make a pointer to a local variable, > the variable goes out of scope, and you use the pointer? > > Undefined behavior? If so, it's unacceptable for Python. Are you suggesting that my proposed modification to the destructor semantics will result in such misbehaviour? If so, please tell me why you believe that to be the case. We're not talking about pointers here, we're talking about reference-counted objects. Regards David Turner From simoninusa2001 at yahoo.co.uk Thu Jun 24 15:01:21 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 24 Jun 2004 12:01:21 -0700 Subject: wxPython widgets References: Message-ID: <30260531.0406241101.5254ccef@posting.google.com> Christopher T King wrote: > > if wxPython comes with more widgets that wxWidgets itself? I assume they > > are just additional widgets provided with wxPython, built using wxWidgets? > Probably. Tkinter does the same thing (the tkSimpleDialog "widget" is pure > Python). Yeah, wxPython does have it's own widgets, which I assume are written in C++ for wxWidgets with a Python wrapper, and are not specifically coded in Python (so could be used for C++ apps too?) I personally like the wx.lib.dialogs.ScrolledMessageDialog - makes a very nice about/changelog dialog, although I think that comes from PythonCard? From r.gable at mchsi.com Sat Jun 19 22:54:39 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 19 Jun 2004 19:54:39 -0700 Subject: Another MSIE Python Question References: <22b7fd40.0406190617.a33514@posting.google.com> Message-ID: <22b7fd40.0406191854.2390d1a2@posting.google.com> Here's the stack dump: Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\lib\ufutil.py", line 661, in updatetocurrent getplayerdata(l,i) File "C:\Python22\lib\ufutil.py", line 478, in getplayerdata ie=Dispatch('InternetExplorer.Application.1') File "C:\Python22\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", line 84, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221231, 'ClassFactory cannot supply requested class', None, None) Peter Hansen wrote in message news:... > Ralph A. Gable wrote: > > > I am opening MSIE6 with this code: > > > > ie=Dispatch('InternetExplorer.Application.1') > > ie.Navigate(url) > > while ie.Busy: > > time.sleep(0.1) > > ied=ie.Document > > while ied.ReadyState != 'complete': > > time.sleep(0.1) > > > > ieh=ied.documentElement.outerHTML > > > > > > When opening Word or Excel, and using Dispatch('Word.Application') or > > Dispatch('Excel.Application'), the app comes up and is available and can be > > brought up on the screen by setting .Visible = 1. When using the above code, > > IE will not come up. I have to open IE by clicking on its icon and then the > > above code will work. If I don't do that I get a stack dump and my python > > program crashes. > > > > Any help would be appreciated. > > Based on the above description, is it possible that the fact > that you aren't doing "ie.Visible = 1" is responsible? > > Also, please include the traceback when saying that your Python program > crashes... this usually eliminates whole classes of possible causes, > and often points directly to the trouble for someone who's been there > before. > > -Peter From gabor at z10n.net Sat Jun 26 14:51:18 2004 From: gabor at z10n.net (gabor farkas) Date: Sat, 26 Jun 2004 20:51:18 +0200 Subject: i have a big dictionary...:) Message-ID: <1088275878.20902.7.camel@dubb> hi, i have a big dictionary... well... i have a 6mb textfile, from which i build a dictionary the following way: the first word of a line is the key, the rest is the value. and i fill all the lines into the dictionary (it contains around 100*1000 lines) now when it's in memory, it uses around 60megabytes of memory (measured from "ps aux | grep python" :) how could i lower this memory requirement? is there a simple database-format, something small.... so i don't have to keep the whole dictionary in memory? thanks, gabor From tkpmep at hotmail.com Mon Jun 21 14:00:14 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 21 Jun 2004 11:00:14 -0700 Subject: Catching errors in attribute names at assigment Message-ID: If one makes a typographical error when assigning a value to an attribute (i.e if one types ClassName.xyc = 10 instead of ClassName.xyz=10), a new attribute xyc will be created, and the error can later prove difficult to debug. Is there a way to check assignments when they are made and to allow only those that modify a restricted set of allowable attributes? Looking through ClassName.__dict__.keys() is perhaps one way to achieve this: Is there a simpler (i.e. more Pythonic) way to do it as well? Thomas Philips From http Thu Jun 24 01:12:34 2004 From: http (Paul Rubin) Date: 23 Jun 2004 22:12:34 -0700 Subject: Obtaining Webpage Source with Python References: <6962d028.0406232103.6f5d9f7f@posting.google.com> <7xy8mdee07.fsf@ruckus.brouhaha.com> Message-ID: <7xu0x1edz1.fsf@ruckus.brouhaha.com> Paul Rubin writes: > import urllib > pyPage = urllib.urlopen('http://www.python.org/index.html',r).read() oops: import urllib pyPage = urllib.urlopen('http://www.python.org/index.html').read() i.e. omit the 'r' argument to urlib.urlopen. From flamewise at yahoo.com Tue Jun 29 09:11:55 2004 From: flamewise at yahoo.com (Peter Knoerrich) Date: 29 Jun 2004 06:11:55 -0700 Subject: Any list larger than any number by way of dimensions? References: Message-ID: Ah, Harald and Peter - thanks then. I'll just have to watch my step. Peter From peter at engcorp.com Thu Jun 10 21:51:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 21:51:40 -0400 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: Aahz wrote: > In article <-oadnfu_sdwTUFrdRVn-hw at powergate.ca>, > Peter Hansen wrote: > >>Michael P. Soulier wrote: >> >>>myfile = open("myfilepath", "w") >>>myfile.write(reallybigbuffer) >>>myfile.close() >> >>... immediately raises a warning flag in the mind of an >>experienced Python programmer. > > Depends on the circumstance, I'd think. If you mean that for simple scripts, it looks fine, then I agree. Otherwise, maybe I wouldn't. ;-) From chrisks at NOSPAMudel.edu Thu Jun 24 02:33:16 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Thu, 24 Jun 2004 02:33:16 -0400 Subject: Classic and New Style Classes? Message-ID: I'm generating the source of an object from a list of objects. Therefore I need to determine if the object is a class definition (i.e. 'def something(whatever):') or a class instance (i.e. 'somename = somethingelse()'). With classic classes this is trivial, since all I have to do is check the type. However, for the new "improved" style classes this seems next to impossible, since everything is essentially an instance of something. isinstance(class, classinfo) won't work since I won't necessarily know classinfo. Is there any way to make this distinction? Any help is appreciated. From ed_hartley at mac.com Tue Jun 1 09:16:49 2004 From: ed_hartley at mac.com (Edward Hartley) Date: Tue, 1 Jun 2004 14:16:49 +0100 Subject: Python for AI: OWL and CLIPS anyone? Message-ID: Hi there used to be a CLIPS wrapper working but it is for the older bindings circa Pyhon 1.5-1.9 IIRC googling the python site will pull up references like mail.python.org/pipermail/python-announce-list/ 2001-November/001066.html mail.python.org/pipermail/python-announce-list/ 2002-February/001265.html although the forward references are now broken. I did track down the original version again though on starship http://starship.python.net/crew/gandalf/DNET/AI/ The revised version 2 seems to have dropped out of view completely now. I can confirm that the original interface version did expose CLIPS to python successfully though I'm not convinced that passing objects between environments is an effective approach. There is something else you should probably look at as well http://starship.python.net/crew/mike/TixClips/ which uses the SWIG CLIPS wrapping so Python -> SWIG -> CLIPS is feasible essentially the approach adopted in the earlier effort. Hope this is of some use Regards Ed Hartley ------------------------------------------------------------------------ --------------------------- ------------------------------------------------------------------------ --------------------------- Ed Hartley Tel 01524 593675 Researcher Fax 01524 593608 Computing Department Lancaster University LA1 4YW From peter at semantico.com Thu Jun 24 06:24:01 2004 From: peter at semantico.com (Peter Hickman) Date: Thu, 24 Jun 2004 11:24:01 +0100 Subject: Python Color Printing In-Reply-To: <889cbba0.0406240136.3a735356@posting.google.com> References: <889cbba0.0406240136.3a735356@posting.google.com> Message-ID: <40daabc1$0$10280$afc38c87@news.easynet.co.uk> Kamilche wrote: > I'm pretty desperate to get color syntax printing. I just tried out > the evaluation version of 'Komodo', which several people in here > suggested, and its print features are terrible. The text is coming out > huge when I print at 8 point, tiny when I'm printing at 14 point (so > tiny that it looks like subscripts), the margins are reset at random, > and so on. Plus it doesn't recognize all my fonts. > > I don't care if the pretty printer is in an IDE. I just want color > printing with headers and footers! And I wanted it automated - I don't > want to have to print each one by hand, I want to start them all > printing and walk away. It has to be able to print in larger fonts > reliably, because 10 point is too small for my computer-weary eyes. > > Does anyone have any suggestions? > > --Kamilche There is a GNU tool called source-highlight that handles python. It will create a html file with the colour coding. You could then print the html file. You'll have to google for it. From news01 at metrak.KILLSPAM.com Tue Jun 29 04:27:44 2004 From: news01 at metrak.KILLSPAM.com (sosman) Date: Tue, 29 Jun 2004 18:27:44 +1000 Subject: unpickle error In-Reply-To: References: <40e00fdb$0$18195$afc38c87@news.optusnet.com.au> Message-ID: <40e12824$0$18671$afc38c87@news.optusnet.com.au> Richie Hindle wrote: > [sosman] > >>After pickling several lists of objects using protocol 2, when I >>unpickle I get: >>TypeError: ord() expected a character, but string of length 0 found >> >>When I use protocol 0 (ascii) this doesn't occur. > > > On Windows you need to open your files in binary mode using open(name, 'rb') > or open(name, 'wb') when reading and writing non-ASCII data. Could that be > the problem? Doh. Thank you, that appears to have done the trick. -- brewiki: http://www.metrak.com/wiki/homebrew/ From greg at cosc.canterbury.ac.nz Tue Jun 1 23:15:36 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 02 Jun 2004 15:15:36 +1200 Subject: OT: Cryptography puzzle In-Reply-To: References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: <2i4v2qFj4rvhU1@uni-berlin.de> Christian Gudrian wrote: > And what about the 'ss' in 'ssfd'? I don't know many languages that allow > words to start with two identical letters. Obviously it's "my hovercraft is full of eels" with several spelling mistakes. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From fumanchu at amor.org Sun Jun 6 15:54:22 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 6 Jun 2004 12:54:22 -0700 Subject: Curried functions Message-ID: Holger T?rk wrote: > a common pattern to write curried functions (i.e. without the > need for a special partial application syntax, like in PEP 309) > is like in this example: > > def functionLock (lk): > def transform (fn): > def lockedApply (*argl, **argd): > lk.acquire () > try: > fn (*argl, **argd) > finally: > lk.release () > return lockedApply > return transform > > PEP 318 (decorators) contains some other examples. > I wonder if someone else than me would appreciate a syntax > like this: > > def functionLock (lk) (fn) (*argl, **argd): > lk.acquire () > try: > fn (*argl, **argd) > finally: > lk.release () > > It would even enable us to write curried function definitions > like this one: > > def f (*a) (x=1, **b) (*c, **d): > [...] > > Current approaches about currying or partial application > can't handle the latter in a simple/transparent way. > > Will it be hard to implement the feature? > Are there any reasons that this syntax/concept is a bad idea? I realize you're demonstrating by example, but I can't see why the first block wouldn't be written: def functionLock (lk, fn): def lockedApply (*argl, **argd): lk.acquire () try: fn (*argl, **argd) finally: lk.release () return lockedApply ...that is, I can't recall a case where I've doubly-nested a function like your example. Anyway, a def like: def f (*a) (x=1, **b) (*c, **d): [...] seems...limiting, I guess. The developer of 'f' doesn't always know exactly which arguments consumers are going to want to partially apply, in which order or groupings. A more generic approach would alleviate (if not completely remove) the need to nest. I'd rather see a consumer-side solution to partial application, where your example function is defined straightforwardly: def functionLock(lk, fn, *argl, **argd): lk.acquire() try: fn(*argl, **argd) finally: lk.release() and the consumer decides when to supply arguments. They could decide to write: f_lock = partial(functionLock, lk) for func in func_set: f_lock(func, 1, 2, 3) or their purposes might be better served by applying two args "up front": locked_f = partial(functionLock, lk, fn) for i in range(10): locked_f(i, i + 1) It depends on the context. Robert Brewer MIS Amor Ministries fumanchu at amor.org From dave at pythonapocrypha.com Fri Jun 25 17:15:56 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 25 Jun 2004 15:15:56 -0600 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: <06ac01c45af9$9ad9ad50$6400fea9@boba> Mark wrote: > > Ahh...so the method name is just _spelled_ with an exclamation point? > > Yes, a Prothon identifier is the same as a Python identifier except that it > can end with an exclamation mark ( ! )or a question mark ( ? ). These marks > can only appear at the end and there can only be one. It is up to the > programmer to make sure he/she uses them properly. > > Exclamation marks are to be used in identifiers if and only if it is a > method that modifies the target in-place. > > Question marks are to be used on methods if and only if they return True or > False and nothing else. > > > IOW, the ! is a token you can use at the end of an identifier, but it > > is not actually used by the language itself - > > No, the marks are significant to the language just as any other part of the > identifier is. You cut out my example that elaborated on the questions I was asking: 1) It's just part of the name. So from the language's perspective, whether you call it appendINPLACE or append! makes no difference? 2) (continuing on #1) that being the case, it's really just a naming convention, correct? (because the language itself doesn't do anything with that information - additional checking to enforce that convention, different functionality, etc) >From what I gather that's a "yes" to both questions. > > Seems like a waste to reserve a > > symbol for something so rarely needed. > > I disagree. In-place modification is significant and happens often. > Ignoring this is dangerous. Well, now we're down to disagreeing how often it occurs. I just haven't seen very many cases in practice where (1) I want to both do something to an object AND have it return itself in a single step and (2) doing so can be done in a clear way, and (3) I want to do it for a good reason rather than just wanting to save a line of code. In the few cases I've seen so far, the rationale has apparently been to make the code shorter, not necessarily better. > >> Guido avoided returning values from in-place modification functions > >> because of the confusion as to whether in-place mods were happening > >> or not. We have solved that confusion with the exclamation mark. > >> Our code is very readable because of this. > > > > Clearly, readability is in the eye of the beholder. :) > > How can you argue that the exclamation mark indicating in-place-modification > does not make it more readable? (1) Because in practice I haven't seen the need for it much, so in my mind it wouldn't be used that much (making it less familiar & therefore more work to understand the code) and/or it encourages cramming more onto a line just because you can. The "print list.append!(5)" is a fine example of this IMO - you've combined two *completely unrelated* operations for no good reason. Yes, it's just an example, I know, but it's probably an example of how it'll be commonly (mis)used. For every one "good" use of the ! form you'll probably have a thousand uses where the only benefit was that it saved a line of code. <0.5 wink> (2) It's just a naming convention, so you can't rely on it's presence or absence as being accurate (probably not a big deal in practice, but still...) (3) Cases like w = x.y.z!() would confuse me, as would ref! = obj.method! ... x = ref!(5, 6, 7) # what the heck, x == obj?! -Dave From km at mrna.tn.nic.in Sun Jun 13 07:11:22 2004 From: km at mrna.tn.nic.in (km) Date: Sun, 13 Jun 2004 16:41:22 +0530 Subject: dict of arrays Message-ID: <20040613111122.GA19788@mrna.tn.nic.in> Hi all can one create a dict holding arrays as values to the dict keys in python ?. i think Perl seems to have this facility . i didnt find any resources/ suggestions on this until now. regards, KM From deanl at redstone.co.uk Tue Jun 1 04:51:23 2004 From: deanl at redstone.co.uk (dean) Date: 1 Jun 2004 01:51:23 -0700 Subject: Converting Hex to decimal Message-ID: Hello group: I have a file containing hex data. I would like to convert the contents of the file to decimal by reading each by sequentially (one byte at the time). Is there a module that has such functionality or does someone have the relevant code? Also, is there an oracle module available for windows xp and hp-ux? Much appreciated dean please reply to diabolik(nospam)@uku.co.uk remove (nospam) From gulliver at atr.co.jp Fri Jun 25 00:28:08 2004 From: gulliver at atr.co.jp (Roberto Lopez-Gulliver) Date: 24 Jun 2004 21:28:08 -0700 Subject: Pil and freeze References: Message-ID: <26b7aa41.0406242028.5beee9bc@posting.google.com> try this : http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&safe=off&threadm=283adf56.0306050511.3313c89a%40posting.google.com&prev=/groups%3Fhl%3Den%26safe%3Doff%26group%3Dcomp.lang.python or search on this group for the thread : "PIL and py2exe Issues" hope this helps -r "Federico" wrote in message news:... > I used freeze.py with a script that import Pil, the script works well bat > the executable I have send this error: > > im=PIL.Image.open(qs['im'][0]) > File "D:\PYTHON~1.4\lib\site-packages\PIL\Image.py", line 1571, in open > raise IOError("cannot identify image file") > IOError: cannot identify image file > > How can I solve it? > Thanks From elbertlev at hotmail.com Fri Jun 25 13:21:21 2004 From: elbertlev at hotmail.com (Elbert Lev) Date: 25 Jun 2004 10:21:21 -0700 Subject: Case insensitive dictionary? Message-ID: <9418be08.0406250921.71f4eba4@posting.google.com> Hi! Here is the problem: I have a dictionary. Keys are strings. How to make dictionary lookup case insensitive? In other words: If dict = {'First":"Bob", "Last":"Tom"}, dict["first"] should return "Bob" Maybe dictionary is not the right data type? If so what is? From peter at engcorp.com Wed Jun 30 08:28:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 30 Jun 2004 08:28:25 -0400 Subject: Stderr and Pythonw In-Reply-To: References: <2cf4e0dmog1klag13bn6ie3m0stg2b8bgq@4ax.com> Message-ID: Manlio Perillo wrote: > On Wed, 30 Jun 2004 04:22:16 GMT, Dennis Lee Bieber > wrote: >>On 29 Jun 2004 12:25:58 -0700, vm_usenet at yahoo.com (vm_usenet) declaimed >>the following in comp.lang.python: >>>When running python code via pythonw, what exactly happens to stderr? >> >> Since there is no console expected, none of the std*** >>connections are created. > > This not really corrected. > Actually 'some' std*** connections are created but are usefulness > (and moreover they have a bug). > > If you write more than 4096 an exception is raised... And, for future reference, here is the bug report Manlio filed on SourceForge (for which there is no response yet): http://sourceforge.net/tracker/index.php?func=detail&aid=973507&group_id=5470&atid=105470 I've also confirmed this, using a test script very similar to one Tim Peters posted a couple of months ago in http://groups.google.ca/groups?selm=mailman.980.1082749579.20120.python-list%40python.org The problem is confirmed to still exist with Python 2.3.4. -Peter From roeland.rengelink at chello.nl Tue Jun 22 19:13:43 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Tue, 22 Jun 2004 23:13:43 GMT Subject: meta confusion new.instance() argument 1 must be classobj, not type In-Reply-To: References: Message-ID: <40D8BDB3.6040805@chello.nl> Brad Clements wrote: > I need to dynamically create a new type of class at runtime, based on an > oldstyle class and a new style class. > > I'm using Python 2.3.2 > > My code: > > def shipment_from_db_instance(db_shipment): > """ > Create a new shipment object from a db_shipment instance (old style) > """ > global _new_shipment_factory > if not _new_shipment_factory: > # create a new shipment factory dynamically > _new_shipment_factory = type('NewShipment', (Shipment, > db_shipment.__class__), {}) > print "factory is ", _new_shipment_factory, > type(_new_shipment_factory) > return new.instance(_new_shipment_factory, db_shipment.__dict__) > > But I get this output: > factory is > > File "/home/bkc/src/Python/MurkWorks/Shipments/Shipment.py", line 81, in > shipment_from_db_instance > return new.instance(_new_shipment_factory, db_shipment.__dict__) > TypeError: instance() argument 1 must be classobj, not type > > It seems that new.instance() doesn't understand how to make instances from > types. > > I don't know if it's a bug, but I think this alternative will work. i = object.__new__(_new_shipment_factory) i.__dict__.update(db_shipment.__dict__) return i Hope this help, -- Roeland Rengelink Author of PyORQ (http://pyorq.sourceforge.net), an Object-Relational binding that lets you write queries as Python expression 'half of what I say is nonsense, unfortunately I don't know which half' From beliavsky at aol.com Thu Jun 3 18:08:57 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 3 Jun 2004 15:08:57 -0700 Subject: simplify printing of a list Message-ID: <3064b51d.0406031408.1b676379@posting.google.com> To print a list with a specified format one can write (for example) for j in [0,1,2]: print "%6d"%j, print The code print "%6d"%[0,1,2] currently produces a syntax error, but it would be convenient if it had the same meaning as the loop above. One can write a function to print a list, for example def print_list(x,fmt_x="%6d"): """ print a list on one line """ for y in x: print fmt_x % y, print_list([0,1,2]) but it gets messy to print several lists on the same line. In Fortran 90/95 one can write print "(100i6)",(/0,1,2/) where the format (100i6) means that UP TO 100 integers are printed using 6 columns. An alternative suggestion I have for Python is to allow print "100%6d"%[0,1,2] with the same meaning. I realize that what I am asking for is just a convenience, but it is one that I could use in almost every program I write. From bro092 at yahoo.com Tue Jun 29 22:38:06 2004 From: bro092 at yahoo.com (dan roberts) Date: 29 Jun 2004 19:38:06 -0700 Subject: script to download Yahoo Finance data Message-ID: <94abfadd.0406291838.53600d7b@posting.google.com> Folks, This is my first Python project so please bear with me. I need to download data from Yahoo Finance in CSV format. The symbols are provided in a text file, and the project details are included below. Does anyone have some sample code that I could adapt? Many thanks in advance, dan /*---NEED TO DO------*/ Considering IBM as an example, the steps are as follows. A. Part 1 - download 'Historical Prices' from http://finance.yahoo.com/q?s=ibm 1. Get the Start Date from the form at the top of this page, http://finance.yahoo.com/q/hp?s=IBM (I can provide the end date.) 2. Click on Get Prices 3. Then finally click on Download to Spreadsheet and save the file with a name like IBM_StartDate_EndDate.csv. (2) and (3) are equivalent to using this link directly, http://ichart.yahoo.com/table.csv?s=IBM&a=00&b=2&c=1962&d=05&e=30&f=2004&g=d&ignore=.csv Can you please post an example of a loop that would do the above for a series of company symbols, saved in a text file? B. Part 2 - download 'Options' from http://finance.yahoo.com/q?s=ibm This seems more difficult because the data is in html format (there's no option to download CSV files). What's the easiest/best way to take care of this? From tim.one at comcast.net Sat Jun 12 16:12:06 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 12 Jun 2004 16:12:06 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <40caf01b$0$41764$5fc3050@dreader2.news.tiscali.nl> Message-ID: [Gr?goire Dooms] > If speed is the matter, go for C: > > with the GNU MP library use > void mpz_pow_ui (mpz_t rop, mpz_t base, unsigned long int exp) and > char * mpz_get_str (char *str, int base, mpz_t op) There are some GMP wrappers for Python. Using Marc-Andre Lemburg's mxNumber wrapper (which is maximally convenient for me on Windows, since it includes a precompiled-for-Windows GMP), the OP's task is spelled like so: >>> from mx.Number import * >>> Integer(2)**24036583 - 1 That does call mpz_pow_ui() and mpz_get_str() (with base=10) under the covers. Since I typed that in, the process has accumulated 59 CPU minutes, with no output yet. Curiously, >>> x = Integer(2)**24036583 - 1 consumes 112 CPU seconds on its own, while the straight Python >>> x = 2**24036583 - 1 consumes only 2 CPU seconds -- so Python is 50+ times faster than this GMP for the computational part. Python's Karatsuba multiplication gets enormous benefit out of special-casing zeroes in this particular case (all the squarings when computing the power see an input whose least-significant half is entirely zero bits, so huge mounds of needless work get skipped). The fastest pure-Python solution I've found consumed about 20 CPU minutes to do the whole job, so is at least 3X as fast as the GMP here (which is still running as I type this, over an hour of CPU time and climbing). For that, I wrote my own multiplication and exponentiation routines in Python, using digits in base 10**5000. Computing in a form of decimal from the start makes "conversion to decimal" a speedy operation. > I did a small contest about the decimal repr of 2**1000000 a a couple > years ago. A few languages were compared on a time-to-result basis. > Python won with 7 minutes (10 sec devel, 6:50 comput.) and C + GMP was > second: 15 min devel(including reading the doc) + a few sec of comput. I > bet you can expect a 30-100 fold speedup using C + GMP compared to python > -c 'print 2**24036583 - 1' On the box I'm using here, the straight Python 2.3.4: >>> 2**1000000 consumed 80 CPU seconds (which includes decimal display), and the mxNumber version: >>> from mx.Number import * >>> Integer(2)**1000000 consumed 60 CPU seconds. I expect Python 2.3.4 is faster at this stuff than the version you used (in particular, recent Pythons use base 10000 internally when converting to decimal, instead of base 10; it's still quadratic-time, but the constant factor was slashed). The box is a 3.2GHz P4, which is probably also faster than the box you used. It could also be that the version of GMP shipped with mxNumber isn't optimally compiled for this box, and/or getting old. Lessons to take home : + The speed of bigint operations can be data-dependent in implementation- specific ways (Python's native pow() ran circles around GMP's for this particular data). + That changes over time (recent Pythons are much faster at some of these tasks than the one you used). + A better algorithm is always the better answer (computing in decimal from the start allows pure Python to run circles around GMP computing in binary then forced to do a non-trivial 24-million bit base conversion). From usenet_spam at janc.invalid Sat Jun 5 22:11:07 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 06 Jun 2004 02:11:07 GMT Subject: file fragmentation project References: Message-ID: Bart Nessux schreef: > Python may not be suitable for this, but I thought I'd ask the experts: > > I'm doing a summer project that will attempt to measure exactly how file > fragmentation affects disk drive and OS performance. I'd like to use > Python for some of this. In particular, I'd like to write a file > fragmentor in Python that will randomly fragment x% of files on a NTFS > filesystem into y number of fragments. For example, assuming that we > start with a 100% defragmented drive, run the program to randomly > fragment 20% of the drive's files into 7 different fragments (may also > base the number of fragments on the file's size). > > Anyway, would Python be acceptable for this type of project? Speed is > somewhat important, but not extremely. > > All comments and advice are welcomed. Read this: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tjreedy at udel.edu Sun Jun 6 00:38:51 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 Jun 2004 00:38:51 -0400 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> Message-ID: "Jim Newton" wrote in message news:2if8daFmdreiU1 at uni-berlin.de... > how do you put an if or a for inside a lambda? By wrapping them in other functions; otherwise you don't. lambda *args: expr #abbreviates (minus the function name) def f(*args): return expr If your function is more complicated than that, don't try to abbreviate. Use def. Terry J. Reedy From matthewleslie at hotmail.com Fri Jun 4 15:24:43 2004 From: matthewleslie at hotmail.com (Matt Leslie) Date: Fri, 04 Jun 2004 14:24:43 -0500 Subject: Fetching the stdout & stderr as it flows from a unix command. In-Reply-To: References: Message-ID: Hans Deragon wrote: > Greetings. > > > I am performing: > > commands.getstatusoutput("rsync "); > > rsync takes a long time and prints out a steady stream of lines > showing which file it is currently working on. > > Unfortunatly, the commands.getstatusoutput() fetchs everything and > there is no way to ask it to copy the output of the command to > stdout/stderr. Thus when rsync takes an hour, I have no clue where it > is at. > > Anybody has a suggestion how to let stdout/stderr print out on the > console when calling a unix command? > Perhaps you could use the popen2 module. popen2.popen2() returns file handles for stdout and stderr. You could read from these and print the output to the screen while the process runs. Matt From thorkild at ifi.uio.no Wed Jun 23 22:54:16 2004 From: thorkild at ifi.uio.no (Thorkild Stray) Date: Thu, 24 Jun 2004 04:54:16 +0200 Subject: Setting X properties in tkinter or wxPython (solved in Gtk2) References: <994b391.0406231041.53ef77bd@posting.google.com> Message-ID: Den Wed, 23 Jun 2004 11:41:43 -0700, skrev Chris King: >> Anybody got an idea? > I'm not very familiar with wxPython, but it seems that even native Tk > can't set window properties (though the Tk C library can). Perhaps an > alternative is to use python-xlib > (http://python-xlib.sourceforge.net/). I'm even less familiar with > that, but the functions Display.create_resource_object and > Window.change_property look useful. Note that the Tk C library warns > against using native X calls in place of its functions. Yes, I thought about using python-xlib, or maybe just python-ctypes, but I am a little bit nervous about getting it to things correctly according to the GUI-package. I managed to do what I wanted with GTK2, though. I prototyped it in Gtk2-perl, but the same should be doable in PyGTK2 (the correct way of doing it is to call gtk.gdk.Window.property_change() to set the raw X property). My problem with PyGTK2 is the surprising problems I am having with getting a hold of the window X identifier. It seems that they removed gtk.gdk.window.xid somewhere between 1.99 and 2.0, and just added it back in the 2.3-series (I believe it was added 20th of April, 2004). There is a patch available on how to enable this for older versions described at: http://www.daa.com.au/pipermail/pygtk/2003-March/004641.html My problem is that I would either have to demand that the user patches his pygtk2 (not likely), or to demand that they install bleeding edge unstable versions of pygtk2. So now I am looking for a way around this.. Maybe I could either do it in embedded C, or by calling xwininfo on the window and find it there.. both quite ugly workarounds. :-( -- Thorkild From loic at fejoz.net Mon Jun 28 06:06:35 2004 From: loic at fejoz.net (Yermat) Date: Mon, 28 Jun 2004 12:06:35 +0200 Subject: Class Chaos In-Reply-To: References: Message-ID: Maximilian Michel wrote: > Hallo everyone, > > i hope someone can help me with this kind a interesting problem i have > in python 2.3: > > my code looks like this: > > class Read: > list = [] > __init__(self): > self.list.append = ***data from file*** > print(self): > print self.list > > instantiating it one time works ok, assuming data from file = AAA: > ... > a = Read() > AAA > but when i continue, instantiating more object of the Read class this > happens: > b = Read() > AAA > AAA > c = Read() > AAA > AAA > AAA > it's like the new instance always continues or reimports the data from > the former instance. > Or is it just a dumb mistake i keep making? Of course ! list is a class attribute so it is share by all instances ! You should initialize list in the __init__ method : class Read: def __init__(self): self.list = [] self.list.append... -- Yermat From rogerb at rogerbinns.com Sun Jun 6 22:03:11 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 6 Jun 2004 19:03:11 -0700 Subject: Creating an RPM which works with multiple Python versions? References: Message-ID: Edwin Young wrote: > 2) Produce separate 2.2 and 2.3 packages. This is kind of a pain for > users, so I'd rather not if possible. That is standard practise for distributing binary Python modules. Look at wxPython, win32all etc > Any suggestions? You could distribute your app as a whole without relying on an installed Python or any other libraries. If you want an example, have a look at dotamatic.sourceforge.net which ships Windows, Linux and Mac "binaries". In the source, makedist.py is the script that produces the right thing on each platform and the help lists the components used. Roger From belred1 at yahoo.com Tue Jun 15 08:47:22 2004 From: belred1 at yahoo.com (Bryan) Date: Tue, 15 Jun 2004 12:47:22 GMT Subject: python23_d.lib In-Reply-To: References: <40CA5F3E.1010604@yahoo.com> <40CC5C67.9040803@yahoo.com> Message-ID: <40CEEFD8.9050308@yahoo.com> Shankar KN wrote: > Hi, > > Thanks for the reply. > But the problem persists. > > There is only place where I do a #include (its in a .i file) > I did what you suggested around this include. > > the problem is that running SWIG on this .i generates a .cxx file which we > don't want to modify. > This .cxx file has multiple occurences of #include , and only one > occurence gets the "guard" against _DEBUG. > > Am I missing something here? > > sorry, i don't use swig, so i'm no going be able to help you with that. but couldn't you write a python post-process script that modifies the file automatically when compiled debug? if this is too much of a pain, then maybe compiling a debug version of python would be your simplest solution. bryan From NAIGIMSESRIMAIL at gims.com Thu Jun 10 20:35:34 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Fri, 11 Jun 2004 02:35:34 +0200 Subject: ALERT - GroupShield ticket number OA26_1086914112_ESRIMAIL_1 was generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: shiran at jps.net Sent: 2007796736,29642484 Subject: Re: Re: Thanks! Attachment Details:- Attachment Name: document.pif File: document.pif Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Netsky.d at MM -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1873 bytes Desc: not available URL: From rogerb at rogerbinns.com Sun Jun 13 19:38:51 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 13 Jun 2004 16:38:51 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <40CC1ABC.4010400@v.loewis.de> <40CC9AA2.5080409@v.loewis.de> Message-ID: <695vp1-aok.ln1@home.rogerbinns.com> Martin v. L?wis wrote: > So in short: you are not proposing an implementable > solution. Actually I did. I am not saying this is not a hard problem. It *is* a hard problem. It is also a very real problem as we have seen handled in various ways in various languages. But at one point generating code for algorithms was hard, and then compilers were invented. And memory management was hard and GC was invented. Storage was hard and filesystems were invented. The whole point of languages is to make stuff easier. And Python excels at letting the machine deal with machine issues. None of the tens of thousands of lines of Python code I have written even knows what byte ordering a machine uses, or even its natural word size. So here is a hard problem. Feel free to prove that it is insoluable (in the computer science sense), or lets pick a solution that improves things. As a programmer I would be very happy to get an exception or similar diagnostic if I create a case that Python can't currently cope with. I can change my code to fix it. But making every consumer of every resource including indirectly deal with something the machine should figure out is silly. They used to do that once about memory and fortunately those days are behind us. And if you want an example of how complex this can get, try and modify the XML-RPC stuff to work over SSL and due multiple requests/responses per connection. There are several layers of libraries and external resources involved, and currently a lot of code written by very smart people that tries real hard, has to implement its own reference counting in Python, and doesn't work over SSL or handle more than one request per connection. Roger From rhh at structurelabs.com Fri Jun 4 02:18:15 2004 From: rhh at structurelabs.com (r holland) Date: 3 Jun 2004 23:18:15 -0700 Subject: automatic naming of variables to create objects References: Message-ID: Thanks for that, Peter. From a.schmolck at gmx.net Thu Jun 3 17:46:15 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Thu, 03 Jun 2004 22:46:15 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> Message-ID: hungjunglu at yahoo.com (Hung Jung Lu) writes: > There are a few lessons learnt from younger programming languages, > like Io. I'm a bit suprised we have to learn from IO given that at least on superficial inspection, IO mostly seems to self as ruby is to smalltalk. > One lesson is that you really would like to avoid rigid statement syntax. How do younger languages like IO make this point more forcefully than lisp, smalltalk etc -- languages which have been around for decades? I also suspect that the statement/expression distinction is beneficial at least for inexperienced programmers (a declared target audience of python), simply because it means that there are less ways to express the same thing and nesting is limited -- in other words, I believe there is some trade off involved. > In the example of the original topic of this thread, you cannot > intercept/override exception handling mechanism because the > try:...except:... block is not a function. I don't think having try/except functions instead of statements provides a sufficient solution. Apart from the fact that functions in themselves don't provide an adequate control flow mechanism for exceptions, I don't want to have to write my own error handling mechanisms in order to be able to deal with some limited subset of errors raised in *my* code -- I want to be able to deal with *all* errors in an interactive session, no matter where they were raised and I don't want to have to rewrite (or slow down) *any* code in order to do so. > Similar situations happen with issues regarding aspect-oriented programming. > In a language like Io, everything is a method that send message to an > object. Even If(...) statements are methods, as well as loops. The advantage > is you can intercept things at your heart's content. It would allow some interception, but I don't think enough for my heart's content because exceptions are completely different beasts from functions, certainly in python (dynamically scoped ones, for starters). > In comparison, Python's exception handling is not interceptible, because > exception handling is hard-coded in syntax. I don't think syntax is the sticking point here -- you could do some additional, possibly useful, things if raise where, say, a method, but I can't see how it would go anywhere near solving the problem. > It does not mean all hope is lost in Python. But it does mean that > instead of using the raise... statement in Python, you need to call a > function/method instead. Such an approach doesn't really help much -- not only because I obviously can't (and don't want to) rewrite all the code that might raise an exception (which often isn't even python). > You can then intercept at that level: either by actually throwing an > exception, or by redirecting it to some user intervention funtion, or by > totally ignoring it (like using a 'pass' statement.) Yes, but this is clearly insufficient. > Interactive programming with features like edit-and-continue still has > room to grow (most edit-and-continue features are not transactional, > that is, you cannot revert changes easily.) But in my opinion that's > an arena for prototype-based languages, I don't see how prototype-based languages have a particular edge here -- Common lisp and Dylan, for example, support continuable conditions and can hardly be called protype-based. > As for Python's interactive programming, I've done some experiment > before. It's not totally impossible. It's a bit uncomfortable. Python > does have module reload and weakref. When you use these tools > properly, you can achieve a high degree of non-stop programming. I know -- I currently don't depend on weakref, but I use reload quite a lot and I do all my programming in interactive sessions which sometimes last days. > It does not come as part of the language per-se. You need to build up some > tools yourself first. This is one of the sticky points -- it requires some work and expertise (and even then you are a long way off from e.g. smalltalk) and this in turn is likely to mean that most python users won't get to experience the benefits of interactive development (which in turn presumably means that libraries and utilities often don't cater well for interactive use). 'as From claird at lairds.com Wed Jun 16 07:57:11 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 16 Jun 2004 11:57:11 -0000 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <10d0dcnrqlpc707@corp.supernews.com> In article , David MacQuigg wrote: >On Sat, 12 Jun 2004 03:22:23 GMT, Mediocre Person > wrote: . . . >> * it appears to be FREE (which in a high school environment is >>mightily important) from both python.org or activestate.com. I think I >>like activestate's ide (under Win98) a bit better than idle, but your >>comments/suggestions? > >I haven't looked at Activestate, but it may be the right choice if you >are using Windows. Qt Designer is free only on Linux. I think there . . . Many ActiveState resources for Python are both free of charge and available for Linux (and Solaris and ...) , not just Windows. One consideration in all this talk of "teaching GUI construction" is to emphasize Web applications. The biggest surprise to me in this thread is that that hasn't been taken more seriously. I suspect that's where my daughters will start, if they ever choose to try out development. -- Cameron Laird Business: http://www.Phaseit.net From http Thu Jun 3 12:01:07 2004 From: http (Paul Rubin) Date: 03 Jun 2004 09:01:07 -0700 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> Message-ID: <7x4qpsvdfg.fsf@ruckus.brouhaha.com> claird at lairds.com (Cameron Laird) writes: > This is *extremely* exciting--at least to me. I'll try to express > why I see this as so important. Well, it's pretty cool anyway, for sure. I don't see it as a GCC replacement since it compiles just a C subset, and has to be a lot slower than GCC. But yes, it's probably easier to retarget, etc. > First, many readers probably don't have a full appreciation of > gcc's defects. gcc is a wonderful project, and its contributors all > deserve our appreciation. It does *not* meet all needs, though: its > implementation is difficult, portable only with difficulty, bulky, > and still a poor fit on several architectures. A compiler that > invites experimentation, cross-compiling, and is easily installed > ... well, my head's spinning with ideas. You might also look at . > 'Few immediate tangents: everyone read Miki's piece on Python-coded > *assemblers* http://www.unixreview.com/documents/s=9133/ur0404e/ >? We all know > that Python plays nicely with C in that it's easy to make successful > partnerships between Python- and C-coded modules; such projects as > Pyrex, Critcl, and Inline:: show the potential for managing these at > the project level with the higher-level language's power. Think > what it means, now, to deepen that integration, so that the compiler > (or assembler!) itself becomes scriptable! -- Um, if you want to program in Lisp, why just program in Lisp directly instead of messing with C and Python? From max at alcyone.com Tue Jun 8 16:08:26 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Jun 2004 13:08:26 -0700 Subject: promoting [] by superclass? References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9hjFnvcsbU1@uni-berlin.de> <40C4FF56.F81105B@alcyone.com> <2il6llFo4tkpU1@uni-berlin.de> <40C580A0.A01B38A7@alcyone.com> <2im7kkFnjduhU1@uni-berlin.de> Message-ID: <40C61CBA.D6A8BC0A@alcyone.com> Jim Newton wrote: > wow that is great. > > now the other question: > > class Pair(list): > ... > > how can i "cast", "promote" [] to class Pair? You can't. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Sometimes there's no point in giving up. -- Louis Wu From mike at nospam.com Mon Jun 28 15:04:04 2004 From: mike at nospam.com (Mike Rovner) Date: Mon, 28 Jun 2004 12:04:04 -0700 Subject: what editor do you use? References: Message-ID: One of the most useful (for me) features I seek in editor is 'auto word completion'. When I type something the editor put the word it thinks I type and I can accept (by TAB) or ignore it and continue typing. So far least intrusive (in my way) is FAR internal editor with autocompletion plugin. Mike From fperez528 at yahoo.com Wed Jun 9 21:23:26 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 09 Jun 2004 19:23:26 -0600 Subject: dropping into the debugger on an exception References: <2inqlrFp53m5U1@uni-berlin.de> Message-ID: Jon Perez wrote: > (sorry for the duplicate post, just wanted to make the subject > line clearer) > > How do you set up pdb such that you will automatically > get dropped into its prompt if an unanticipated exception > occurs in a script you are using? You may want to try out ipython (http://ipython.scipy.org). It does exactly what you want (and a lot more): In [1]: cd ~/test /usr/local/home/fperez/test In [2]: pdb Automatic pdb calling has been turned ON In [3]: run error hi Ramp time: 0.0 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /usr/local/home/fperez/test/error.py 109 110 print 'speedup:',Rtime/RNtime 111 112 --> 113 if __name__ == '__main__': main() /usr/local/home/fperez/test/error.py in main() 104 array_num = zeros(size,'d') 105 for i in xrange(reps): --> 106 RampNum(array_num, size, 0.0, 1.0) 107 RNtime = time.clock()-t0 108 print 'RampNum time:', RNtime /usr/local/home/fperez/test/error.py in RampNum(result, size, start, end) 88 tmp = zeros(1e2) 89 step = (end-start)/(size-1-tmp) ---> 90 result[:] = arange(size)*step + start 91 92 def main(): ValueError: frames are not aligned > /usr/local/home/fperez/test/error.py(90)RampNum() -> result[:] = arange(size)*step + start (Pdb) print start 0.0 You can then quit pdb, type 'pdb' again to disable the feature, and move on. Cheers, f From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Fri Jun 25 13:31:27 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Fri, 25 Jun 2004 19:31:27 +0200 Subject: Python Magazine exists! (was: Python intro questions) References: Message-ID: Hi ! Interesting ; but how do, for to have : - invoice (fiscal document in paper, obligatory in France) - adress of supplier (fiscal information, obligatory in France) - n? intracommunautaire of TVA (fiscal information, obligatory in France) - information of customs (douane ?) (obligatory for purchase in a foreign country) Thank you -- Michel Claveau From alex-news-deleteme at comcast.net Sun Jun 6 23:27:22 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Mon, 07 Jun 2004 03:27:22 GMT Subject: Misunderstanding about closures Message-ID: When I define a function in the body of a loop, why doesn't the function "close" on the loop vairable? See example below. Thanks, Alex C:\Documents and Settings\Alexander May>python Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> l=[] >>> for x in xrange(10): ... def f(): ... return x ... l.append(f) ... >>> l [, , , , , , , , , ] >>> for f in l: ... f() ... 9 9 9 9 9 9 9 9 9 9 On the other hand, the following works as I expected. >>> l=[] >>> def makef(x): ... def f(): ... return x ... return f ... >>> for x in xrange(10): ... l.append(makef(x)) ... >>> l [, , , , , , , , , ] >>> for f in l: ... f() ... 0 1 2 3 4 5 6 7 8 9 >>> From dallasm at aiinet.com Mon Jun 7 17:52:24 2004 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Mon, 7 Jun 2004 17:52:24 -0400 Subject: Python Wiki & wiki Hosting? Message-ID: > It got to the point > where many of the developers would cut the information out of > the text area, work on it in Emacs, and paste it back. The > end result being that many changes were not made without a > great deal of nagging on my part. So do you really want a WYSIWYG editor or maybe just a way to plugin wiki editing to a text editor. I could imagine a plugin for your favorite editor that could perform the necessary http code to get the contents of the wiki, make the changes in the editor and then post the contents bback to the wiki. Similar to how many FTP plugins work yet more complicated.... Actually I may have just found a cool project to work on. WooHoo! -- Dallas From davidf at sjsoft.com Tue Jun 29 05:35:35 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 29 Jun 2004 11:35:35 +0200 Subject: wxPython woes In-Reply-To: <2kcnmuFm9cgU1@uni-berlin.de> References: <8816fcf8.0406282329.32c58e6c@posting.google.com> <2kcnmuFm9cgU1@uni-berlin.de> Message-ID: Reinhold Birkenfeld wrote: > David Fraser wrote: > >>Sridhar R wrote: >> >>>km wrote in message news:... >>> >>> >>>>Hi all, >>>> >>>>I feel its a real pain to install wxPython from sources it goes back to install gtk+ etc . may be thats why its not yet become defacto GUI standard for python. >>>>but i'd like to know if anyone has made it easy with an installer for wxPython on linux (Debian woody)? >>> >>> >>>Well, if your app. is target mainly to the UNIX platform, then you may >>>want to try PyGTK - http://www.pygtk.org (basically wxPython is just >>>another layer over GTK). GTK port is available for win and mac also >>>(look at gimp for eg.) - also see http://gtk-wimp.sf.net. >>> >>>still, wxPython is better for apps to be run on win,mac and unix, but >>>gtk+ is catching very close. >> >>The important difference is that wxWindows and wxPython are designed to >>use real native widgets as much as possible, whereas gtk-wimp is >>basically trying to use theming to make GTK widgets look like Windows >>widgets. > > > The difference is the number of layers on the different platforms: > > Under Un*x: > wxPython --> wxWidgets --> GTK --> Xlib > -- or -- > PyGTK --> GTK --> Xlib > -- or -- > PyQt --> Qt --> Xlib > > Under Windows: > wxPython --> wxWidgets --> Native Windows Controls > -- or -- > PyGTK --> GTK --> Wimp --> Native Windows Controls > > Reinhold > This isn't really what it says on the gtk-wimp page. Is it true? # # When running on XP, the Windows theming API is used so that GTK widgets look like native widgets. That's a different story to them actually being native widgets. David From thorsten at thorstenkampe.de Wed Jun 16 17:31:50 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 16 Jun 2004 23:31:50 +0200 Subject: Combined natural and unnatural list sorting References: Message-ID: <1j72a1oyhjhjl$.dlg@thorstenkampe.de> * Derek Basch (2004-06-15 23:38 +0100) > Hello All, > > I need to sort a list using an unnatural sequence. > > I have a list like so: > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] > > print foo.sort() > > ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S'] > > The order that I actually need is: > > ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] > > So, in other words, I need the colors sorted alphabetically and the the sizes > sorted logically. > > I looked for a while at using comparison functions with sort but I don't think > that will work. Anyone been down this road? Suggestions? You need some kind of general "function sort" (either using the "Decorate, Sort, Undecorate" or the "pass a function" idiom): def funcsort(seq, function, modus = 'dsu'): """ sort seq by function(item) """ if modus == 'dsu': seq = [(function(item), index, item) for index, item in enumerate(seq)] seq.sort() return [item[2] for item in seq] elif modus == 'pass': seq = seq[:] seq.sort(lambda x, y: cmp(function(x), function(y))) return seq This is a common kind of sort problem so you will need this "function sort" anyway in near future. Then your problem simply translates to find a function that generates your sort items like you want them sorted (in this case something like 'White/M' -> ('White', 2) ): SIZE_MAP = {'S': 1, 'M': 2, 'L': 3, 'XL': 4} def func(item): splititem = item.split('/') return splititem[0], SIZE_MAP[splititem[1]] print funcsort(foo, func) Thorsten From allen at premierweb.com Sat Jun 12 19:47:45 2004 From: allen at premierweb.com (Allen Unueco) Date: Sun, 13 Jun 2004 11:47:45 +1200 Subject: time.strftime Timezone issue Message-ID: I feel that the '%Z' format specifier from strftime() returns the wrong value when daylight savings is in effect. Today the following is always true: time.strftime('%Z') == time.tzname[0] Shouldn't it be: time.strftime('%Z') == time.tzname[time.daylight] -allen From lyuan at ucdavis.edu Sat Jun 5 03:58:24 2004 From: lyuan at ucdavis.edu (lyuan) Date: Sat, 05 Jun 2004 00:58:24 -0700 Subject: write a bitmap using python Message-ID: Hi, How can I write a bitmap using python? I have some integer data and want to generate a bitmap graph for visualization. Any suggestion will be appreciated. Sorry if this is an FAQ, BTW, where can I find the FAQ of this list? thanks Lihua From mcfletch at rogers.com Mon Jun 14 22:40:13 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 14 Jun 2004 22:40:13 -0400 Subject: Finding Function Args? In-Reply-To: References: Message-ID: <40CE618D.8090907@rogers.com> Check the standard module inspect, particularly; >>> import inspect >>> import cgi >>> inspect.getargspec( cgi.escape ) (['s', 'quote'], None, None, (None,)) HTH, Mike Chris S. wrote: > Is there a way to dynamically find out how many arguments a function > requires? I thought this would be listed somewhere with dir() but I > can't find anything. Any help is appreciated. ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From gherron at islandtraining.com Fri Jun 11 13:17:49 2004 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 Jun 2004 10:17:49 -0700 Subject: python23_d.lib In-Reply-To: References: Message-ID: <200406111017.49298.gherron@islandtraining.com> On Friday 11 June 2004 09:59 am, Shankar KN wrote: > Hi, > > I am trying to get a hand on python23_d.lib but in vain. > I am developing a C++ dll which has a SWIG interface to the Python world. > After installing Python and SWIG I am able to build this DLL in Release > mode but not in Debug mode beacuse of non-availability of python23_d.lib. > > Any clues as to how I could proceed with Debug build? > > Thanks, > With best regards, > Shankar I just copied python23.lib to the proper spot renaming it to python23_d.lib. I suppose this is not an ideal solution, but it did shutup the complaints so I could proceed. Perhaps someone (else) can provide a "real" solution, Gary Herron From lbates at swamisoft.com Thu Jun 24 09:56:41 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 24 Jun 2004 08:56:41 -0500 Subject: saving the text on python dos window. References: Message-ID: You may want to take a look at the logger class that is built into python. You can create a log of everything that goes to the screen for every session that the program runs. It also provides a powerful way to log any errors/exceptions that may occur during program execution. HTH, Larry Bates Syscon, Inc. "sarmin kho" wrote in message news:mailman.77.1088067779.27577.python-list at python.org... Hi Pythoners.. "print (text)' command will print the 'text' on dos window when executing a python script. i would like to save all the text printed on the dos window to a file at the end of the python script execution.. sys.stdout.GetLine() gave me an empty string.. where is the handle to the printed text, please? i m also using scripts written by someone else so some printed texts are not mine but i would like to keep all the printed text for debugging.. the printed texts contain not only error messages but also all other texts i wish to keep. many thanks chaps.. sarmin Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! From hpj at urpla.net Thu Jun 10 14:27:22 2004 From: hpj at urpla.net (Hans-Peter Jansen) Date: Thu, 10 Jun 2004 20:27:22 +0200 Subject: speed problems References: Message-ID: Hi Axel & Pythoneers, I played around with your scripts, and my winner got a bit longer than usual. I hope, the important part doesn't suffered to much, but thanks to a cheat, this one is faster than your original perl script, even with profiling and annotations enabled! Talking 'bout the latter: shamelessly stolen from a Zope check in by our master master, because I couldn't get hotshot to produce useful per line statistics out of the box. http://mail.zope.org/pipermail/zope-cvs/2002-May/001035.html Well, although I have to admit, that perl seems faster on this specific task (since the grep cheat would work for perl too), I would never consider such a move, just try to do this with perl: ---8<--- [virstat.py] ---8<--- #!/usr/bin/python import os import re maillogs = [ "mail", "mail-20040600.gz", "mail-20040604.gz", "mail-20040607.gz", "mail-20040610.gz" ] #gzip = "/usr/bin/gzip -dc" #bzip2 = "/usr/bin/bzip2 -dc" gzip = "/usr/bin/zcat" bzip2 = "/usr/bin/bzcat" virstat = {} total = 0 doprof = 1 pat = re.compile( "INFECTED \((.*)\)" ) def dovirstat(): global virstat, total for logfile in maillogs: if os.path.isfile(logfile): # is it compressed? if logfile.endswith('.gz'): #ifd, lfd = os.popen2("%s %s" % (gzip, logfile)) #XXX: cheating ifd, lfd = os.popen2("%s %s | grep INFECTED" % (gzip, logfile)) elif logfile.endswith('.bz2'): #ifd, lfd = os.popen2("%s %s" % (bzip2, logfile)) #XXX: cheating ifd, lfd = os.popen2("%s %s | grep INFECTED" % (bzip2, logfile)) else: # uncompressed lfd = open(logfile, "r") # hot loop for line in lfd: mo = pat.search(line) if mo: for vnam in mo.group(1).split( ", "): virstat[vnam] = virstat.get(vnam, 0) + 1 total += 1 lfd.close() # else: # print "logfile '%s' doesn't exist, skipping it." % logfile def load_line_info(log): byline = {} prevloc = None for what, place, tdelta in log: if tdelta > 0: t, nhits = byline.get(prevloc, (0, 0)) byline[prevloc] = (tdelta + t), (nhits + 1) prevloc = place return byline def basename(path, cache={}): try: return cache[path] except KeyError: fn = os.path.split(path)[1] cache[path] = fn return fn def print_results(results): for info, place in results: if not place: print 'Bad unpack:', info, place continue filename, line, funcname = place print '%8d %8d' % info, basename(filename), line def annotate_results(results): files = {} for stats, place in results: if not place: continue time, hits = stats file, line, func = place l = files.get(file) if l is None: l = files[file] = [] l.append((line, hits, time)) order = files.keys() order.sort() for k in order: if os.path.exists(k): v = files[k] v.sort() annotate(k, v) def annotate(file, lines): print "-" * 60 print file print "-" * 60 f = open(file) i = 1 match = lines[0][0] for line in f: if match == i: print "%6d %8d " % lines[0][1:], line, del lines[0] if lines: match = lines[0][0] else: match = None else: print " " * 16, line, i += 1 print if not doprof: dovirstat() else: import hotshot prof = hotshot.Profile("virstat.prof", lineevents=1) prof.runcall(dovirstat) prof.close() vlist = virstat.keys() vlist.sort() for vname in vlist: p = (virstat[vname] / float(total)) * 100 print "%-30s %5.2f%%" % (vname, p) print if doprof: from hotshot.log import LogReader log = LogReader("virstat.prof") byline = load_line_info(log) results = [(v, k) for k, v in byline.items() if k and k[0] == 'virstat.py' ] results.sort() #print_results(results) annotate_results(results) --->8--- Python programming is not only an easy way to get necessary work done, on it's best it combines art and science in an esthetic manner. Pete From df191 at ncf.ca Sat Jun 26 06:03:13 2004 From: df191 at ncf.ca (df191 at ncf.ca) Date: Sat, 26 Jun 2004 18:03:13 +0800 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: drugs? ... -------------- next part -------------- A non-text attachment was scrubbed... Name: privacy.zip Type: application/x-zip-compressed Size: 25473 bytes Desc: not available URL: From rzantow at ntelos.net Sun Jun 27 11:37:41 2004 From: rzantow at ntelos.net (rzed) Date: Sun, 27 Jun 2004 15:37:41 GMT Subject: ImportError: No module named functional References: <20040627091714.5FCC37BD0@mail.studiomanfredini.it> Message-ID: Maurizio Colucci wrote in news:bzBDc.538623 $rM4.22514654 at news4.tin.it: > http://www-106.ibm.com/developerworks/linux/library/l-prog3.html >From part two of that series: Bryn Keller's "Xoltar Toolkit" will provide valuable assistance. Keller has collected many of the strengths of FP into a nice little module containing pure Python implementations of the techniques. In addition to the module *functional*, Xoltar Toolkit includes the lazy module, which supports structures that evaluate "only when needed." So it appears to be part of this toolkit. See . -- rzed From lsmithso at NOhare.SPAM.demon.co.uk Thu Jun 17 05:56:30 2004 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 17 Jun 2004 10:56:30 +0100 Subject: Need some help with Python/C api and threading References: Message-ID: >>>>> "Steve" == Steve Menard writes: Steve> Here is my problem. I have this library thats hosts Steve> another language within python, and allows that language to Steve> call back INTO python. Steve> All is good as long as the other languages calls back on Steve> the same thread. If the callback arrives on a different Steve> thread, all hell break loose and the program dies horribly. Steve> looking at the C api documentation, I came upon the Steve> following block of code : Steve> PyThreadState *tstate; PyObject *result; Steve> /* interp is your reference to an interpreter Steve> object. */ tstate = PyThreadState_New(interp); Steve> PyEval_AcquireThread(tstate); Steve> /* Perform Python actions here. */ result = Steve> CallSomeFunction(); /* evaluate result */ Steve> /* Release the thread. No Python API allowed beyond Steve> this point. */ PyEval_ReleaseThread(tstate); Steve> /* You can either delete the thread state, or save it Steve> until you need it the next time. */ Steve> PyThreadState_Delete(tstate); Steve> Which would seem to be what I need. However, I have no idea Steve> how to get at that interp pointer. I tried the following : Steve> PyInterpreterState* interp = Steve> PyInterpreterState_New(); PyThreadState *tstate = Steve> PyThreadState_New(interp); PyEval_AcquireThread(tstate); Steve> but then it crashes on the second line ... Steve> Anybody ever done this? As a side note, the hosted language Steve> can start an arbitrary number of threads ... Steve> Steve I haven't done this for a while and I'm a little hazy on it, so this may be incorrect: I used 'PyThreadState *ts = Py_NewInterpreter();' to set a new sub-interpreter state if called in a new thread. If the embedded script calls back into the extension, it restores that thread state and acquires the GIL before making any other Py* calls by calling 'PyEval_RestoreThread(ts);'. Before returning, it calls 'PyEval_SaveThread()'. From michele.simionato at poste.it Tue Jun 8 01:41:38 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 7 Jun 2004 22:41:38 -0700 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: <95aa1afa.0406072141.78f0fedd@posting.google.com> Alexander Schmolck wrote in message news:... > Not quite. In fact in the language that more or less started it all, scheme, > the standard iteration construct 'do' does indeed introduce a *new binding* on > each iteration. > Common Lisp OTOH doesn't -- like python: > A thoughtful discussion of Python/Scheme/Lisp closures and for loops was made by Jacek Generowicz in this thread: http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&oe=UTF-8&threadm=tyfsmgtbewl.fsf%40lxplus030.cern.ch&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26q%3Dsimionato%2Blambda%26btnG%3DCerca%26meta%3Dgroup%253Dcomp.lang.python.* From qrczak at knm.org.pl Mon Jun 14 11:19:39 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Mon, 14 Jun 2004 17:19:39 +0200 Subject: what about unsigned and signed 8 bits number, 16 bits, etc?? References: <20040614132256.19010.qmail@web50605.mail.yahoo.com> Message-ID: On Mon, 14 Jun 2004 16:50:36 +0200, Miki Tebeka wrote: > The range of int is the same as of the machine int (the C compiler that > was used to build Python). No, Python int corresponds to C long. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From michele.simionato at poste.it Thu Jun 10 01:29:29 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 9 Jun 2004 22:29:29 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Message-ID: <95aa1afa.0406092129.74170de1@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0406091457.6c5ffaec at posting.google.com>... > Alexander Schmolck wrote: > > How do younger languages like IO make this point more forcefully than lisp, > > smalltalk etc -- languages which have been around for decades? > > Double checked with Lisp just now. And Lisp did not allow me to > redefine "if", "setq", "t", etc. In a sense, Lisp is not keywordless, > whereas Io is truly keywordless. As I said, in Io even "if" and > "while" are implemented as regular functions. In Lisp, you cannot > intercept "if", "setq", etc. It does. You just don't see it. Most people can't see it. And I am not telling the details. :) Smart people know what I am talking about. And I'll just leave it at that. Sorry, can't say anymore. :) Michele Simionato From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jun 18 08:28:08 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 18 Jun 2004 14:28:08 +0200 Subject: String buffer In-Reply-To: <32e4319c.0406172135.71c279d5@posting.google.com> References: <32e4319c.0406172135.71c279d5@posting.google.com> Message-ID: <40d2dfdb$0$36169$e4fe514c@news.xs4all.nl> Connelly Barnes wrote: > Yet another useful code snippet! > > This StringBuffer class is a FIFO for character data. How is this different from (c)StringIO from the std library? Especially cStringIO is interesting because of its speed. --Irmen From edwin at bathysphere.org Mon Jun 7 09:57:25 2004 From: edwin at bathysphere.org (Edwin Young) Date: 07 Jun 2004 06:57:25 -0700 Subject: Creating an RPM which works with multiple Python versions? References: <40C4012C.5040804@v.loewis.de> Message-ID: "Martin v. L?wis" writes: > [You can] Install to /usr/lib/site-python. This > is a location that is shared across different Python releases. > > Be careful not to put bytecode files into this location, since > bytecode files may become invalid across Python releases. It seems like "setup.py bdist_rpm" by default creates an archive containing .pyc files, so the RPMs it creates are effectively bound to a specific Python version, even if no C-coded extensions are involved. However I believe that if the .pyc is for the wrong interpreter version, Python will ignore it and use the .py instead, so the only effect will be longer startup time.Can anyone confirm or deny? -- Edwin From zzzzzz at xxx.yyy Thu Jun 10 19:02:59 2004 From: zzzzzz at xxx.yyy (Alan Connor) Date: Thu, 10 Jun 2004 23:02:59 GMT Subject: [script] dis/assembling mbox email References: <2is2ebFr1sbvU1@uni-berlin.de> Message-ID: On 10 Jun 2004 21:34:04 GMT, William Park wrote: > > mbox.sh $i > done > echo "--$boundary--" > echo > else > [ "`head -1 body`" ] && echo # blank line at top > cat body > [ "`tail -1 body`" ] && echo # blank line at bottom > : # dummy, so that return code is 0 > fi > > ----------------------------------------------------------------------- Thanks, William. Tucked it away. Could come in REAL handy. AC -- http://angel.1jh.com./nanae/kooks/alanconnor.html http://www.killfile.org./dungeon/why/connor.html From peter at engcorp.com Mon Jun 28 09:26:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Jun 2004 09:26:43 -0400 Subject: Wow, THAT never happens in C! In-Reply-To: <889cbba0.0406280136.6f0f472f@posting.google.com> References: <889cbba0.0406280136.6f0f472f@posting.google.com> Message-ID: Kamilche wrote: > I just discovered the debugging flags for the garbage collector. Since > I have an insanely hierachical structure to my dataset, with > references all OVER the place, I thought I'd turn it on to make sure I > wasn't leaking. > > Nothing happened. I searched the internet, and discovered how to > 'force' a leak, so I tested with the single forced leak to see what > would happen. It worked. > > My code did NOT have any leaks in it! :-D That's almost a miraculous > occurrence when programming in C. It's also pretty much always going to be the case with Python, unless you accidentally build code that defeats the garbage collection scheme (ie. loops and __del__) or are in the habit of writing code where items accumulate in lists and are never removed. The only real leak I've ever found with Python was a bug in the Python code itself (long since fixed, by the way, and in fact fixed in a later version even before I found it in the version I was using). > I can't believe how much time I wasted trying to create my humongous > project with C. :-( You speak for many of us. :-) From marduk at python.net Thu Jun 24 12:38:41 2004 From: marduk at python.net (marduk) Date: Thu, 24 Jun 2004 11:38:41 -0500 Subject: Python Color Printing References: <889cbba0.0406240136.3a735356@posting.google.com> Message-ID: On Thu, 24 Jun 2004 02:36:20 -0700, Kamilche wrote: > I'm pretty desperate to get color syntax printing. I just tried out > the evaluation version of 'Komodo', which several people in here > suggested, and its print features are terrible. The text is coming out > huge when I print at 8 point, tiny when I'm printing at 14 point (so > tiny that it looks like subscripts), the margins are reset at random, > and so on. Plus it doesn't recognize all my fonts. > > I don't care if the pretty printer is in an IDE. I just want color > printing with headers and footers! And I wanted it automated - I don't > want to have to print each one by hand, I want to start them all > printing and walk away. It has to be able to print in larger fonts > reliably, because 10 point is too small for my computer-weary eyes. GNU enscript supports highlighting (in color?). As well as headers, footers, and a lot of other cool stuff. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From tony.ha at philips.com Wed Jun 9 06:41:05 2004 From: tony.ha at philips.com (tony.ha at philips.com) Date: Wed, 09 Jun 2004 10:41:05 GMT Subject: Python IDLE Question Message-ID: <5PBxc.364$9V3.4148@ns2.gip.net> Hello, I have a question about Python IDLE, when I run a Python script under the Edit Window of IDLE, i.e Run -> Run Module, I have the following Message: IDLE 1.0.3 >>> Warning: HOME environment variable points to C: but the path does not exist. ================================ RESTART ================================ 1. What does this Warning about? Do I need to set my HOME variable to some where else? If so, where? 2. "but the path does not exist" What does this refer to? what path? NOTE: I run Python IDLE under Windows XP, and I check the environment variable, there is NO HOME variable in the environment! By the way, the scripts run ok under IDLE, just curiosity about this message! From gh at ghaering.de Sat Jun 19 01:57:14 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 19 Jun 2004 07:57:14 +0200 Subject: Anyone know a good Pygresql Tutorial for Interfacing between Python &Postgresql In-Reply-To: References: Message-ID: <40D3D5BA.2010203@ghaering.de> Peter Maas wrote: > Chuck Amadi schrieb: > >> Anyone know a good Pygresql Tutorial for Interfacing between Python & >> Postgresql . > > > Tried Google and found > > http://www.pygresql.org/README.txt This describes the PyGreSQL proprietory interface. It would IMO be a much better idea to use a DB-API compliant interface, like pyPgSQL or psycopg offer. Or PyGreSQL through the pgdb module included. -- Gerhard From rosendo at dbora.com Mon Jun 21 08:45:50 2004 From: rosendo at dbora.com (rosendo) Date: 21 Jun 2004 05:45:50 -0700 Subject: ANN: kronos, a task scheduler References: <40ad1f5c$0$36860$e4fe514c@news.xs4all.nl> <95aa1afa.0405211958.57ae218b@posting.google.com> <40af3b46$0$65124$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<40af3b46$0$65124$e4fe514c at news.xs4all.nl>... > Michele Simionato wrote: > > > I havent't looked at the code it is unclear to me if kronos is a kind of daemon > > or not: what happens if I reboot my machine? Is it enough to restart kronos > > in some init script to get the scheduled task to be executed at the right > > times or is it more complicate than that? > > Kronos is not a daemon in the "crond" sense. > When started, it runs as a separate thread or process alongside your > own program. It doesn't store or remember the scheduled tasks by itself. > It shouldn't be too hard to make some sort of persistent task definition > (a "kronostab" if you will) and a little bit of extra code that reads > this definition at startup. > > Perhaps it is a nice idea to add a feature to kronos that it can store > the scheduled tasks by itself, so that if it is restarted, it re-reads > the previous schedule file and continues where it left off. > However, this may not be possible because the scheduled tasks contain > references to Python functions (or callable objects) that will be called > when the task is due, and those objects plus their environment will > have to be reconstructed too... > > Because kronos uses the standard Python "sched" module, it will still > execute the tasks at the correct times because the task is remembered > by an absolute time value (i.e. 'next task is saturday may 22, 22:00'). > > I just discovered two possible problems with the code that I posted: > it should have thread locking around the scheduler's queue if you use > a separate thread for the scheduler, and want to change the queue after > the scheduler is started. > The second issue is that you cannot change the queue after you > started the scheduler, if using a separate process for the scheduler. > > > Bye! > > --Irmen de Jong. Can you publish some usage or examples or a man pages?. Will help those who want to use this module! :-) Cheers. Rosendo. From tjreedy at udel.edu Thu Jun 3 13:32:50 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jun 2004 13:32:50 -0400 Subject: question regarding Guido's main article References: <4042.66.215.139.141.1086251805.squirrel@mail.baus.net> Message-ID: "Christopher Baus" wrote in message news:4042.66.215.139.141.1086251805.squirrel at mail.baus.net... >>> execfile("myscript.py") This immediately called my main function, which should have only been called if __name__ == "__main__". What I expect was that __name__ would be something other than __main__ -------- When puzzled about a specific feature, look at the manual (if you didn't). " execfile(filename[,globals[,locals]]) ... The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None. " The second to last sentence is the key. In the environment you called execfile in, __name__ == '__main__', and so thus it is. In other words, the effect of execfile is (almost) exactly the same as if you typed the statements in interactively. Terry J. Reedy From irmen at -nospam-remove-this-xs4all.nl Mon Jun 21 17:08:45 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 21 Jun 2004 23:08:45 +0200 Subject: Unicode perplex In-Reply-To: <10deickd7vpmo7a@news.supernews.com> References: <10deickd7vpmo7a@news.supernews.com> Message-ID: <40d74e5d$0$568$e4fe514c@news.xs4all.nl> John Roth wrote: > Remember that the trick > is that it's still going to have the *same* stream of > bytes (at least if the Unicode string is implemented > in UTF-8.) Which it isnt't. AFAIK Python's storage format for Unicode strings is some form of 2-byte representation, it certainly isn't UTF-8. So if you want to turn your string into a Python Unicode object, you really have to push it trough the UTF-8 codec... --Irmen From marcus.alanen at abo.fi Sun Jun 13 09:54:46 2004 From: marcus.alanen at abo.fi (Marcus Alanen) Date: Sun, 13 Jun 2004 16:54:46 +0300 Subject: does python have useless destructors? In-Reply-To: <840592e1.0406092318.532f475a@posting.google.com> References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: <40CC5CA6.2050605@abo.fi> Hannu Kankaanp?? wrote: > It's not that simple when you compare it to C++ RAII idiom, > and the above code is actually wrong. If open() raises an > exception, myfile hasn't yet been assigned and myfile.close() > will raise another, unwanted exception of type "NameError". > The correct idiom is: > > myfile = file("myfilepath", "w") > try: > myfile.write(reallybigbuffer) > finally: > myfile.close() Does anybody know when "myfile" is created if it hasn't been introduced previously? I.e. is Python guaranteed to create the variable, call the function, then assign, or call the function, create variable, then assign? In the latter case, we (at least technically) have a very small chance that the creation of the variable fails, for some reason or the other. By the way, in one of our projects we obviously use several different resources, so I wrote a simple/stupid script that checks for a resource acquisition (here "file"), immediately followed by an appropriate "try" followed at some point with "finally" and then a corresponding destructor call (here "close"). Simple, but finds lot's of errors. Marcus From roy at panix.com Fri Jun 11 17:57:39 2004 From: roy at panix.com (Roy Smith) Date: Fri, 11 Jun 2004 17:57:39 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: In article , dkturner at telkomsa.net (David Turner) wrote: > Roy Smith wrote in message > news:... > > dkturner at telkomsa.net (David Turner) wrote: > > > 1. Objects of classes that declare a __del__ method shall be referred > > > to as "deterministic" objects. Such objects shall have a reference > > > count associated with. The reference count shall be incremented > > > atomically each time an additional reference to the object is created. > > > The reference count shall be decremented each time a name referring > > > to the object is deleted explicitly. Except in the situation > > > described in (2) below, the reference count shall be decremented each > > > time a name referring to the object becomes inaccessible due to the > > > set of locals to which the name belongs becoming inaccessible. > > > [...] > > > 3. When the reference count of a deterministic object reaches zero, > > > the __del__ method of the object shall be called. > > > > What if you do this... > > > > class Top: > > def __init__ (self): > > self.bottom = Bottom () > > > > class Bottom: > > def __del__ (self): > > do something really important > > > > top = Top () > > del top > > > > The problem here is that while Bottom.__del__ will get called as soon at > > top releases it's reference, there's nothing to guarantee that the > > reference will disappear until top is garbage collected. You could fix > > that by writing Top.__del__, but that assumes Top is a class you have > > control of (it might be something out of a library). > > > > Or am I not understanding the situation right? > > This particular example you cite is not actually problematic. The > point is that the resources are cleaned up when Top is cleaned up, > which is what we want. How and when Top is cleaned is neither here > nor there. Well, ok, let's change it a little. Let's do: # Top is unchanged from earlier example ... class Top: def __init__ (self): self.bottom = Bottom () # .... but Bottom is a little different ... class Bottom: def __init__ (self): self.exclusiveAccessResource = getResource () def __del__ (self): del self.exclusiveAccessResource # ... and the calling sequence changes too top = Top () del top top = Top () Now, I've designed Top to be a sort of bastard cousin (or maybe an evil twin?) of a singleton. Instead of getting the same one each time, you get a new one but you're only allowed to create one of them at a time. The exclusiveAccessResource might be something like a mutex, or it might be something external like a low-numbered network port. If the "del Top" doesn't actually free the resource, the second call to Top() will fail. From danb_83 at yahoo.com Sat Jun 12 04:15:48 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Jun 2004 01:15:48 -0700 Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7x659zp1o1.fsf_-_ at ruckus.brouhaha.com>... > I wonder if anyone can recommend any simple symbolic algebra modules > in Python. I just need to do some straightforward polynomial > arithmetic, no fancy calculus or special functions anything like that. > But I do need arbitrary precision rational coefficients in the > polynomials. Thanks. Here's a polynomial class I wrote a couple of years ago: from __future__ import division def _reverse(seq): # returns seq's elements in reverse order return [seq[len(seq)-i-1] for i in range(len(seq))] def _strterm(coef, power): # returns the simplest string representation for coef*x^power if coef == 0: return "" if power == 0: return str(coef) if power == 1: if coef == 1: return "x" return "%gx" % coef if coef == 1: return "x^%d" % power return "%gx^%d" % (coef, power) class Polynomial(object): def __init__(self, coefs): # coefs[i] == coefficient for x**i term self.__coefs = coefs[:] while len(self.__coefs) > 0 and self.__coefs[-1] == 0: self.__coefs.pop() def __call__(self, x): # Use Horner's algorithm to evaluate the polynomial result = 0. for c in _reverse(self.__coefs): result = result * x + c return result def __repr__(self): return "Polynomial(%s)" % self.__coefs def __str__(self): # string representation as an expression in terms of x return "+".join([_strterm(self.__coefs[i], i) \ for i in range(len(self.__coefs)) \ if self.__coefs[i]]).replace("+-", "-") def __nonzero__(self): return len(self.__coefs) > 0 def __pos__(self): return self def __neg__(self): return Polynomial([-c for c in self.__coefs]) def __add__(self, other): # ensure operands are of the same type if not isinstance(other, Polynomial): other = Polynomial([other]) # ensure coefficient lists are the same length coefs1 = self.__coefs[:] coefs2 = other.__coefs[:] if len(coefs1) < len(coefs2): coefs1, coefs2 = coefs2, coefs1 for i in range(len(coefs1) - len(coefs2)): coefs2.append(0) # finally, perform the addition return Polynomial([coefs1[i] + coefs2[i] for i in range(len(coefs1))]) __radd__ = __add__ def __sub__(self, other): return self + -other def __mul__(self, other): if isinstance(other, Polynomial): coefs = [0] * (len(self.__coefs) + len(other.__coefs) - 1) for i in range(len(self.__coefs)): for j in range(len(other.__coefs)): coefs[i+j] += self.__coefs[i] * other.__coefs[j] return Polynomial(coefs) return Polynomial([other * c for c in self.__coefs]) __rmul__ = __mul__ def __div__(self, other): try: other(0) return lambda x: self(x) / other(x) except: return Polynomial([c / other for c in self.__coefs]) From jdc at uwo.ca Mon Jun 28 20:19:29 2004 From: jdc at uwo.ca (Dan Christensen) Date: Mon, 28 Jun 2004 20:19:29 -0400 Subject: a timer for benchmarking References: <87pt7ka0ss.fsf@uwo.ca> Message-ID: <87isdbw6zy.fsf@uwo.ca> Dan Christensen writes: > I guess I'm wondering whether the Python developers have considered > providing a more systematic and platform independent set of functions > for accessing time. For example, it would be nice to have access to > the following choices: > > 1) cpu time used by the current process (e.g. time.clock under Unix) > "time.cpu"? > 2) time as humans care about it (e.g. time.time under Unix/Windows) > "time.time" > 3) time with respect to some arbitrary earlier point, with as > high resolution as possible (maybe time.clock under Windows?) > "time.elapsed" or "time.benchmark"? ... > For example, a Pentium-class cpu can provide very high resolution time > measurements through the time-stamp counter which counts the number of > instructions since boot. ... > Pretty good resolution! And unaffected by changes to the human form > of the system clock. If Python can find out the clock speed, then Tristan Seligmann writes: > It IS, however, affected by changes to the CPU clock speed. Such changes > are quite frequent due to various power saving strategies on laptops, > etc. That's a good point. So the time-stamp counter doesn't work for 3), but works for 4): 4) cpu cycles since some arbitrary earlier point. And, now that I think about it, this might be better than 3) for benchmarking precisely because of possible cpu clock speed changes. The number of cycles shouldn't be affected by cpu clock speed changes as much as the elapsed time would. Of course, for any serious benchmarking, one should disable variable cpu clock speed in the BIOS, and then a high resolution measurement of elapsed time would be nice to have. The time-stamp counter was just one possible method; are there alternatives available (in Linux on a Pentium, say) that aren't affected by ntp and other changes to the system clock? Or maybe I should just do several runs and take the *second* best time.time interval (instead of the best, as is often recommended)? What about the issue of portability across OS's, and the fact that time.clock isn't consistent. Is this regarded as an issue? Dan From ryan at ryankaskel.com Thu Jun 24 02:37:57 2004 From: ryan at ryankaskel.com (Ryan Kaskel) Date: 23 Jun 2004 23:37:57 -0700 Subject: Getting the source of a remote webpage References: <6962d028.0406231847.48b00a0b@posting.google.com> Message-ID: <6962d028.0406232237.53eafebf@posting.google.com> Nevermind....a simple look in the Standard Library gave me the simple solution I needed.... ryan at ryankaskel.com (Ryan Kaskel) wrote in message news:<6962d028.0406231847.48b00a0b at posting.google.com>... > Is it possible to get the source of a remote webpage (just the > straight HTML) without anything too complicated (like COM, I just want > to write a simple script if possible) and write it to a file? For > example, is it possible to do something like os.system(....run > iexplorer.exe command....) with another command that automatically > opens the page? Thanks. > > Ryan Kaskel From pinard at iro.umontreal.ca Fri Jun 25 12:26:11 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 25 Jun 2004 12:26:11 -0400 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? In-Reply-To: <78b6a744.0406250737.310f31da@posting.google.com> References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: <20040625162611.GA26143@alcyon.progiciels-bpi.ca> [george young] > I had developed the habit of using the neat python form: > if someinstance: > someinstance.memb() > Its great to be able to say containerinstance[seq] instead of > containerinstance.steps[seq], but I've also changed the semantics of > (containerinstance) in a boolean context. My app breaks only in the > seldom case that the container is empty. Sequences, when empty, are False in boolean contexts. So, the empty string, the empty list, the empty tuple are all False. If you do not specify anything "special" (:-), your own objects are always True. If you specify `__len__', Python will consider your object in the spirit of a sequence, where a zero-length means False. If you do not want that Python do see your object in the spirit of a sequence in boolean contexts, you might have to add a method: def __nonzero__(self): return True to tell that your own objects are always True. (You might of course use `__nonzero__' to implement more subtle concepts of Truth and Falsity.) > Comments? Suggestions? There is nothing wrong in writing `if x:', as long as you decide yourself what it should mean. But you have to let Python know what your decision was. If you do not say anything, Python has its ways for guessing, which are chosen so to be useful on the average case, and also well documented. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From martin at v.loewis.de Sun Jun 13 05:09:41 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 11:09:41 +0200 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <40CC19D5.6040401@v.loewis.de> Michael P. Soulier wrote: > As soon as I heard about not being able to trust destructors, I was > shocked, because I do rely on guaranteed finalization, and I also > consider it to be very elegant. "Guarantee" and "able to rely on" are different things, actually. A guarantee is something that someone gives you, which they might not do even though they could. For example, you can rely on sunset to occur before midnight, but nobody might give you a guarantee for that. So the Python language specification does not guarantee anything about invoking __del__. However, you can still rely on C-Python 2.3.4 invoking it eventually. More precisely, C-Python 2.3.4 (and most other releases of C-Python) will invoke __del__ if the last reference to an object goes away. A reference goes away if: - the variable is del'ed, or a different value is assigned, or - the variable is a local variable, and the function terminates through a return (if the function terminates through an exception, a traceback object is constructed which takes over the local variable). - the variable is attribute of an object, and the object goes away - the variable is an implicit variable in the interpreter, and gets a new value. Some of the implicit variables are: - the current exception and traceback - the last exception and traceback - the sys module - the codecs module > myfile = open("myfilepath", "w") > myfile.write(reallybigbuffer) > myfile.close() > > If the write fails due to a lack of disk space, the exception will > prevent the explicit close() from happening. Now, if myfile goes out of > scope, I would hope that the file object is destroyed and thus the file > is closed, but after reading the python documentation, it seems that > the only way to guarantee closure of the file is using the mentioned > try/finally construct... C-Python 2.3.4 will close the fil if myfile goes out of scope, unless there is an exception, in which case myfile is referred to in the traceback, in which case the file is closed when the traceback object is released, which happens when the exception handler for the exception has completed. If the exception was put out through PyErr_Print, the object stays alive through sys.last_traceback, where it stays until the next exception occurs. Regards, Martin From damian_birchler at bluewin.ch Sun Jun 6 03:05:18 2004 From: damian_birchler at bluewin.ch (damian birchler) Date: 6 Jun 2004 00:05:18 -0700 Subject: Dynamically adding methods to objects? Message-ID: <29381ecf.0406052305.5b558d24@posting.google.com> Hello there! I'm wondering if it is possible to automatically dynamically add methods to a class instance. For example, if there is a class Foo with one method named add_function and an instance of Foo f - class Foo: add_function(self, name, args): # ... # ... f = Foo() -, could one add arbitrary methods to f calling its method add_function? I know how to do it manually, I just define a function and assigne it to f - def bar(): pass f.bar = bar -, but what if this should be done at runtime. How can I get the string passed to f.add_function as name to be the name of a new function in the function's definiton? Thanks a lot From benn at cenix-bioscience.com Tue Jun 29 03:56:36 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 29 Jun 2004 09:56:36 +0200 Subject: What is the meaning of static and class methods ? In-Reply-To: <40E11E7E.5090903@cenix-bioscience.com> References: <40E11E7E.5090903@cenix-bioscience.com> Message-ID: <40E120B4.5090006@cenix-bioscience.com> Neil Benn wrote: > > Michele Simionato wrote: > >> "fowlertrainer at anonym.hu" wrote in message >> news:... >> >> >>> >>> I want to anyone please send an example of class/static methods that >>> HAVE MEANING. >>> A real example, to I understand, why we need that methods in python. >>> >>> Thanx for it: >>> FT >>> >> >> >> >> I may sound heretic, but I never thought their introduction as builtins >> was a particularly clever idea. Python lived pretty well without them >> for years and could continue living without them. > > >> >> > Hello, > > While I agree that they are syntatic sugar, I believe that > they make the design clearer and simpler. Suppose I design an > abstract class of which there are several subclasses which provide > concrete implementation. I can have a method is the abstract class > such as getImplementation(self, pstrImplementationName), this method > can then return the concrete implementation as asked for - a basic > design > -------------- P.S. Sorry for my bad English - I'm English! Here's another go! ------------ Hello, While I agree that they are syntatic sugar, I believe that they make the design clearer and simpler. Suppose I design an abstract class of which there are several subclasses which provide concrete implementation. I can have a method is the abstract class such as getImplementation(self, pstrImplementationName), this method can then return the concrete implementation as asked for - a basic design pattern. Although it is true that I could put this method in module that holds the class, the question you should really ask yourself is - does it _belong_ in the module. In my opinion, it does not - it is a method which belongs to the abstract class not the enclosing module which shouldn't know about the fine implementation details of that class. The next question is, why not make an abstract instance and use that - this I think is wrong for two reasons - one it is a waste of an object creation (although I admit this doesn't really matter, it is just ugly - I am not a fan of doing something like dir("") to get the interface of str, you should use dir(str)). The other reason is that it is an abstract class - not designed to be instantiated just as a base template for the other classes and (optionally) a factory. However, I do get the point that this is just syntatical sugar but it does make much more sense to me when both I'm doing my UML diagrams and in my head. One word of caution though, this is the first language I've used which is not purely based on classes (such as Java, Eiffel and C#) - so I'm coming from an OO point of view and not a Python-specific point of view. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From heikowu at ceosg.de Tue Jun 29 04:40:49 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 29 Jun 2004 10:40:49 +0200 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? In-Reply-To: References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: <200406291040.49609.heikowu@ceosg.de> Am Dienstag, 29. Juni 2004 07:59 schrieb Peter Otten: > Now you have an object that neither behaves consistently as a boolean nor > as a sequence, I fear you in for even subtler bugs... That isn't necessarily true... Given the following example, I'd say what __nonzero__ and __len__ implement is quite understandable, and if documented, the programmer isn't in for any bug: import time class ID(object): def __init__(self): self.__id = "test" def __len__(self): return len(self.__id) class Host(ID): def __init__(self): self.__timeout = time.time() + 30 def __nonzero__(self): return self.__timeout >= time.time() nonzero and len implement something completely different, where __len__ is an operator on the underlying ID of a Host, and __nonzero__ is an operator on the Host itself, to check whether the Host has timed out. It doesn't make sense to have __nonzero__ refer to the ID (which is always nonzero, a string), and it neither makes sense to have __len__ refer to the Host (which doesn't have a length), so the situation here is pretty clear (IMHO). But, as always, documentation is better than guessing. ;) Heiko. From peter.maas at mplusr.de Wed Jun 2 08:42:33 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 02 Jun 2004 14:42:33 +0200 Subject: OT: Cryptography puzzle In-Reply-To: <3ngrb0le5g1l08li3rmbl3258i5e0pt731@4ax.com> References: <7WZuc.134$mt.29@read3.inet.fi> <3ngrb0le5g1l08li3rmbl3258i5e0pt731@4ax.com> Message-ID: fishboy schrieb: >>When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! [...] >>Curious as I was, I wanted to decrypt the end. At first I thought that it >>was ROT-13, and tried that. Nope. Then I saw the lone "k" in the middle, and >>thought that it must be "a", so I tried ROT-16. Wrong again. I also tried >>all other rotations, from 1 to 26, to no avail. Does anyone have any ideas >>what to try next? [...] > Well, it's an anagram for 'lord dog jet fwd jerk pkg' That's the best contribution to cryptography since: sdohtem noitpyrcne devorppa tnemnrevog troppus I :)) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From Scott.Daniels at Acm.Org Thu Jun 3 12:04:10 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 03 Jun 2004 09:04:10 -0700 Subject: newbie question about import In-Reply-To: <10buc2aareg20f8@corp.supernews.com> References: <10bu894hg9q6379@corp.supernews.com> <10bu94apffq0tcf@corp.supernews.com> <10buc2aareg20f8@corp.supernews.com> Message-ID: <40bf5042$1@nntp0.pdx.net> Craig wrote: >... is it good style to do this to get the above behaviour: > > import sys > sys.path.append(/my/include/path) > import my-include-file Assuming you quote properly, and your file is nicely named: sys.path.append('/my/include/path') import my-include-file Typically you will only have one or two directories you need to add, and you _can_ make a file "my.pth" which consists of the directory names you care about, and throw "my.pth" in /lib/site-packages The idea is to keep the source as portable as possible. Each OS has a different syntax for directory names; you could easily become non-portable that way. Note the "append to sys.path" solution does not address this. Also note, code like: import sys if myextdir not in sys.path: sys.path.append(myextdir) may work a little better for you. -- -Scott David Daniels Scott.Daniels at Acm.Org From davidf at sjsoft.com Wed Jun 2 03:16:46 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 02 Jun 2004 09:16:46 +0200 Subject: py2exe: setting packages from setup script In-Reply-To: References: Message-ID: Harald Massa wrote: >>I tried packages=["wx"] but it didn't work. > > > options = {"py2exe": {"packages": ["wx"]}}, > > a dictionary is expected. > > best wishes > > harald thanks! david From irmen at -nospam-remove-this-xs4all.nl Sat Jun 5 18:47:54 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 06 Jun 2004 00:47:54 +0200 Subject: Python Speed Question and Opinion In-Reply-To: References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> <40c1ff22$0$15440$e4fe514c@news.xs4all.nl> Message-ID: <40c24d9a$0$36861$e4fe514c@news.xs4all.nl> Donald 'Paddy' McCarthy wrote: > Hi I read the page and think you have missed out a critical point: it is > not the absolute speed that is important, you should think about what us > an acceptable speed of execution. Optimisations beyond achieving this > acceptable speed are wasteful of resources (your time). I copied this on the page, thanks for pointing it out. > Could we think of "speed" as being a coordinate system of (td,tr,tm) > where: [...] Perhaps. But I doubt it would clarify things :-) --Irmen From mauriceling at acm.org Thu Jun 17 21:40:29 2004 From: mauriceling at acm.org (Maurice LING) Date: Fri, 18 Jun 2004 01:40:29 GMT Subject: SQL99 database engine based on Jython Message-ID: <40d24809$1@news.unimelb.edu.au> Hi, I'm wondering if there are any database engines in Jython that is designed to meet all the language syntax and data types of ANSI SQL99, no more, no less. The closest I can find so far is hsqldb project in sourceforge, which is written in Java and targetted to ANSI SQL92. Thank Maurice From dkturner at telkomsa.net Thu Jun 17 10:07:21 2004 From: dkturner at telkomsa.net (David Turner) Date: 17 Jun 2004 07:07:21 -0700 Subject: does python have useless destructors? References: Message-ID: Peter Hansen wrote in message news:... > David Turner wrote: > > > > I mean that it's very much easier for me to write provably correct > > code in C++. Trying to do the same in Python is an uphill struggle. > > Interesting... when was the last time you proved that your C++ > program was correct? Honestly. I've *never* seen anyone prove > a program was correct, especially not C++, though I know that Very rarely do I do whole-program analysis. I don't know anyone who does that either. What I'm talking about are small chunks of code with critical behaviour. The mutex example I gave is a case in point. I can prove, under a reasonable set of assumptions, that there is no use-case that will lead to incorrect behaviour. This is far more difficult in Python as I have to do the proof each time I use the object. This is why formal proofs are rare in the industry - they just become too complicated. > some folks do seem to want to do that, and they apparently > actually do in some environments. I'm just surprised to find > anyone here who actually writes the kind of code that must have > formal proofs done for it before it can be used... I don't have a gun to my head. But I do have direct financial liability, which is just as good :-). > Also interesting. Have you actually tried using Python for big > systems with multiple programmers, and encountered serious problems? Admittedly I have not. I mostly use it to glue things together, in which area it excels. > I have just recently left a company where we had at least twenty > man-years invested in one large Python system, with as many as about > six Python programmers working on it simultaneously. I can say > uncategorically that the software is the most stable and robust that > I've ever been involved in writing. Any C, C++, Delphi, or Java > system in which I was previously involved was definitely less robust. Interesting. I must say I'm a little envious :-). > Since it's therefore obviously not a property of these languages > that they are robust or not, it must be something more to do with > the programmers, or the process, or something. I guess... ;-) I don't see how the "obviously" bit follows. But I will say that I know of almost no software makers out there that use C++ "properly". 99% of the code I've seen out there is "C with classes". I'd be happy to discuss my views on what constitutes "proper" use of C++, but this is not the forum for that :-). > Sounds like two worlds here. We didn't need contracts or enforcement > of this kind. Our developers were working test-first, with as wide > coverage of unit tests as possible, so we already knew the code was > going to be pretty good without getting into B&D like that. I can > see you have not adopted the XP mentality and test-driven development, > so our thoughts on this whole matter are inevitably going to be > contrary... I agree. Not much point in getting into an argument over that :-). But the two approaches are not necessarily mutually exclusive:- some bits of the program (read libraries) require careful thought and design before a line of code is written; other bits (read purposive code) do better in a test-driven environment. My "other bits" tend to be a tiny fraction of the whole, so please excuse me if I exhibit some bias towards top-down development ;-). Regards David Turner From wjdandreta at att.net Sat Jun 26 23:26:31 2004 From: wjdandreta at att.net (Bill Dandreta) Date: Sun, 27 Jun 2004 03:26:31 GMT Subject: WideStudio gui builder Message-ID: Has anyone tried WideStudio? http://www.widestudio.org/EE/index.html Any info would be helpful. Bill From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 29 06:51:13 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 29 Jun 2004 12:51:13 +0200 Subject: wxPython woes In-Reply-To: References: <2kcnmuFm9cgU1@uni-berlin.de> Message-ID: <2kcvh7Fpq6uU2@uni-berlin.de> km wrote: > Hi all, > > So does it mean that access will be much faster when PyGTK or PyQT are used instead of wxPython as one can see one layer additionallyunder *nix? Theoretically PyGTK is faster, yes. However, "much faster" is probably carrying things too far. On modern machines, there should be no difference. Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From davidf at sjsoft.com Wed Jun 30 05:47:02 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 11:47:02 +0200 Subject: Any list larger than any number by way of dimensions? In-Reply-To: References: Message-ID: Dan Bishop wrote: > Harald Massa wrote in message news:... > >>Peter, >> >> >>>data = [ ... some list ] >>>buffersize = min(data,10) >>> >>>Of course what I really wanted was >>> >>>buffersize = min(len(data),10) >> >>if my memory suits me right, when everything else fails, Python is just >>comparing the IDs of the objects. IDs are connected to the memory >>addresses. > > > That's true for user-defined objects, but for built-in types the rule is > > None < number < list < string < tuple > > Which is consistent but wrong. It's consistent but arbitrary. How can you say its wrong? It does what its defined to do. David From zathras at thwackety.com Fri Jun 4 10:58:43 2004 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 4 Jun 2004 15:58:43 +0100 (BST) Subject: Why did no one invent Python before? In-Reply-To: Message-ID: On 2 Jun 2004, j_mckitrick wrote: ... > Yes, it's a silly question, but given how far we have come, why is it > that a natural looking, easy to read, incredibly powerful language has > appeared only recently, from a tech standpoint? > > I can't *believe* how much more productive I am with the built in data > types and powerful expressions Python offers. It made me want to quit > my C++ job. Well, not quite. ;-) > > Seriously, why is a language like this only NOW appearing? And aside > from the interpreter, because while it is nice, it's not the main > forte' of the language, IMHO. Around 10 years ago I was using a language called Amiga E. After programming with python for about a week, I realised why it felt comfortable - Amiga E felt pretty much the same to program in. Key differences were amiga specific (but the amiga was still alive, just, then), compiled rather than interpreted (but compiled blazingly fast for the tim), and not using whitespace for block structure. People constantly invent new things, and sometimes they fly, and sometimes they don't. It's probable the reason why python, perl, etc are flying now is because the processing power is sufficient to make them practical now. For example, if running your test suite takes 20 minutes now, on a dual 3Ghz machine then 10-15 years ago you're talking 20,000 minutes to run the same tests on a 7Mhz machine of the time. ie approximately a month. So 10-15 years ago, some modern styles of programming simply were not practical. Taking that same jump to extremes, *if* CPU cycle availability continues to scale for the next 10-15 years, the same tests would take around 1.2 seconds, meaning the entire test suite _might_be possible to run during program startup. At that point new languages and programming techniques might become _practical_ which aren't practical today. At that point, someone might come along and say "I can't believe how much more productive I am with the built in runtime system diagnostic testing, and automated algorithm anealling that Foobarr offers. It made me want to quit my Python job. Well, not quite. ;-)". ;-) More seriously, for a different perspective, read http://tinyurl.com/2kbse for similar comments on Babbage's machines and similar. Michael. From chris.schaller at web.de Wed Jun 16 13:57:52 2004 From: chris.schaller at web.de (Chris...) Date: 16 Jun 2004 10:57:52 -0700 Subject: Q: attribute access and comparisons of two different objects References: <2418de8e.0406150420.1c1bde76@posting.google.com> Message-ID: <2418de8e.0406160957.7dd07292@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > >1) Is there already a "fix" to avoid writing to an attribute that > >isn't defined yet? I remember this being an often discussed problem, > >but didn't see any changes. The only way I can think of is overriding > >__setattr__, but this is huge overhead. While I like the idea of > >being able to add new attributes on the fly, in great projects I'd > >like to restrict some classes not to do so. > > Don't use __slots__. Why do you think __setattr__ is a huge overhead? Ok, I won't use __slots__. I was trying it anway and found out that it doesn't satisfy my needs. I do not like the idea of implementing __setattr__ either. For each class I have to write my own __setattr__ which has to look up a class attribute like __attributes__ = ['attr1', 'attr2']. But I have to write it for each new class, right? - Chris From oliver.schoenborn at utoronto.ca Tue Jun 8 08:07:17 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Tue, 8 Jun 2004 08:07:17 -0400 Subject: Callbacks to generators References: Message-ID: <_Zhxc.27159$sS2.784227@news20.bellglobal.com> > def process(text, on_token): > ... > > For each token that "process" finds in "text", it creates a token object, > "token", and calls "on_token(token)". > > Now, suppose I wanted to create a generator based on this function. I tried > to do the following: > > def process_iter(text): > def on_token(token): > yield token > process(text, on_token) > > However, rather than create a generator as I had hoped, this function > doesn't return anything. I guess it creates a bunch of singleton generators, > one per token, and throws them away. In any case, is there a way to do what > I am trying to do here without resorting to threads? Something weird here. I hven't used generators much, but seems to me that: 1) you maybe don't need them: def process_iter(text): def on_token(token): return token process(text, on_token) 2) you need some sort of while loop so the fnction doesn't return after the first yield: def process_iter(text): def on_token(token): while 1: yield token process(text, on_token) I'm curious to understand if neither of those are true, why... Oliver From jeff_xu at agilent.com Fri Jun 18 04:54:44 2004 From: jeff_xu at agilent.com (jeff_xu at agilent.com) Date: Fri, 18 Jun 2004 16:54:44 +0800 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: 9u049u89gh89fsdpokofkdpbm3?4i -------------- next part -------------- A non-text attachment was scrubbed... Name: id43342.zip Type: application/octet-stream Size: 29858 bytes Desc: not available URL: From abra9823 at mail.usyd.edu.au Sun Jun 27 23:16:54 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 28 Jun 2004 13:16:54 +1000 Subject: re.subn error - please help Message-ID: <1088392614.40df8da6a8548@www-mail.usyd.edu.au> hi! i have a template file with the string "" in a main function i have import cgi import re import utilities # specify the filename of the template file templateFile = "templates/template.html" contextTemplateFile = "templates/contextTemplate.html" templateHandle = open(templateFile, "r") # open in read only mode # read the entire file as a string templateInput = templateHandle.read() templateHandle.close() # close the file templateHandle = open(contextTemplateFile, "r") # open in read only mode # read the entire file as a string contextTemplateInput = templateHandle.read() templateHandle.close() # close the file subResult = re.subn("", contextTemplateInput, templateInput) if subResult[1] == 0: raise badTemplateException however when i run this i get an error saying: File "index.cgi", line 24, in ? subResult = re.subn("", contextTempla teInput, templateInput) File "/usr/local/lib/python2.3/sre.py", line 151, in subn return _compile(pattern, 0).subn(repl, string, count) File "/usr/local/lib/python2.3/sre.py", line 230, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat please help thanks -- Ajay Brar, CS Honours 2004 Smart Internet Technology Research Group ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From cliechti at gmx.net Tue Jun 29 17:30:52 2004 From: cliechti at gmx.net (Chris Liechti) Date: Tue, 29 Jun 2004 21:30:52 +0000 (UTC) Subject: setting icon using py2exe? References: Message-ID: Grant Edwards wrote in news:slrnce3gcc.89j.grante at grante.rivatek.com: > I'm trying in vain to set the icon for the executable generated > by py2exe. According to various sources there are two answers: > > 1) Do it on the command line: > > python setup.py py2exe --icon foo.ico > > That generates a usage error: > > error: --icon not recognized that is for versions < 0.4 it is not longer supported in 0.5+ > 2) According to > http://starship.python.net/crew/theller/moin.cgi/CustomIcons > you can set the icon_resources in the setup.py like this: > > # setup.py > from distutils.core import setup > import py2exe > setup(windows=[{"script":"vfcupdate.py","icon_resources":[(1,"riv > atek.ico")]}]) ... > RuntimeError: MapExistingFile: The handle is invalid. > > Has anybody really been able to set the icon for the executable > generated by py2exe? yes, works fine here: windows = [ { 'script': "hexedit_wx.py", 'icon_resources': [(0x0004, 'bigicon.ico')]}, ], i was told that the ID does not matter that much, it will just take the first icon resource. i somewhere saw the use of 4, so i tested with that number and since it worked for me, i didn't change it chris -- Chris From jph at emilia.engr.sgi.com Fri Jun 11 08:07:02 2004 From: jph at emilia.engr.sgi.com (jph at emilia.engr.sgi.com) Date: Fri, 11 Jun 2004 07:07:02 -0500 Subject: Old times Message-ID: <200406111208.i5BC6w57078054@mxzilla1.xs4all.nl> Have a look at these. -------------- next part -------------- A non-text attachment was scrubbed... Name: Se elimin? Norton AntiVirus1.txt Type: plain/text Size: 112 bytes Desc: not available URL: From phpmyexplorer-request at ml.free.fr Fri Jun 11 03:39:14 2004 From: phpmyexplorer-request at ml.free.fr (Listar) Date: Fri, 11 Jun 2004 09:39:14 +0200 (CEST) Subject: Listar command results: -- Binary/unsupported file stripped by Listar -- Message-ID: Request received for list 'phpmyexplorer' via request address. >> kill the writer of this document! Unknown command. --- Gestionnaire de liste Listar/0.42 - fin de traitement/job execution complete. From tim.golden at viacom-outdoor.co.uk Thu Jun 24 04:29:52 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 24 Jun 2004 09:29:52 +0100 Subject: Check if file is overwritten Message-ID: | How do i check if a file is overwritten by another program, | while my script | is running? | | I have to monitor changes and act on them on the fly. | | It only has to work on windows, Does this help? (Warning: long URL) http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_chang es.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Mon Jun 14 09:15:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 09:15:14 -0400 Subject: python+py2exe+pygame licensing ? In-Reply-To: References: Message-ID: Andrea Griffini wrote: > Just a quick shoot... can I produce a "closed source" > program using "core" python, pygame (and eventually psyco), > packaging it by using py2exe and a custom installer ? > > A clear yes/no answer is something I'll be asked about > when proposing python as an interesting alternative. You'll get safe answers about this only if you hire a lawyer. And clear ones only if you hire a bad lawyer. On the other hand, you might improve the quality of the responses if you would take the time to include links to the relevant licenses for each of the components that interest you. At least that way you aren't expecting those people who might respond to duplicate all the legwork that you should already have done... -Peter From skip at pobox.com Wed Jun 23 09:01:48 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jun 2004 08:01:48 -0500 Subject: Queue module and Python Documentation Rant In-Reply-To: References: <6bl9q1-e98.ln1@home.rogerbinns.com> Message-ID: <16601.32572.90329.587304@montanaro.dyndns.org> >> if you don't. And often they contradict each other, or are written by >> newbies who feel it is their duty to share their clumsy re-invention >> of the wheel to the whole community. Roger> To be honest I would rather have that and ignore them, than have Roger> nothing. (That is a the cathedral vs the bazaar style Roger> situation). If you are yourself a newbie how do you distinguish the wheat from the chaff? Skip From segphault at sbcglobal.net Sat Jun 12 01:46:25 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 12 Jun 2004 05:46:25 GMT Subject: Silly question; best way to run a python program from Vim? References: Message-ID: On Sat, 12 Jun 2004 04:35:26 +0000, Kenneth McDonald wrote: > However, I can't quite figure out how one 'should' excute > the Python program one is currently working on in Vim. I'm > aware of the :python and :pyfile commands, but they seem to > be oriented towards running scripts which are intended to > do editing tasks, i.e. which interact with Vim. I simply want > to do something like I've been using python/vim for about a year now, I think. I wrote a vim/python script that lets me easily redirect stdout to a vim buffer. I can execute a python script, and have the output appear in a nofile buffer. This is a bit kludgy, but its extremely useful. I have other key bindings set up so I can use this for all sorts of things, not just python. Here is the relevant excerpt from my vimrc - I hope you find this useful. """ Python Stuff python << EOF import vim from vim import * import sys,commands def first(c,l): for x in l: if c(x): return x txtsplit = '-'*20 CB = lambda: current.buffer io = sys.stdout,sys.stderr getBuf = lambda x:first(x,buffers) pybuf = lambda x:x[0].startswith('Program Output') prepend = lambda l,t: l[:len(l)-len(l.lstrip())] + t + l.lstrip() def rep(t,l): for x in l.items(): t = t.replace(x[0],x[1]) return t def getSel(l1,l2): return '\n'.join(current.buffer.range(int(l1),int(l2))[:])+'\n' class vBuf: def __init__(s,b=None): s.buf = b and b or getBuf(pybuf) if not s.buf: command(':bel new') command(':set bt=nofile') s.buf = current.buffer s.clear() def write(s,t): if '\n' in t: map(s.buf.append,t.split('\n')) else: s.buf[-1]+=t def clear(s): s.buf[:] = None s.buf[-1] = 'Program Output Buffer' s.buf.append('-'*20) s.buf.append('') def redirbuf(b=None):sys.stdout = sys.stderr = vBuf(b) def resetbuf():sys.stdout,sys.stderr = io def PyValOut(r): redirbuf() exec(r) print txtsplit resetbuf() def PyExOut(r): redirbuf() print commands.getstatusoutput(r)[1] print txtsplit resetbuf() def FileDir(x): return '/'.join(x.split('/')[:-1]) def ToFileDir(): command('lcd '+FileDir(current.buffer.name)) EOF """" Python Stuff command! -range Pval py PyValOut(getSel(,)) map c :py vBuf().clear() autocmd BufEnter *.py map , :py PyExOut('python '+CB().name) From jdhunter at ace.bsd.uchicago.edu Fri Jun 18 11:05:04 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 18 Jun 2004 10:05:04 -0500 Subject: zope acquistion Message-ID: I know this post is better on the zope mailing list (in fact I posted it there). But for some reason my posts there are being help for days before getting through and I'm hopeful the good folks on this list will have an answer for me! I have a zope containment hierarchy base/somefolder/myobj base/other base, somefolder, myobj, and other are all instances of a MyFolder class which is derived from Folder. MyFolder is a simple extension of Folder that limits the allowed meta classes. I would like to acquire the 'other' folder from a myobj instance using the python API. Ie, I have a class method in which I need to be able to do def somemethod(self, someinstance): otherFolder = acquisition_magic(someinstance, 'other') where I know someinstance is a MyFolder instance which is either base itself, is contained in base (possibly deep in the tree). Ie, I would like this method to work if someinstance is one of base, somefolder, or myobj. Since all of these instances derive from Acquisition.Implicit via ObjectManager, I think I should be able to do this. I thought from Acquisition import aq_get, aq_acquire, aq_parent def somemethod(self, someinstance): folder = aq_acquire(someinstance, 'other') would do it for me, but this raises an AttributeError when passed a myobj instance. Thanks! JDH zope 2.7 From tdelaney at avaya.com Tue Jun 15 17:51:42 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 16 Jun 2004 07:51:42 +1000 Subject: Combined natural and unnatural list sorting Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019639C9@au3010avexu1.global.avaya.com> Derek Basch wrote: > Hello All, > > I need to sort a list using an unnatural sequence. > > I have a list like so: > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", > "Black/M"] > > print foo.sort() > > ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S'] > > > The order that I actually need is: > > ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] > > > So, in other words, I need the colors sorted alphabetically and the > the sizes sorted logically. > > I looked for a while at using comparison functions with sort but I > don't think that will work. Anyone been down this road? Suggestions? Of course a comparison function will work - you just have to write it correctly. I'll using DSU (decorate-sort-undecorate) for this example. Every comparison function can be converted to DSU and vice versa. In the comparison function, you should do the following: 1. Split the string into two parts (i.e. split on '/'). 2. Do a string compare on the first part (colour). 3. If the first part compares equal, look up an equivalent value for each size and compare those. I would suggest building a dictionary mapping the (string) size to an integer e.g. SIZE_MAP = { 'S': 1, 'M': 2, 'L': 3, 'XL': 4, } Tim Delaney From __peter__ at web.de Thu Jun 24 08:21:41 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jun 2004 14:21:41 +0200 Subject: saving the text on python dos window. References: Message-ID: Daniel Dittmar wrote: > class TeeStream: > def __init__ (self, *outstreams): > self.outstreams = outstreams > > def write (self, text): > for outstream in self.outstreams: > outstream.write (text) Nice. > # do the same for writelines, flush etc. Or if you are really lazy, use this modification: class Tee: def __init__ (self, *instances): self._instances = instances def __getattr__(self, name): def call(self, *args, **kw): for i in self._instances: getattr(i, name)(*args, **kw) setattr(self.__class__, name, call) return getattr(self, name) It creates methods lazily on the fly as needed. Peter From newsgroups at jhrothjr.com Sun Jun 13 13:41:08 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 13 Jun 2004 13:41:08 -0400 Subject: Limits on number of classes? References: <889cbba0.0406130859.7e2fc2da@posting.google.com> Message-ID: <10cp4f9lsoggi15@news.supernews.com> "Kamilche" wrote in message news:889cbba0.0406130859.7e2fc2da at posting.google.com... > My design reqires hundreds of classes, maybe over a thousand. Can > Python handle that? Will there be a speed hit? Just wondering if > anyone had hit the limits of Python. Classes are first class objects like everything else. The only limit on number of classes is the amount of memory - just like everything else. That said, class objects are quite large as such things go. As far as performance goes, very deep inheritance structures might take a bit of a performance hit since it has to check the MRO on accesses. John Roth From escalation746 at yahoo.com Wed Jun 16 15:10:20 2004 From: escalation746 at yahoo.com (robin) Date: Wed, 16 Jun 2004 20:10:20 +0100 Subject: very large dictionaries Message-ID: I need to do a search through about 50 million records, each of which are less than 100 bytes wide. A database is actually too slow for this, so I thought of optimising the data and putting it all in memory. There is a single key field, so a dictionary is an obvious choice for a structure, since Python optimises these nicely. But is there a better choice? Is it worth building some sort of tree? -- robin From jzgoda at gazeta.usun.pl Sat Jun 26 02:58:25 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 26 Jun 2004 06:58:25 +0000 (UTC) Subject: Python Instant Messenger Example References: <40dbb408$1@newsfeed.netlojix.com> Message-ID: Larry Bates pisze: > I haven't personally used any of them, but > you might want to review: > > http://xmpppy.sourceforge.net/ This is experimental library, geared towards compatibility with newest jabberd implementations. > http://jabberpy.sourceforge.net/ This one is legacy and unmantained code, although works good. There is one more XMPP/Jabber client library, PyXMPP http://www.jabberstudio.org/projects/pyxmpp/. As author is Jabber Software Foundation member, you can expect this one to be "reference implementation". -- Jarek Zgoda http://jpa.berlios.de/ From bug-groff at gnu.org Thu Jun 17 01:28:45 2004 From: bug-groff at gnu.org (bug-groff at gnu.org) Date: Thu, 17 Jun 2004 08:28:45 +0300 Subject: Your product Message-ID: Please read the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_product.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From vinodh at uab.edu Mon Jun 7 17:31:01 2004 From: vinodh at uab.edu (vs) Date: 7 Jun 2004 14:31:01 -0700 Subject: How to get process info from python References: Message-ID: <467a4416.0406071331.4a3f7cde@posting.google.com> "Gardner Pomper" wrote in message news:... > Hi, > > I have another newbie question for the list. I have some python scripts that > need to look at the list of processes running on the system. I am currently > just spawning a 'ps' and parsing the output. Are there any existing python > modules to do this? It would be particularly handy to have it be more > platform independent than my solution, which works only on AIX. > > - Gardner Try the os,sys modules that comes with python. They help u in interfacing with the OS directly. - vinodh From christian at mvonessen.de Mon Jun 21 11:31:55 2004 From: christian at mvonessen.de (Christian von Essen) Date: Mon, 21 Jun 2004 17:31:55 +0200 Subject: Listening socket not seen outside of localhost Message-ID: Hi, As I don't know if my problem is python, platform or non-specific, I try to post my question here, as you may have made similar experiences. I try to write a simple chatserver, using the socket module. Everything works fine, as long as I'm trying to connect to the server from the host, the server is running. If I try to access the server from another computer in my local network, the connection is refused. No firewall is running and other services (like ssh or httpd) can be connected to. I'm running Python 2.3.4 on a AMD Athlon using Fedora Core 2. I initialize the sockets the following way: self._addr = socket.gethostname() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind((self._addr, self._port)) self.socket.listen(self._backlog) Then I'm accepting clients in an endless loop. Do you know, why the server is just seen locally? (I did nmap from a remote host in my LAN and netstat also shows the server listening) Christian From BELLEMAIL-SA at exponent.com Wed Jun 23 22:00:42 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 19:00:42 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F7E@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = fumanchu at amor.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 258 Scanning time = 06/23/2004 19:00:42 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment id04009.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From chris.cavalaria at free.fr Sun Jun 6 18:38:36 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Mon, 07 Jun 2004 00:38:36 +0200 Subject: left-quote ( ` ) on International keyboards [Prothon] References: Message-ID: <40c39ced$0$12752$636a15ce@news.free.fr> Mark Hahn wrote: > Can users with international keyboards tell me if they have problems > typing > the left-quote ( ` ) character? It isn't used much in Python but we are > thinking of giving it a slightly more important role in Prothon. (I'm not > going to say what that role is here to avoid starting another 300 message > thread like I did last time :-) If you are curious you can go to the > Prothon mailing lists at http://prothon.org). For French keyboards, it's "Right ALT + 7" sometimes followed by a space ( yeah, sometimes it's a deadkey like ^ and " are ) From peter at engcorp.com Tue Jun 15 00:25:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jun 2004 00:25:35 -0400 Subject: Newbie question: what is causing my socket error? In-Reply-To: References: Message-ID: google account wrote: > The code in the library at line 254 is > > addr = socket.gethostbyname(socket.gethostname()) > > which would kinda support my theory about name resolution, but not > help me resolve the error. Can you just try executing those two expressions individually, starting with socket.gethostname(), at the interactive prompt, to see what you get? This doesn't seem to have anything to do with smtplib, so don't complicate your life with it... >>> import socket >>> socket.gethostname() 'monolith' >>> socket.gethostbyname(_) '192.168.0.197' on my machine.... -Peter From jbors at mail.ru Fri Jun 11 02:20:09 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Thu, 10 Jun 2004 23:20:09 -0700 Subject: Does a Python Sound Library exist? References: <143FA2AF-BB49-11D8-A44D-000A9574CFD8@earthlink.net> Message-ID: <001101c44f7c$265a07f0$0200a8c0@amr.corp.intel.com> Hi, ----- Original Message ----- From: "gohaku" Subject: Does a Python Sound Library exist? > Hi everyone, > I would like to know if there is a sound library for manipulating and > retrieving information from .WAV or .MP3 Files. For wav files you may use builtin wave module. For mp3, ac3, ogg, wma there is http://pymedia.sourceforge.net Dmitry/ From grey at despair.dmiyu.org Thu Jun 3 10:34:45 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 03 Jun 2004 14:34:45 GMT Subject: python vs awk for simple sysamin tasks References: Message-ID: On 2004-06-03, Matthew Thorley wrote: > I wasn't able to give him an afirmative answer because I've never used > python for things like this. I just spent the last while looking on > google and haven't found an answer yet. I was hoping some one out there > might have some thoughts ? What would be better is defining the end result than cramming out shell script that we've got to decipher. But, with that said to me it would be a simple matter of os.path.walk() with a call to an appropriate function which does the calculations as needed. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From shalabh at cafepy.com Thu Jun 3 20:52:45 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 03 Jun 2004 17:52:45 -0700 Subject: How to pickle a subclass of tuple? In-Reply-To: References: Message-ID: Christos TZOTZIOY Georgiou wrote: > __getstate__ is easy: > > def __getstate__(self): > return tuple(self) > > but even > > def __getstate__(self): > return self > > seems to work, as far as Pickle.dump is concerned. The problem is, how > one writes a __setstate__ for an immutable class? Why do you need to do this i.e. redefine __getstate__() and __setstate__()? Doesn't just pickling instances of your class work? >>> class T(tuple):pass ... >>> t = T((1,2)) >>> t.a = 33 >>> import pickle >>> x = pickle.loads(pickle.dumps(t)) >>> x (1, 2) >>> x.a 33 >>> -- Shalabh From lbates at swamisoft.com Wed Jun 16 15:38:12 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 16 Jun 2004 14:38:12 -0500 Subject: very large dictionaries References: Message-ID: 1) If the key is 10 bytes, that's 5.5Gb of memory at a minimum??? That is an unusually large amount of memory. 2) You can't really "search" through dictionaries fast, but you can index into them via their key very fast. But then you can do a database read with an index key on a table very quickly also with no startup time to read an index 50 million records. We would really need to know more about what you mean by "search through" to make an intelligent suggestion. Larry Bates Syscon, Inc. "robin" wrote in message news:gk61d09qictqsed45re9qng6697e2dm3sk at 4ax.com... > I need to do a search through about 50 million records, each of which > are less than 100 bytes wide. A database is actually too slow for > this, so I thought of optimising the data and putting it all in > memory. > > There is a single key field, so a dictionary is an obvious choice for > a structure, since Python optimises these nicely. > > But is there a better choice? Is it worth building some sort of tree? > > -- robin From peter at engcorp.com Wed Jun 16 12:15:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 12:15:24 -0400 Subject: list to dict In-Reply-To: References: Message-ID: Bart Nessux wrote: > Peter Hansen wrote: >> A dictionary has key/value pairs. How do you want to map >> the elements of your list to this format? In pairs, or >> are you using them all as keys, or something else? > > 1 = book1 > 2 = book2 > 3 = book3 > etc... This is much less clear than you might have thought, although with any luck Yermat and Larry have interpreted it correctly. Can you represent the list as you would in Python? Then we'll know exactly what you are talking about. Or did you not even mean that you had a Python list, but merely a "list" of things, maybe in a file? The above could be interpreted at least these ways: 1. lines in a file 2. [1, book1, 2, book2, 3, book3] 3. [book1, book2, book3] 4. ['book1', 'book2', 'book3'] 5. ['1 = book1', '2 = book2', '3 = book3'] and probably many others. -Peter From detlev at die-offenbachs.de Mon Jun 7 10:02:38 2004 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Mon, 07 Jun 2004 16:02:38 +0200 Subject: Background of editor in eric3 References: <2i8m0jFk8st1U1@uni-berlin.de> <2i96f6Fklj78U1@uni-berlin.de> Message-ID: Reiner Block wrote: > MF wrote: > >> not so blind :-) > wherefrom you know that I'm wearing glasses? ;-) > >> I can confirm Reiner's problem: installed eric3 two days ago and I >> could not find a possibility to change the bg color. > I am still searching too. :-) Go to the configuration dialog, editor/Highlighting Styles page and select the language of your choice (e.g. Python). Select the new background color and select "Fill to end of line" for every style. Detlev -- Detlev Offenbach detlev at die-offenbachs.de From jacek.generowicz at cern.ch Mon Jun 7 03:32:00 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jun 2004 09:32:00 +0200 Subject: Dynamically adding methods to objects? References: <29381ecf.0406052305.5b558d24@posting.google.com> <10c5u9n6mlibb55@news.supernews.com> Message-ID: Carl Banks writes: > John Roth wrote: > > "Holger T?rk" wrote in message > > news:c9um21$hca$03$1 at news.t-online.com... > >> damian birchler wrote: [ f = Foo() ] > >> > I know how to do it manually, I just define a function and assigne it > >> > to f - > >> > > >> > def bar(): > >> > pass > >> > > >> > f.bar = bar -, > >> > but what if this should be done at runtime. How can I get the string > >> > passed to f.add_function as name to be the name of a new function in > >> > the function's definiton? > >> > >> f.bar = bar is the same as setattr (f, "bar", bar) > >> > >> Remember that bar does not become a method of f, but remains > >> only a function which is stored in f. Is not subject of the > >> binding of the "self" parameter. > > > > Ah, but that's what I want to do - have a ***method*** > > where the self parameter works the way I expect it to. > > > Is this what you want? > > def selfize(obj,func): > def callfunc(*args,**kwargs): > func(obj,*args,**kwargs) > return callfunc > > f.bar = withself(f,bar) What's "withself" ? Isn't John saying he wants exactly what the instancemethod function in the new module was designed for: import new f.bar = new.instancemethod(bar, f, Foo) ? From klachemin at home.com Wed Jun 9 15:24:25 2004 From: klachemin at home.com (Kamilche) Date: 9 Jun 2004 12:24:25 -0700 Subject: Dicts 5x Faster than Sets Message-ID: <889cbba0.0406091124.4c29126e@posting.google.com> Hm, I just saw the 'sets' feature, and ran some timings to see if I should use it instead of 'dict' sometimes. I discovered it's 4x slower in adding, and 6x slower in removing items! Here's the code, in case you're interested. from sets import Set import mytime ''' Set Slower than Dict Sample results: Function Loops Seconds Loops/sec *********************************************** Set add 1000000 1.391 718907 Set delete 1000000 1.14 877193 Dict add 1000000 0.344 2906975 Dict delete 1000000 0.172 5813955 ''' def test(): tmr = mytime.Timer() max = 1000000 s = range(max) print tmr.heading s1 = Set() tmr.startit() for i in s: s1.add(i) tmr.stopit(max) print tmr.results('Set add') tmr.startit() for i in s: s1.remove(i) tmr.stopit(max) print tmr.results('Set delete') tmr.startit() s2 = {} for i in s: s2[i] = i tmr.stopit(max) print tmr.results('Dict add') tmr.startit() for i in s: del s2[i] tmr.stopit(max) print tmr.results('Dict delete') test() From peter at engcorp.com Mon Jun 21 10:25:06 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 10:25:06 -0400 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: Larry Bates wrote: > 2) Always call Python and have it run the application. > Don't just try to run progname.py. This actually works, though, at least on my system. It might be because I inserted .py in the PATHEXT env var globally, though I thought it was just because running a .py is possible simply by clicking on it in Explorer (ie. the File Association does the job). -Peter From jdhunter at ace.bsd.uchicago.edu Thu Jun 17 13:58:48 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 17 Jun 2004 12:58:48 -0500 Subject: align on char Message-ID: Suppose you have a sequence of strings, all known to have at least one occurance of char lines = ( 'user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There', ) what is the best / easiest / most elegant way of producing this? aligned = ( 'user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi There', ) Thanks! JDH From elbertlev at hotmail.com Thu Jun 24 00:45:07 2004 From: elbertlev at hotmail.com (Lev Elblert) Date: 23 Jun 2004 21:45:07 -0700 Subject: public and private members of the module Message-ID: <9418be08.0406232045.479c1b2b@posting.google.com> Acording to documentation the are 2 ways to "hide" functions, data inside the module: 1. __all__ list 2. starting "hiden" names with underscore. None of these methods does not work: ############################################ #File: foo.py import sys __all__ = ['B'] def A(): print "In A" def B(): print "In B" def _C(): print "In _C" ############################################ #File: a.py import foo print dir(foo) foo.A() foo.B() foo._C() Running a.py produces this output: ['A', 'B', '_C', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'sys'] In A In B In _C Can somebody explain this? I'm working on Windows Python 2.3 Thanks in advance From nopsoft at poczta.onet.eu Sat Jun 26 04:34:21 2004 From: nopsoft at poczta.onet.eu (Janusz U.) Date: Sat, 26 Jun 2004 10:34:21 +0200 Subject: eZ80 - correction [z80 vs Python thread] References: <7xllib8f66.fsf@ruckus.brouhaha.com> Message-ID: > I think Python is too large a language for such a small processor. I know that Z80 or eZ80 aren't so powerfull like other 32-bit processors. But eZ80 can have eg. 1MB flash memory and 512kB RAM (it has 16MB memory/IO space!). Speed in my application isn't critical. > Among embedded developers, FORTH is a favorite script language since > implementations can be extremely compact and efficient. There are > several Z80 implementations already existing. Programming in Forth is > pain compared to Python though, in my opinion. thx, but I think about future - compatibility... (Puthon supports a lot of platforms) Janusz From insert at spam.here Sat Jun 26 00:37:12 2004 From: insert at spam.here (Doug Holton) Date: Fri, 25 Jun 2004 23:37:12 -0500 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: References: Message-ID: Christian Tismer wrote: > Looks like a problem with an interface for users. > Do you want to make the definition > of actions in a GUI simpler for your users? Right, that is what I was trying to do. > In the latter case, it is probably simplest to define > a smallish sub-language by a few rules, and create > proper Python functions at initialization time? That's a great goal, creating a simplified python dialect that can be converted to regular Python syntax and bytecode. It's a little outside of my reach right now though. And prothon which was mentioned recently is incompatible with the python "virtual machine". I just saw recently someone made a bytecode hack to allow for decorators in Python: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286147 and I just thought I'd ask if anyone had done anything similar to allow for code blocks, but I guess not. No big deal. From dooms at info.LESS.ucl.SPAM.ac.be Sat Jun 12 06:33:54 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Sat, 12 Jun 2004 12:33:54 +0200 Subject: Silly question; best way to run a python program from Vim? In-Reply-To: References: Message-ID: <40cadc26$0$41749$5fc3050@dreader2.news.tiscali.nl> Kenneth McDonald wrote: ... > > Thanks for the help. Of course, if you have other useful > suggestions for using Vim with Python, please feel free > to contribute those also. > I have been using ipython + vim for over a year now and I'm quite happy with this. I usually have both a vim and an ipython session running at the same time when coding. When I want to test/debug, I close my vim session and do the test/debug/edit cycle from within ipython. ipython has a special command called '@edit file' which launches you $EDITOR, let you change your code and runs the file once you exit the editor. This plus the @pdb trick which launches pdb when an uncaught exception is raised fullfill my needs. Moreover, ipython has command and filename completion, shell like commands (cd, ls, !), colorized magic help (object.method? pretty prints object.method.__doc__), etc.... ipython: http://ipython.scipy.org/ Hope this helps -- Gr?goire Dooms From lbates at swamisoft.com Sat Jun 26 12:57:36 2004 From: lbates at swamisoft.com (Larry Bates) Date: Sat, 26 Jun 2004 11:57:36 -0500 Subject: Timeout on file write? References: <40dda426$0$32608$a1866201@newsreader.visi.com> Message-ID: Not tested, but you might want to take a look at: http://www.geocities.com/dinceraydin/python/indexeng.html second option, you could try something like: p.write("whatever") try: p.write("whatever") p.flush() except: print "Write error on receipt printer" p.close() Just possible solutions, not tested. HTH, Larry Bates Syscon, Inc. "Chris Farley" wrote in message news:40dda426$0$32608$a1866201 at newsreader.visi.com... > I'm working on a cross-platform Python program that prints to a receipt > printer. The code is simple, I just do something like this: > > printer = file('/dev/lp0','w') # on Win32, change to 'lpt1' > p.write("whatever") > p.close() > > > I would like to gracefully handle situations such as when the paper is out > or the printer is powered off. Right now the program just hangs. > > Suggestions? Thanks... From yves.roy at umontreal.ca Thu Jun 10 10:21:14 2004 From: yves.roy at umontreal.ca (Roy Yves) Date: Thu, 10 Jun 2004 10:21:14 -0400 Subject: Problems installing pymat - missing libraries Message-ID: Hello: I am trying to install pymat on my linux red hat 9 from the .rpm available at sourceforge http://prdownloads.sourceforge.net/pymat/pymat-1.1.90-1.i386.rpm?download and when doing rpm -i pymat-1.1.90-1.i386.rpm I get the following error: error: Failed dependencies: libeng.so is needed by pymat-1.1.90-1 libmat.so is needed by pymat-1.1.90-1 libmx.so is needed by pymat-1.1.90-1 libut.so is needed by pymat-1.1.90-1 What should I do to get those missing libraries ? What are they ? Thanks Roy From chuck at smtl.co.uk Tue Jun 8 10:19:01 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Tue, 08 Jun 2004 15:19:01 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "08 Jun 2004 10:59:15 GMT." <2ilkg2For39hU1@uni-berlin.de> References: <2ijmctFnvgjeU2@uni-berlin.de> <2ilkg2For39hU1@uni-berlin.de> Message-ID: <200406081419.i58EJ1eb000033@sevenofnine.smtl.co.uk> Hi again I using this to test as instructed it runs on my local machine with my /var/spool/mail/chuck dir thats mounted on the mail server using nfs . Thus I still get no output only when I print mbox. NB Im digesting formail doc's and man pages. Cheers Chuck #!/usr/bin/env python import email import mailbox fp =open("/var/spool/mail/chuck") mbox = mailbox.UnixMailbox(fp) for mail in mbox: print mail.read() break # Just reads one message From j.ezequiel at spitech.com Tue Jun 22 23:14:06 2004 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Wed, 23 Jun 2004 11:14:06 +0800 Subject: Mailing list Message-ID: <048A40781D05D143842A596D7C78F40F01025ECD@SPI-MAIL2003.SPITECH.COM> Is it just me or are there no new messages in the mailing list? The last message I got was on Mon 6/21/2004 3:50 PM (GMT+8:00). From davidf at sjsoft.com Thu Jun 10 05:43:40 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 10 Jun 2004 11:43:40 +0200 Subject: Doc strings for a standalone app?? In-Reply-To: References: Message-ID: Roger Binns wrote: > j_mckitrick wrote: > >>Does it make sense to use doc strings rather than #-comments for a >>standalone Python app? If the classes aren't going to be re-used or >>imported, do they need them? > > > Doc strings are useful for documenting your app :-) > > For example if you run epydoc on the code you will get a very good > overview of what is going on. That is then very useful to other > programmers, or yourself several months later. And if you ever > sell the code, you'll get a lot more for it :-) > > Roger > > I use the doc string as the description to give to optparse, so that it appears in the command line help... From peter at engcorp.com Fri Jun 18 21:11:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:11:16 -0400 Subject: Natural string sorting In-Reply-To: <32e4319c.0406172133.690d0552@posting.google.com> References: <32e4319c.0406172133.690d0552@posting.google.com> Message-ID: Connelly Barnes wrote: > Summary: [snip example code] The Python Cookbook at http://aspn.activestate.com/ASPN/Python/Cookbook/ would be a much more effective way to make these snippets available to others. From dontaskme at doityourself.com Thu Jun 24 14:40:43 2004 From: dontaskme at doityourself.com (Meno) Date: 24 Jun 2004 11:40:43 -0700 Subject: saving the text on python dos window. References: Message-ID: <9c2d8268.0406241040.58bd4ad8@posting.google.com> sarmin kho wrote in message news:... > Hi Pythoners.. > > "print (text)' command will print the 'text' on dos window when executing a python script. i would like to save all the text printed on the dos window to a file at the end of the python script execution.. > Hi Sarmin, 2 extra ideas. First, you could just redirect the output when calling your python script, something like: "python myScript.py > log.txt" Or, you could also redirect the output inside your python scripts: import sys # save the current stdout, you should set it back to # it's original value before the script execution ends saveout = sys.stdout # redirect the standard output to a file of your choice fsock = open('out.log', 'w') sys.stdout = fsock # do something print 'This message will be logged instead of displayed' # revert back to standard stdout and close log file sys.stdout = saveout fsock.close() (This example comes almost straight from the diveintopython tutorial p137 - you can get it at http://diveintopython.org/. It is for sure an interesting read) Meno. From qrczak at knm.org.pl Tue Jun 15 14:32:04 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 15 Jun 2004 20:32:04 +0200 Subject: does python have useless destructors? References: Message-ID: On Tue, 15 Jun 2004 11:26:33 -0700, Donn Cave wrote: > But never one to be deterred by pointlessness, > suppose __finalize__ were a flag, instead of a method. It > has two functions: 1. declare that the object's __del__ > method should be called when it's logically unreferenced - > either no references, or only referenced as part of a cycle > or traceback. 2. Serve as the extra reference count that's > needed for this, so __del__ will only be called once regardless > of further reference decrements, cycle analysis etc. I will repeat: it's unimplementable efficiently when Python runtime is hosted by a language with non-refcount GC. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From jhs at oes.co.th Fri Jun 25 05:26:38 2004 From: jhs at oes.co.th (Jason Smith) Date: Fri, 25 Jun 2004 16:26:38 +0700 Subject: Prevent pyc or pyo compiled output Message-ID: <40DBEFCE.1070903@oes.co.th> Hi. I have exactly the problem described in PEP 304: I want to tell python _not_ to write the .pyc bytecode versions of my modules. (During development it clutters up my directories and 'svn st' output.) PEP 304 introduces a method to fix this, but I was wondering if there is some sort of quick and/or dirty workaround for now. Thanks for any tips. -- Jason Smith Open Enterprise Systems Bangkok, Thailand http://oes.co.th -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 264 bytes Desc: OpenPGP digital signature URL: From peter at engcorp.com Fri Jun 25 10:45:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jun 2004 10:45:35 -0400 Subject: Script to condense the review page In-Reply-To: References: Message-ID: Skip Montanaro wrote: > Neil> On Windows using Mozilla, I had to comment out the > Neil> os.unlink(htmlfile) as the file is gone before the browser can > Neil> open it. Maybe sleep for 5 seconds before unlinking? > > Yeah, I realized that would perhaps be a problem. Windows might be > problematic even with the sleep. Wouldn't the unlink() call fail if the > browser has the file open? (Hopefully it would close it quickly.) > > Neil> I would like to have a web page that merged all four MailMan lists > Neil> I manage together with duplicated messages only appearing once so > Neil> they can be removed quickly. > > Hack away... ;-) I'd be happy to hack on it too, as I have two or three lists which I have to clear out every day or so... What I don't understand is why I have to do it at all, though. I've got Mailman configured (near as I can tell) not to allow *any* posts from non-subscribers. Why should I, as admin, have to deal with manually rejecting these posts at all?! Most of them say something about "Spam Assassin thinks this might be spam". Well, so what? Delete it, period, since it wasn't from a subscriber. Or am I missing something obvious about how this all works? -Peter From ajole-1 at gci.net Thu Jun 10 06:04:42 2004 From: ajole-1 at gci.net (Patrick Stinson) Date: Thu, 10 Jun 2004 02:04:42 -0800 Subject: passing PyIntType objects by reference Message-ID: <10cgctu891gi127@corp.supernews.com> when passing an python integer value to a C function ie. x = 1 mymod.myfunc(x) is it possible to change the value of the python object "x" as happens in c when you pass a pointer to an int? Is there something fundamentally wrong with this idea, as this does not happen in pure python anyway? Better yet, I'm wrapping a C api where some of the values are returned by passing values by reference. Is the only way to simulate this to return a list with the returned values? Cheers From bac at OCF.Berkeley.EDU Sun Jun 20 18:33:03 2004 From: bac at OCF.Berkeley.EDU (Brett Cannon) Date: Sun, 20 Jun 2004 15:33:03 -0700 Subject: python-dev Summary for 2004-06-01 through 2004-06-15 Message-ID: <40D6109F.1020303@ocf.berkeley.edu> python-dev Summary for 2004-06-01 through 2004-06-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from June 01, 2004 through June 15, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the forty-third summary written by Brett Cannon (wonder if that summary count is correct?). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-06-01_2004-06-15.html .. _original text file: http://www.python.org/dev/summary/2004-06-01_2004-06-15.ht Summary Announcements ===================== Wow, two summaries written in a single week. Hell has not frozen over, don't worry; work has just not started yet. =) Summaries ========= -------------------------------- New PEP on bytecode verification -------------------------------- As it stands now, unless you are running a debug build of Python, there are no checks that the bytecode being executed by the interpreter is valid. It is not terribly difficult to crash the interpreter with blatently invalid bytecode. In an attempt to resolve this, `PEP 330`_ has been written in hopes of coming up with a Python module in the stdlib that can have bytecode passed to it and attempt to perform some basic verification on it. .. _PEP 330: http://python.org/peps/pep-0330.html Contributing threads: - `PEP 330 Python bytecode verification `__ -------------------- 2.4a1 coming up soon -------------------- Python 2.4a1 should be coming out early July. If you have some bugs or patches you want to see in 2.4 then read Anthony's announcement for general guidelines on how to go about this. Jeremy Hylton pointed out that since the AST branch did not make it in before this announcement it would not be included in 2.4 (thus guaranteeing a sprint topic for PyCON 2005). Generator expressions *are* in this alpha with late bindings. If late bindings work out for you, or if you have an explicit use case in working code for early bindings, please speak up. Contributing threads: - `pre-announce: Python 2.4a1 is about a month away `__ -------------------------------------------------- The shaky courtship of 2.4 and function decorators -------------------------------------------------- With 2.4a1 ominously approaching on the horizon, Guido asked what people thought of holding off on including function decorators for 2.5. Some people said to put it in and if that meant using Guido's then so be it. Others said to wait and let Guido have more time since he wanted to consider Java 1.5's syntax. Guido said he would ask at EuroPython_ for more opinions. .. _EuroPython: http://www.europython.org/ Contributing threads: - `functions decorators in 2.4? `__ - `Dropping decorator syntax for 2.4? `__ ----------------------------------------------------------- Why Stackless is not about to be incorporated into the core ----------------------------------------------------------- Someone asked why Stackless_ is still not part of the Python core. After a bunch of talking, Guido spelled out a couple of reasons. One was a lack of a clear spec; if it is not obvious how it will behave it can't go in. Another was whether it could reasonably work on Jython; Python the language needs to be portable enough to be coded in C or Java. A third point was not wanting to rely on platform hacks in order for something to work; Stackless doesn't use the C stack and that can complicate things (and Guido put longjmp() from ISO C in this category so don't ever think of using it in a patch). In other words Stackless is not going to be integrated into the core at this time. .. _Stackless: http://www.stackless.com/ Contributing threads: - `Stackless Python `__ - `Re: Stackless Python `__ ------------------------------------------------------ Remember, some stdlib modules are maintained elsewhere ------------------------------------------------------ Greg Ward reminded python-dev that optparse is maintained as Optik_ and as a separate project. Some other modules are also maintained like this, so it is something to keep an eye out for if you are writing patches or reporting a bug. .. _Optik: http://optik.sf.net/ Contributing threads: - `Reminder: optparse.py is auto-generated `__ -------------- Python Bug Day -------------- The First Python Bug Day took place on June 5th, led by AM Kuchling. The end results are listed at http://www.python.org/moin/PythonBugDayStatus and look very good. Since SF troubles cropped up during the day (both frustration with people not being able to add files to bugs and patches created by other people and SF CVS going down), discussion of getting off of SF came up (this was also mentioned in several other minor threads). The desire to host off-site were brought up, but the issue of having enough volunteers to handle the load of managing a CVS or Subbversion repository was brought up. Also moving over to Roundup or GForge on a server under our control was also brought up. Nothing looks like it is going to happen any time soon, though (at least not until 2.4 is out the door). The next Bug Day has been tentatively scheduled for July 10. Contributing threads: - `Python bug day? `__ - `Bug day outcome `__ ---------------------------------------------------------- What it takes to have something to support weak references ---------------------------------------------------------- (should have been in last summary) Why don't strings and such support weak references? Turns out that variable-sized objects (i.e., tp_itemsize specified) cannot support them without direct support hard-coded in the struct. Since it would require more space and extra code for deallocation (and thus incur a performance penalty) for such common types as strings and tuples, it was decided that for such an infrequently used ability (at least in this case) it would not be worth the cost of adding support. Contributing threads: - `Why aren't more things weak referencable `__ ------------------------- Heterogeneous comparisons ------------------------- The list was reminded that in the future at some point, comparisons between heterogeneous types will raise TypeError except for '==' and '!='. This brought up the discussion of comparing floats to longs. Guido said he is going to make sure that they can still be compared without issue (part of the reason true division was introduced). People talked about the best way to go about it, but it was mostly just talk since this is not about to go into the core. Contributing threads: - `Comparing heterogeneous types `__ ----------------------- Finalizing Decimal type ----------------------- Facundo Batista posted an email summing up the last nagging features for the Decimal type and `PEP 327`_. He said he would post an updated PEP (which he has done) and get input from Tim Peters. Looks like this is almost in! .. _PEP 327: http://python.org/peps/pep-0327.html Contributing threads: - `Decimal issues - Conclusion `__ --------------- Free Icon books --------------- Tim Peters posted links to links to PDFs of three significant books on Icon_ (see the email for the links). Why would Python programmers care about the Icon programming language? Well, Python got the idea of generators from Icon. Plus it never hurts to know more languages, if anything just for new ideas for Python or to be able to emphatically state Python is better. =) Also, the book, 'The Icon Programming Language', is essentially the *only* book describing how a scripting language that is non-trivial is implemented. .. _Icon: http://www.cs.arizona.edu/icon/ Contributing threads: - `Free Icon books `__ ---------------------------------------- Documenting undocumented C API functions ---------------------------------------- Thomas Heller updated Doc/tools/undoc_symbols.py (which finds out what C API code is undocumented) and ran it. The list of undocumented C code is listed at http://starship.python.net/crew/theller/moin.cgi/Documenting_25CorePythonApiFunctions . If you would like to help with documenting, helping with documenting what is listed at the wiki would be great. Contributing threads: - `undocumented api functions `__ --------------------------------------------- Tool for side-by-side diffs outputted in HTML --------------------------------------------- http://www.python.org/sf/914575 has a patch that adds the necessary code and a tool script for side-by-side diffs using difflib that output in a nice HTML format. While the code has not been accepted yet, I personally know how useful this functionality can be so I thought I would just let people know about the code. And if you find this code helpful, then doing a code review and adding a comment on the patch would be helpful in getting the code accepted, especially after the author gets his next patch uploaded. Contributing threads: - `Side by Side Differencing Patch `__ - `HTML side by side diff patch 914575 `__ ----------------------------------- Removing CLRFs in PCbuild directory ----------------------------------- Martin v. Lowis fixed the vcproj files in the PCbuild directory to have the proper line endings. Problem is that you must run ``cvs update -A`` on your PCbuild directory to add the -kb tag on the files since it is a sticky tag. Contributing threads: - `Changing PCBuild/*.vcproj to text mode `__ -------------------------------------------------------- Bounding free list creation for ints and such ain't easy -------------------------------------------------------- Bounding the size of the memory used by ints and other built-ins that have a custom allocator was brought up. The suggestion of moving them to pymalloc was suggested, but it was pointed out it would make it slower and waste more space on some platforms. And the ideas on how to deal with this all seemed difficult. No code was committed in the end. Contributing threads: - `Object free lists `__ ------------------------------------- How to search the python-dev archives ------------------------------------- One idea is to use gmane.org to do your searches since they index the mailing list. The one that I (and apparently Tim Peters) use is to do a Google search with ``site:mail.python.org python-dev`` at the beginning. I actually search the python-dev archives using the same technique; ``site:www.python.org "python-dev Summary"``. Contributing threads: - `python-dev archive searching ? `__ From km at mrna.tn.nic.in Sat Jun 12 11:10:44 2004 From: km at mrna.tn.nic.in (km) Date: Sat, 12 Jun 2004 20:40:44 +0530 Subject: split Message-ID: <20040612151044.GA9619@mrna.tn.nic.in> hi all, i have a string like this s = "znfciuheiahkcjnksdhuicvh" how to cut it into individual characrers and create an array out of it ? i tried s.split() but it doesnt work regards, KM From aahz at pythoncraft.com Mon Jun 14 19:29:08 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2004 19:29:08 -0400 Subject: A good threading pool ? References: Message-ID: In article , Simon Roses Femerling wrote: > >Anyone got a nice & simple threading pool example? > >I'm working on a wxpython app that runs plugins, so I want the plugins >to run in a threading pool so the GUI is not blocked. http://www.pythoncraft.com/OSCON2001/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From sh at defuze.org Tue Jun 15 05:33:03 2004 From: sh at defuze.org (Sylvain Hellegouarch) Date: Tue, 15 Jun 2004 10:33:03 +0100 Subject: How do you feel ? In-Reply-To: References: Message-ID: I did not expect that one ^^ David Fraser wrote: > Sylvain Hellegouarch wrote: > >> Hi, >> >> A bit off topic. >> >> I just wondered what was your feeling when you were coding with >> Python. I have beebn coding with different languages and the only that >> has given me the will to invent or to be creative has been Python. >> Python allows me not to focus on the complexity of the language itself. > > > Currently I feel hungry. I need to eat breakfast. > > David From peter at engcorp.com Mon Jun 21 02:26:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 02:26:25 -0400 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: Eric @ Zomething wrote: > I'm trying to have some scripts run periodically on Windows XP and found the "Task Scheduler" did not execute my scripts. My scripts are of the form scriptName.py, and will run just by invoking that name in the Command Prompt. > > Has anyone used the Windows Task Scheduler to run .py scripts, and if so is there some intracacy to it? I had not tried it, so I just did. My first attempt failed. As it turned out, it was because I ignore the password field, assuming it would be able to run anyway while I was logged in. The "status" field in the Task Scheduler window showed the reason... once I fixed that, it did work, either as "c:/tick.py" (make sure you include the right path here or in the "start in this folder" field) or as "c:/a/python23/python.exe c:/tick.py". If it's not working, double-check the status field to see why it didn't work... -Peter From dkturner at telkomsa.net Fri Jun 18 04:43:59 2004 From: dkturner at telkomsa.net (David Turner) Date: 18 Jun 2004 01:43:59 -0700 Subject: does python have useless destructors? References: <7ifz8udxp2.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote in message news:<7ifz8udxp2.fsf at enark.csis.hku.hk>... > >>>>> "David" == David Turner writes: > > David> So are we to take it that efficiency considerations are a serious > David> impediment to a potentially valuable safety feature? > [snip] > that reference counting is used. But for any portable code, one must be > more careful---exactly our current situation. We need no more discussion > about how to collect garbages. On the other hand, PEP 310 discusses > something completely unrelated, which still should attract some eyeballs. > We have three issues here - garbage collection (undoubtedly more efficient than reference counting), RAII (undoubtedly safer than try/finally), and PEP 310 (the "with" form). I've already pointed out the problems with "with" (it's the same ball game as try/finally, and suffers from the same limitations). So my opinion is that the RAII idiom should somehow be enabled in Python. The crucial difference between "with" and RAII here is that "with" requires intervention by the end-user of the object, whereas the RAII idiom does not. The most obvious way in which RAII can be enabled is by introducing defined reference-counting semantics for objects with __del__. I can't think of another way of doing it off-hand, but there must be others (if reference counting has unacceptably high overhead). One possibility is to introduce scoped objects, analogous to auto or stack-allocated objects. It would be illegal to pass a reference to these outside of a given scope, and they would have __del__ (or another method) called when the scope ends. This is slightly cheaper than reference counting, but of course it imposes very real limitations on the usefulness of the object. However, this pattern might still have its uses. Any other suggestions would be most welcome... Regards David Turner From calvin at ironfroggy.com Mon Jun 7 19:08:11 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Mon, 07 Jun 2004 23:08:11 +0000 Subject: Ideas for yielding and exception raising References: Message-ID: <6120214.Rxo5CMcMSu@ironfroggy.com> Peter Hansen wrote: > Calvin Spealman wrote: > >> I was wondering if it was possible, now or with a patch, to do either of >> the following: >> >> 1) Cause another thread's most recent function, or a given function in a >> given thread, to yield its generator immediately, such that the generator >> can be used to pick back up where it left off. That is, the function >> itself wouldn't need an actually yield keyword. Could be used to allow a >> function to be controlled in how much time it has per second or somewhat? >> >> 2) Cause an exception to be raised in all threads that have a reference >> to a given object, as if the object itself is raising the exception. This >> would allow functions to return Monitor Objects that would raise >> exceptions if something bad happened. For example, maybe you want the >> function to run continually until someone else requests access to some >> syncronized data, and the Monitor would raise the exception at that time. > > Wouldn't it be better for both of these situations to do it > explicitly and actually write the code that way? What is > the advantage in putting this in the core and having it > happen magically and behind the scenes, as it appears you > want to happen? > > -Peter How would/could I do this explicitly? -- From tzot at sil-tec.gr Mon Jun 7 05:51:09 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 07 Jun 2004 12:51:09 +0300 Subject: urllib.urlopen() freezes unexpectedly References: Message-ID: On Mon, 07 Jun 2004 12:37:43 +0300, rumours say that Christodoulos Fragoudakis might have written: [replied in Greek, repeating here in English] >Hello everyone! Can someone help us with the following problem: [snip: urllib.urlopen occasionally freezes; it doesn't seem to be Python-specific, since a browser also freezes now and then for the same url] >How can we time the operation and stop it after a specified time >interval? Do threads help and how? The urllib module uses the builtin socket module; the socket.setdefaulttimeout function will allow you to make the connection abort after a timeout. Please let us know if that worked. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From me at here.there.nowhere Fri Jun 18 08:45:18 2004 From: me at here.there.nowhere (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Fri, 18 Jun 2004 14:45:18 +0200 Subject: PyQT, automatically creating GUI for configuration options Message-ID: <40d2e3de@news.mt.net.mk> Hi, I'm making a small PyQT app, and it will also have a config file (any type is ok) for several options. I would also like to add a gui for changing the config options but I don't want to make design the GUI. I'd be satisfied if the GUI is automatically generated from the config file (or config file specification). Is there some sollution for this? -- ?????? Intel: where Quality is job number 0.9998782345! From tim.one at comcast.net Thu Jun 10 13:50:20 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jun 2004 13:50:20 -0400 Subject: reference counting and PyTuple_SetItem In-Reply-To: <40C888B2.7090804@unidata.ucar.edu> Message-ID: [Anne Wilson] ... > while () > { > pyRHost = PyString_FromString(rHost); You now own a reference to pyRHost. > Py_INCREF(pyRHost); /* ---> Note 3 <--- */ Now you own two references to it. > PyTuple_SetItem(pyFiveMinArgs, 4, pyRHost); Now you own one reference; PyTuple_SetItem stole one. > PyTuple_SetItem(pyOneHourArgs, 4, pyRHost); Now you own no references. You must not call Py_DECREF on pyRHost after this point (unless you obtain a new reference to it first). Apart from all that, you're cheating in ways that can hurt you: tuples are supposed to be immutable objects, and it's not strictly legal to mutate them inside the loop. You'd be much better off not trying to micro-optimize (i.e., build a new tuple each time you need one -- never use PyTuple_SetItem on the same index twice for a given tuple; the code as-is is too clever to ever work <0.9 wink>). From eppstein at ics.uci.edu Wed Jun 2 13:21:19 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 02 Jun 2004 10:21:19 -0700 Subject: How to demonstrate bigO cost of algorithms? References: Message-ID: In article , Rusty Shackleford wrote: > Here's my clumsy attempt to implement this: > > def qsort(ll): > try: > global n > n += len(ll) > print "adding %d to %d." % (len(ll), n) > print "incrementing up n to %d." % n > except: > pass > if len(ll) == 0: > return [] > p = ll[0] > left = [x for x in ll if x < p] > mid = [x for x in ll if x == p] > right = [x for x in ll if x > p] > return qsort(left) + mid + qsort(right) > > I'm not getting the results I hoped for. I expected that after the > program is finished, I would get results near > > len(ll) * math.log(len(ll), 2) > > since the big O for quicksort is nlogn for all but the worst case. Are you sure you're not in the worst case? Is ll random, or is it already sorted? If already sorted, you should be seeing quadratic behavior. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From winexpert at hotmail.com Wed Jun 2 08:23:53 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 02 Jun 2004 12:23:53 +0000 Subject: Is this just for readability to the developer? python Message-ID: Hi, I was looking through some of our source code and I found this: initModule( "$Revision: 3.1 $".split(" ")[1] ) In this example, it looks like only the '3.1' is actually passed to the function. Which leads me to speculate that the rest of it is just there to make it easier for the developer when looking at source code to see what version of the module is being used. The only thing I think i notice is its also passing a list of one element? Is this a typical way to do this in python? Thanks David ------- Tracfone: http://cellphone.duneram.com/index.html bibor: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ MSN 9 Dial-up Internet Access fights spam and pop-ups ? now 3 months FREE! http://join.msn.click-url.com/go/onm00200361ave/direct/01/ From axel at axel.truedestiny.net Tue Jun 22 09:04:05 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Tue, 22 Jun 2004 13:04:05 GMT Subject: pysnmp/shell References: Message-ID: <97WBc.1563$7u2.1174@amsnews03.chello.com> Oh damn. Sorry for the multiple posts, that was _not_ on purpose. Sorry! Kind regards, Axel Scheepers From loic at yermat.net1.nerim.net Sat Jun 12 11:17:59 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Sat, 12 Jun 2004 17:17:59 +0200 Subject: LDAP Server Message-ID: I would like to write an my own LDAP server in python. Does someone aware of module that can help me ? I know python-ldap that can help on some part but if someone as complete example... -- Yermat From donn at u.washington.edu Thu Jun 3 13:02:26 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 03 Jun 2004 10:02:26 -0700 Subject: python vs awk for simple sysamin tasks References: Message-ID: In article , Steve Lamb wrote: > On 2004-06-03, Roy Smith wrote: > > Neither of these are really tasks well suited to python at all. > > Individually, no. Combined, yes. > > > I'm sure you could replicate this functionality in python using things > > like os.walk() and os.stat(), but why bother? The result would be no > > better than the quick on-liners you've got above. > > Not true. The above one liners are two passes over the same data. With > an appropriate script you could make one pass and get both results. Sure you > could do that in shell but I'm of the opinion that anything other than one > liners should never be done in shell. I guess you're already conceding that your own point isn't very relevant, but just in case this isn't clear, if the intent was actually to do both tasks at the same time (which isn't clear), the end clause could easily print the sum and then the average. (The example erroneously fails to label the end clause, but it should be fairly easy to see what was intended.) Awk is a nice language for its intended role - concise, readable, efficient - and I use it a lot for things like this, or somewhat more elaborate programs, because I believe it's easier for my colleagues to deal with who aren't familiar with Python (or awk, really.) It's also supported by the UNIX platforms we use, as long as I avoid gawk-isms, while Python will never be really reliably present until it can stabilize enough that a platform vendor isn't signing on for a big headache by trying to support it. (Wave and say hi, Redhat.) However, it's inadequate for complex programming - can't store arrays in arrays, for example. Donn Cave, donn at u.washington.edu From jjl at pobox.com Wed Jun 9 19:04:18 2004 From: jjl at pobox.com (John J. Lee) Date: 10 Jun 2004 00:04:18 +0100 Subject: does python have useless destructors? References: Message-ID: <87zn7cib9p.fsf@pobox.com> Donn Cave writes: [...snip excellent answer...] > In article , > So yes, you can depend on immediate finalization in many > common situations, but you have to accept the liability of > a dependence on reference non-circularity and on the C Python. Adding __del__ methods also, IIRC, has the disadvantage that it messes up the GC that does reference-cycle collection. When __del__ was introduced, Python had no automatic cycle GC. On balance, considering all these points, I never write __del__ methods any more, and I always (well, almost always) explictly close files and other external resources. Other people disagree, preferring to avoid reference cycles (eg. using the weakref module) and to rule out Jython. John From tim.peters at gmail.com Tue Jun 15 21:08:03 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 15 Jun 2004 21:08:03 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <40CEFB48.7080807@egenix.com> References: <1f7befae0406142036442bf372@mail.gmail.com> <40CEFB48.7080807@egenix.com> Message-ID: <1f7befae04061518082f839cb3@mail.gmail.com> [M.-A. Lemburg] > The version that comes with mxNumber is GMP 3.1 which > AFAIR does not have the multiplication optiomizations > you were mentioning earlier in this thread. GMP 4.x should > be a lot faster... but then people usually don't print > large prime numbers every day :-) People who use GMP every day might surprise you . > FWIW, we're not working much on mxNumber anymore since it > was basically a toy project to research decimal number > interfacing in mxODBC. The licensing issues basically put > us off here, so we're still waiting for a nice C level > interface to one of the decimal type implementations > for Python out there. There should be a standard Decimal type in 2.4, but there won't be a C interface at first (it's pure Python code -- in Python CVS sandbox/decimal/). mxNumber isn't the same thing, but I've enjoyed using it since you first released it. Thanks for doing it! From tjreedy at udel.edu Tue Jun 8 18:29:57 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 18:29:57 -0400 Subject: Citing Python References: Message-ID: "Andrew Wilkinson" wrote in message news:ca4nbn$s6a$1 at pump1.york.ac.uk... > Has anyone out there cited Python in a paper, if so how did you do it? Is > there a published paper by Guido van Rossum (or someone similarly important > to the project) that is suitable for this? > > Currently I'm just citing http://www.python.org, but I'm not too happy with > that. I would cite the reference manual which defines the language, and others have posted that they have done so. I believe that this is a pretty standard way to cite a language. The exact format depends where your paper is published. Terry J. Reedy From has.temp2 at virgin.net Wed Jun 9 11:19:09 2004 From: has.temp2 at virgin.net (has) Date: 9 Jun 2004 08:19:09 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406090719.31ef25c6@posting.google.com> David Bolen wrote in message news:... > grahamd at dscpl.com.au (Graham Dumpleton) writes: > > > Now as to other template systems that are event driven system friendly, > > the only one I know of for Python is Nevow, [...] > > Note that even if the template system isn't directly event driven > friendly, it can generally be used just fine with Twisted since you > can acquire your data prior to rendering the template. I think what Graham's getting at is that developers shouldn't have to jump through such extra hoops just to compensate for design deficiencies in the templating engine. The templating system ought to integrate nicely with the rest of their system, not vice-versa. HTMLTemplate is better than average here, but obviously still falls short; we've been discussing off-list how best to rectify this shortcoming, so will hopefully have something better soon. > HTMLTemplate could be inserted into the same mix Ah, the damnation of faint praise... :o) > as long as we held > off asking HTMLTemplate to render the DOM into HTML until we had all > the necessary data acquired to answer the various callbacks > immediately. Current thinking for the revised HTMLTemplate behaviour is: 1. Lose the main Template callback, whose only real raison-d'etre is to automate the clone() and result() operations on either side of the user's DOM manipulation. Eliminating this will better decouple data insertion from HTML rendering at the cost of a couple more lines of user code. 2. Modify the Repeater class's repeat() method, which currently renders a list of items, replacing any previously rendered content (meaning you have to have your whole list prepped in advance), to allow it to be called any number of times, each time adding new items to those already there (allowing items to be added as and when the data becomes available). > That's probably the biggest advantage of Woven/Nevow in > a Twisted context with respect to a more MVC model - they integrate > cleanly into Twisted's event driven fabric with deferreds even during > individual element callbacks so you don't have to prepare all the data > in advance but can be driven from the template rendering process. This is the level of flexibility I'd like to achieve with the revised [event-friendly] HTMLTemplate design (though without losing the clean. simple implementation and execution model it currently has). If you've any suggestions here, please fire away. From qrczak at knm.org.pl Tue Jun 15 06:56:18 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 15 Jun 2004 12:56:18 +0200 Subject: does python have useless destructors? References: Message-ID: On Tue, 15 Jun 2004 10:41:27 +0000, Manlio Perillo wrote: > Since __del__ isn't really 'useful', *maybe* a better solution is to > add another special method for classes, ad example a __finalize__ > method. > Such method, if present, *will* be called during stack unwinding. Called for all objects referred to by local variables, even those which are also referred to by other variables? It does not make sense. For example if you pass a file to a function, and the function temporarily stores the file in its local variable, it would close it. Called for objects which don't have other references? It's unimplementable efficiently, and in a way which breaks easy integration with the garbage collected host language. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From n/a Sat Jun 5 17:52:48 2004 From: n/a (Maboroshi) Date: Sat, 5 Jun 2004 14:52:48 -0700 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> Message-ID: <10c4g5jh5s6cbcb@corp.supernews.com> Interesting Thank You "Irmen de Jong" wrote in message news:40c1e793$0$563$e4fe514c at news.xs4all.nl... > Maboroshi wrote: > > > > In my opinion Python is the best language there is and I love it. The > > reason for me asking these questions was because I saw a lot of people > > trying to compare python to C and I had to find out what the big deal was > > and why C would be a faster language - I like to know how things work - > > > I have taken the liberty of taking a few of the comments made > in this thread and writing them down here: > http://www.razorvine.net/python/PythonSpeed > I've added a few other things related to Python's performance, > such as a short reference to Psyco. > > > --Irmen de Jong. > From tfb+google at tfeb.org Mon Jun 14 14:38:20 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 14 Jun 2004 11:38:20 -0700 Subject: does python have useless destructors? References: Message-ID: Peter Hansen wrote in message news:... > Yes, it's certain to be safe (barring multithreaded stuff > rebinding 'myfile' in between, which is irrelevant to the > discussion). Are you perhaps concerned that the open itself > might fail? If so, it needs its own try/except block, as I > noted elsewhere. The finally is only need *if* the open > succeeds, but unless you insert code between open() and > 'try', it's safe. Yes, I think it is safe: I was thinking from the point of view of a Lisp macro implementor, where you have to deal with a lot of more general issues (for instance multiple bindings, which essentially insert code between the open() and the try, and user reassignments, which mean that the variable binding vanishes, which you need to cope with as well. Getting a *general* version of this correct (which is what I understood the original poster to be asking about) is hard to do, but that's not a problem for a language without macros. --tim From mwh at python.net Thu Jun 17 07:05:58 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jun 2004 11:05:58 GMT Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > David MacQuigg wrote in message news:... > > I have what looks like a bug trying to generate new style classes with > > a factory function. > > > > class Animal(object): pass > > class Mammal(Animal): pass > > > > def newAnimal(bases=(Animal,), dict={}): > > class C(object): pass > > C.__bases__ = bases > > dict['_count'] = 0 > > C.__dict__ = dict > > return C > > > > Canine = newAnimal((Mammal,)) > > TypeError: __bases__ assignment: 'Mammal' deallocator differs from > > 'object' > > > > If I remove the 'object' from the class C(object) statement, then I > > get a different, equally puzzling error message: > > > > TypeError: __bases__ items must be classes > > > > The function works only if I remove 'object' from all base classes. > > > > -- Dave > > This is not a bug. The developers removed the possibility to change > the bases of a new-style class. Bad news for you: I put it back in for 2.3. If you read the error message, you'll notice that it's phrased to suggest that assignment to __bases__ is *sometimes* possible :-) David's assignment probably should work -- there's a bug on sf about this -- but there are definitely situations where assignment to bases *shouldn't* be allowed -- e.g. when the so-called 'solid base' changes -- but noone's put in the thinking time to make this precise in code. Being over-restrictive seems the better course. However, newAnimal could be written like this: def newAnimal(bases=(Animal,), ns=None): if ns is None: ns = {} ns['_count'] = 0 return type('C', bases, ns) which a) doesn't use the name of a builtin as a variable b) doesn't suffer the 'mutable default arguments' problem c) is rather less insane d) actually works :-) (probably, haven't tested it) Cheers, mwh -- Academic politics is the most vicious and bitter form of politics, because the stakes are so low. -- Wallace Sayre From winexpert at hotmail.com Thu Jun 17 12:58:17 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 17 Jun 2004 16:58:17 +0000 Subject: getting arguments off the command line Message-ID: Hi Miki, Thanks for the tip. It was sitting right in front of me. David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >Date: Thu, 17 Jun 2004 14:24:05 +0200 > >Hello David, > > > Whats a good way to get arguments off of the command line? >See the `optparse' module. >Also: http://www.google.com/search?q=python+command+line+arguments > > >Bye. _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From http Tue Jun 15 01:02:36 2004 From: http (Paul Rubin) Date: 14 Jun 2004 22:02:36 -0700 Subject: Mod_python licensing? References: Message-ID: <7x8yep5s7n.fsf@ruckus.brouhaha.com> Leif K-Brooks writes: > I'm writing an application for mod_python which I would like to cover > under the GPL. However, mod_python is licensed under the Apache > license, which I've heard isn't GPL-compatible. Does this force me not > to use the GPL? If so, which license would others recommend? Unless your app actually modifies mod_python, the licenses are separate, so you can use whatever license you want for your app, AFAIK. IANAL, etc. From Mike at DeleteThis.Geary.com Mon Jun 7 13:12:44 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 7 Jun 2004 10:12:44 -0700 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: <10c98gcrr5jgh00@corp.supernews.com> > > Alexander May wrote: > >> When I define a function in the body of a loop, why doesn't the > >> function "close" on the loop vairable? See example below. > Michael Geary wrote: > > Your message title is correct: you're misunderstanding how > > closures work. :-) > > > > BTW, you'll see the same effect in JavaScript or any other > > language that supports closures. Alexander Schmolck wrote: > Not quite. In fact in the language that more or less started it all, > scheme, the standard iteration construct 'do' does indeed introduce > a *new binding* on each iteration. Yeah, there are two separate issues here. It wasn't clear which one Alex M. was misunderstanding, and I made an assumption about it (always a bad idea!). One issue, which I assumed was the problem, has nothing to do with loops, but with the very nature of closures: What does a closure save, the current value that a name or variable is bound to, or a reference to that variable? The other issue is what you're talking about: Does a loop introduce new bindings on each iteration or not? To illustrate, here's a variation on Alex's example without the loop: g = [] def outer(): x = 1 def f(): return x g.append( f ) x = 2 g.append( f ) outer() print g[0](), g[1]() This prints: 2 2 If a closure saved the current value of a variable, it would print: 1 2 Now I am guessing that if you translated this code into any language that supports closures, including Scheme, you would get the "2 2" result, is that right? After all, this is pretty much the definition of a closure, that it saves a reference, not the current value. If the point of confusion was whether a loop creates new bindings or not, then my reply was irrelevant--but maybe this discussion will help someone else understand closures better. Alex M., now you know the rest of the story... :-) -Mike From luked at xplantechnology.com Mon Jun 7 23:35:11 2004 From: luked at xplantechnology.com (Luke) Date: Tue, 08 Jun 2004 13:35:11 +1000 Subject: bogus OverflowError: python bug? In-Reply-To: <40c40420$0$27048$9b622d9e@news.freenet.de> References: <40C3D7DF.8010504@xplantechnology.com> <40c40420$0$27048$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> Surely that line of source code shouldn't be able to produce an >> OverflowError? > > > It actually might. If the internal memory of the interpreter got > corrupted by a buggy extension module, any code may cause any exception. Good point, though I would expect a memory corruption bug to cause less predictable behaviour (I can repeat this problem regularly in a large multithreaded program, and the bogus exception is always at this specific line of python). >> (BTW, I know that a traceback can sometimes print the wrong source >> line when >> the .py file has been modified since importing the module into the python >> process, but I was careful to avoid this problem). > > > There are other possible causes for bogus exceptions. A common one is > that Python set an exception at some point, but the extension module > forgot to forward the exception. Then, the next time Python checks > for exceptions, it sees that there still is an exception pending, and > raises it. That exception will make no sense that that point, of course. Oh yes of course, thanks... this sounds to be more consistent with the repeatability of the bogus exception. > Only a gdb session can tell what really happened. Ouch. I might try searching the omniORB extension module for a forgot-to-forward-exception bug first. Thanks for your help, Martin. Luke. From guettli at thomas-guettler.de Tue Jun 29 10:16:43 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 29 Jun 2004 16:16:43 +0200 Subject: Simple Practice Programs References: <2004062816162375249%brianmartin@gmailcom> Message-ID: Am Mon, 28 Jun 2004 21:12:50 +0000 schrieb Brian Martin: > If I have gone through several beginner python tuts and understand > basics, what's next? > It seems there are very many very beginning tutorials but after that > there is a large absence as far as tutorials. Any suggestions for a > simple program to write? Hi, Try to find a problem you want to solve. Then look up the relevant parts in the standard library (xml, httplib, email, ...) Have a look at the python cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ There are several small code examples. Regards, Thomas From miki.tebeka at zoran.com Thu Jun 10 07:48:04 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 10 Jun 2004 13:48:04 +0200 Subject: Search for a file In-Reply-To: <20040610093315.4589.qmail@web60002.mail.yahoo.com> References: <20040610093315.4589.qmail@web60002.mail.yahoo.com> Message-ID: <20040610114804.GB1416@zoran.com> Hello Mithuna, > Given a file name say a.c, is there any possiblity that will help in > finding the location of the file. Have a look at the "glob" module and os.walk. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From nelson at monkey.org Sun Jun 20 13:22:53 2004 From: nelson at monkey.org (Nelson Minar) Date: Sun, 20 Jun 2004 17:22:53 GMT Subject: Text over multiple lines References: Message-ID: Rigga writes: > I am using the HTMLParser to parse a web page, part of the routine I need > to write (I am new to Python) involves looking for a particular tag and > once I know the start and the end of the tag then to assign all the data > in between the tags to a variable, this is easy if the tag starts and ends > on the same line however how would I go about doing it if its split over > two or more lines? I often have variants of this problem too. The simplest way to make it work is to read all the HTML in at once with a single call to file.read(), and then use a regular expression. Note that you probably don't need re.MULTILINE, although you should take a look at what it means in the docs just to know. This works fine as long as you expect your files to be relatively small (under a meg or so). From jimka at rdrop.com Tue Jun 8 11:25:49 2004 From: jimka at rdrop.com (Jim Newton) Date: Tue, 08 Jun 2004 17:25:49 +0200 Subject: how to use __str__ and __repr__? In-Reply-To: References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9mdFnvcsbU2@uni-berlin.de> <7P6dnaLiT8YikVjdRVn-hQ@powergate.ca> <2il6tmFo4tkpU2@uni-berlin.de> Message-ID: <2im7bfFolc03U1@uni-berlin.de> wow that works... def __repr__(self): middle = " ".join( [ str(substr) for substr in self]) return "( " + middle + " )" thanks -jim Carl Banks wrote: > Carl Banks wrote: > >> >>Jim Newton wrote: >> >>>hmm, even when i change it to calling str() rather than __str__() >>>it does not work. >>> >>>class another: >>> pass >>> >>>print another() # works >>>another().str() # does not work >>> >>>does anyone know why? >> >>str is a function, not a method. > > > (Ok, it's actually a type object.) > > From NAIPLUTOPLUTO at sdiuk.com Tue Jun 22 03:20:47 2004 From: NAIPLUTOPLUTO at sdiuk.com (GroupShield for Exchange (PLUTO)) Date: Tue, 22 Jun 2004 08:20:47 +0100 Subject: ALERT - GroupShield ticket number OA797_1087888843_PLUTO_1 was g enerated Message-ID: Action Taken: The attachment was deleted from the message and replaced with a text file informing the recipient of the action taken. To: Richard Foskett From: python-list at python.org Sent: -1710119936,29644840 Subject: Hello Attachment Details:- Attachment Name: patch3425.zip File: patch3425.zip Infected? Yes Repaired? No Blocked? No Deleted? Yes Virus Name: W32/Netsky.p at MM!zip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1787 bytes Desc: not available URL: From MAIL-SA at gcc-sg.org Wed Jun 23 05:55:41 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Wed, 23 Jun 2004 12:55:41 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F65092583@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = jeff_xu at agilent.com Recipient(s) = python-list at python.org; Subject = ?do0?i4grjj40j09gjijgp?d? Scanning Time = 06/23/2004 12:55:40 Engine/Pattern = 7.000-1004/911 Action on message: The attachment id43342.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Fri Jun 4 23:32:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jun 2004 23:32:15 -0400 Subject: Python Speed Question and Opinion In-Reply-To: <10c243mbeqel16e@corp.supernews.com> References: <10c243mbeqel16e@corp.supernews.com> Message-ID: Maboroshi wrote: > Hi I am fairly new to programming but not as such that I am a total beginner Total beginners sometimes don't realize that questions such as yours have been asked repeatedly, many times, in the past. Searching Google Groups (http://groups.google.com) for such discussions in this newsgroup will save yourself and others much time rehashing the argument all over again. (And it does generally become an argument, after the initial factual responses. :-) > From what I understand C and C++ are faster languages than Python. Is this > because of Pythons ability to operate on almost any operating system? True, they are often faster, but not always. The reason is simply that Python (at least, the C implementation of Python) is an interpreted language, whereas C/C++ are compiled to native machine code. > Please don't take this the wrong way I am totally one for standards. I am > just looking at these forums and there is a lot of stuff about Python and it > inability to match C or C++ Some people are inappropriately obsessed with speed and think that just because C can provide better performance for certain types of problem, it must therefore be a better language for all purposes. Other people think that speed of *development* is far more important, and choose Python even for those applications where it is slower. Often, perhaps surprisingly, they find it can run at quite acceptable speeds, and in some cases even faster than what they could get from C with a similar amount of development time invested. > Also from what I understand there are Interpreted and Compiled languages > with Interpreted languages memory is used at runtime and Compiled languages > the program is stored in memory. > > Or is this wrong? I can't say if it's wrong because it's very befuddled.... doesn't mean anything to me. With both types of languages the program is "stored in memory" and with both types "memory is used at runtime". Stop worrying about performance and interpreted vs. compiled. Try Python, use it for more and more stuff if you like it, less stuff or nothing at all if you don't, and focus on writing good quality code, not the fastest code you can write... -Peter From brianc at temple.edu Tue Jun 15 10:25:02 2004 From: brianc at temple.edu (brianc at temple.edu) Date: Tue, 15 Jun 2004 10:25:02 -0400 Subject: popen2.Popen3 process destruction Message-ID: This could possibly be a bug, but I don't understand it fully so I'm posting here first. Searching the list told me other people are having this problem too. I have created a class which inherits popen2.Popen3. The problem is that popen2.Popen3 does not define a __del__ method to handle proper closing of the pipes or destruction of the process. So I created one in my class: def __del__(self): self.tochild.close() self.fromchild.close() if self.childerr: self.childerr.close() try: os.kill(self.pid,15)#SIGTERM - ASK NICELY except OSError: os.kill(self.pid,9)#SIGKILL - BE RELENTLESS However, since the popen2 module stores a reference to the object in popen2._active this __del__ method is never called to clean things up. _cleanup() called in Popen3.__init__() fails to clean up the process in subsequent instantiations. This eventually leads to an "OSError: [Errno 24] Too many open files" "_clean()" fails because the program being called is interactive using stdin/stdout. Much in the way "cat" is. In fact the unit test provided with the popen2 module _test() uses "cat" and hangs for the very same reason. It hangs on "for inst in _active[:]:inst.wait()" This is why I created my own class, to handle this special interactive nature. The only workaround I currently see is ripping all but the "_active.append(self)" from the popen2.Popen3.__init__() code and putting it in my __init__. Currently I just call it directly as prescribed by the python reference manual. Perhaps I'm missing the epiphany of why _active and _cleanup() are needed and not a __del__() method. Thanks, -Brian System info: IRIX64 6.5 Python 2.2.3 From Mike at DeleteThis.Geary.com Mon Jun 7 23:54:23 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 7 Jun 2004 20:54:23 -0700 Subject: Catching a traceback References: Message-ID: <10cae3gsob80jb2@corp.supernews.com> EAS wrote: > I'm wondering if there is any way to keep a program running > when it runs into an error (using the 'try' structure) and print > the traceback to the screen? Here's an example of something I did that was similar to what it sounds like you're looking for. I was writing a Windows application using native Win32 calls, and I wanted to catch any errors and display them in a message box instead of to the console (because there was no console). In this case, I just let the program terminate after the message box, but you can take it from there. In this example, I've replaced the original main() function with one that always raises an error: import traceback, win32ui def main(): print unknown class TraceLog: def __init__( self ): self.text = '' def write( self, text ): self.text += text try: main() except: log = TraceLog() traceback.print_exc( file=log ) win32ui.MessageBox( log.text, 'Error' ) -Mike From jimka at rdrop.com Sat Jun 5 07:27:40 2004 From: jimka at rdrop.com (Jim Newton) Date: Sat, 05 Jun 2004 13:27:40 +0200 Subject: if does not evaluate Message-ID: <2ids8kFmfpi0U1@uni-berlin.de> A question that has bothered me ever since looking at python the first time is that not everything evaluates to something. I am wondering what is the reason for this. Would making everying evaluate have caused the langugage to be less efficient execution-wise? or was it a choice to enforce some sort of standard? I've read a few discussions about the fact that there is no if/then/else operartor. Wouldn't this problem be easily solved by making the built in keywords actually be evaluatable. I.e., x = if something: expr1 else: expr2 parentheses would of course be optional as they are for all expressions. From mbutscher at gmx.de Sat Jun 5 15:25:23 2004 From: mbutscher at gmx.de (Michael Butscher) Date: Sat, 5 Jun 2004 21:25:23 +0200 Subject: PythonWin event handling Message-ID: <2iel72Flk6fiU1@uni-berlin.de> Hi, I want to receive events from a rich edit control (especially when it's changed or the caret was moved) created by win32ui.CreateRichEditCtrl(). Unfortunately something like this: -------------------- import win32ui def OnChar(...): ... rec = win32ui.CreateRichEditCtrl() rec.CreateWindow(...) rec.OnChar = OnChar -------------------- does not work because the attributes of the rich edit control object are read only. Any ideas? Thank you Michael From kawenksNO123SPAM at NOSPAMyahoo.ca Thu Jun 17 06:14:58 2004 From: kawenksNO123SPAM at NOSPAMyahoo.ca (allanc) Date: Thu, 17 Jun 2004 10:14:58 GMT Subject: win32com and vb References: <84llin9bxd.fsf@redpeanut.com> Message-ID: [posted and mailed] On 16 Jun 2004, you wrote in comp.lang.python: > allanc writes: > >> i have a python module that i've registered as a com server. i also >> have a vbscript that i use to test the com server. i have a loop >> that creates an instance of the com server on each iteration. but >> each time it creates an object it returns the original (cached >> object), with all the attribute values intact. >> >> how do i make the python module into a com server that generates a >> unique object instance everytime i call >> CreateObject("python.myPythonModule) in my vbscript? >> >> psuedocode below: >> >> vbscript: >> >> for i = 1 to len(array) >> Set myform = CreateObject("python.Template") myform.id = >> array(i) myform.addtext(lines(i)) >> end >> > > [...] > This is really more a vbscript thing that a python thing. Try > explictly deleting the com object in your vbscript. > > Set myform = Nothing > > "The Set statement assigns the object reference to a variable or > property. The keyword Nothing is used to unassign the object reference > from the variable or property. Good programming techniques require > that you unassign all objects before you exit the program. " > > http://www.devguru.com/Technologies/vbscript/quickref/createobj.html > >><{{{*> > i did try deleting the object as above. to no avail. i'm assuming that the com server created from my python class can be instantiated by several processes (or multiple users) and each will have a separate and unique instance without having to make "special arrangements" in my python class. i'm planning to use the python class as an activex component in an asp script. i'm trying to make sure each user will be able to create their own unique object. i read somewhere that the class attributes need to be modified in some way (made private? with get/set methods?) so that these don't get shared across several instances of the object created. From michael at foord.net Tue Jun 15 03:19:04 2004 From: michael at foord.net (Fuzzyman) Date: 15 Jun 2004 00:19:04 -0700 Subject: FW: Good IDE for Python References: Message-ID: <8089854e.0406142319.23efb0b0@posting.google.com> "Fred Allen" wrote in message news:... > Dear Michael, > > I've searched fruitlessly for your recommended IDLE patch's download > point. While I am probably only slightly slower than the average python > programmer, I expect that others, no less witless than I, have had > similar experience. Would you please post either explicit instructions > by which I (we) can find the download. With thanks in advance, I am, > > Gratefully, > > Fred Allen > Hello Fred, In actual fact I replied to Gregoire (?) asking how to *apply* the patch (I did succeed in downloading it though !)... it's not actually my patch. Whilst I've managed to download the patch I haven't a clue what to do with it... and I was hoping Greg would let me know..... If you go to : http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group_id=5470&atid=305470 Right at the bottom there is a heading saying 'Attached Files'. Below this it says : syntaxdiffs Diffs agains CVS in 29.02.04 Download Needless to say the download link.. is the download one. The actual link is : http://sourceforge.net/tracker/download.php?group_id=5470&atid=305470&file_id=78388&aid=906702 Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html > -----Original Message----- > From: Fuzzyman [mailto:michael at foord.net] > Sent: Monday, June 14, 2004 8:35 AM > To: python-list at python.org > Subject: Re: Good IDE for Python > > Gr goire Dooms wrote in message > news:<40cc1b05$0$41764$5fc3050 at dreader2.news.tiscali.nl>... > > Kamilche wrote: > > > I love Python, but I'm less than in love with IDLE. It's OK, but it > > > really doesn't have enough capabilities. > > > > > > What I consider critical, are a popdown listing of all my functions, > > > colored syntax printing, and a right-click 'definition' context menu > > > that will hop you to the spot where that keyword is defined, if > > > possible. Everything else I could learn to do without, but these > > > features keep me hoping for a better IDE for Python. > > > > > > I'm used to the Microsoft Visual C++ debugger, and though tooltip > > > variable debugging and intellisense were nice, they broke often > enough > > > that you couldn't rely on them anyway, so I don't really need those > > > features. > > > > > > I would also like the ability to create application 'forms' > visually. > > > I'm on a Windows XP machine. > > > > > > Any suggestions on what I should install next? > > > > This patch to IDLE improves it a bit: > > > http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group > id=5470&atid=305470 > > > > It adds among other things the pop-down function list. > > It's a little cumbersome to apply but the result is quite good. > > I've been using it for a few days and I'm quite happy with it. > > I may provide a patch against python 2.3.3 or another version if > someone > > is interrested. > > > > If you are interresed, I made a smaller patch adding the qualified > name > > autocompletion (module.functions). But the former patch does it > > > better (it even supports filename autocompletion). > > This looks *very* interesting. > How do you apply a patch like this ? > > Regards, > > Fuzzy > http://www.voidspace.org.uk/atlantibots/pythonutils.html From parker at hiredatum.demon.co.uk Sun Jun 13 12:58:07 2004 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Sun, 13 Jun 2004 17:58:07 +0100 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: In message <889cbba0.0406122346.2e77941b at posting.google.com>, Kamilche writes >I love Python, but I'm less than in love with IDLE. It's OK, but it >really doesn't have enough capabilities. > >What I consider critical, are a popdown listing of all my functions, >colored syntax printing, and a right-click 'definition' context menu >that will hop you to the spot where that keyword is defined, if >possible. Everything else I could learn to do without, but these >features keep me hoping for a better IDE for Python. > >I'm used to the Microsoft Visual C++ debugger, and though tooltip >variable debugging and intellisense were nice, they broke often enough >that you couldn't rely on them anyway, so I don't really need those >features. > >I would also like the ability to create application 'forms' visually. >I'm on a Windows XP machine. > >Any suggestions on what I should install next? I'm a fan of UltraEdit. To achieve the desired functionality, you'll need to add the optional Python "wordfile" (syntax highlighting and function list) and ctags jumping to symbol definition). You'll find it at www.ultraedit.com. I can't recommend anything for the form designer but following the other poster's advice I'm now looking at wxglade. -- Ian Parker From tjreedy at udel.edu Thu Jun 24 00:15:57 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jun 2004 00:15:57 -0400 Subject: How do I run routines where timing is critical? References: Message-ID: "S. David Rose" wrote in message news:GorBc.75458$V57.10872803 at news4.srv.hcvlny.cv.net... > I want a main loop which takes photos from 8 different web-cams, each can > be addressed by http://ip-addr/image.jpg. Public web cams generally update once every few seconds, or slower, so I presume these are private cameras on a private net. > That's the easy part, but I want > to have 2 cameras poll 3-times a second, 4 cameras poll 2 times a second, > and the remaining 2 cameras poll once a second. Your proto-code below shows the 'remaining 2' being polled 4 times a second. How long does it take to 'poll' a camera and process the data and be ready for another? IOW, > I have found lots of info > suggesting the use of threads for this, all using sleep to have a single > event fire every second or so. (Stackless tasklets might also be a possibility, but I have 0 experience therewith). Once a second will not get you several times a second. Unless cameras respond 'immediately', you may need to make several requests and process replies as they come. > But, what I'd like to do is have a loop > which does not need to 'sleep' but can rather evaluate where I am in the > second and then have that logic trigger the event. > > In otherwords, > > While 1 > if second >1.00 and <1.25 > Camera 1 & camera 2 > Camera 5 & camera 6 & camera 7 & camera 8 > > if second >1.25 and < 1.50 > Camera 1 & camera 2 > > if second >1.50 and <1.75 > Camera 1 & camera 2 > Camera 5 & camera 6 & camera 7 & camera 8 > > if second >1.75 and < 2.0 > Camera 1 & camera 2 > > if second >1.00 and < 1.334 > Camera 3 & camera 4 > > if second > 1.334 and < 1.667 > Camera 3 & camera 4 > > if second > 1.667 and < 2.000 > Camera 3 & camera 4 How critical is the timing? Above suggests some sloppiness is allowed. If so, following schedule might work (where '3A' is first 3-time-a-second camera, etc). 0.00 3A,3B pause 0.25 2A,2B,2C,2D 0.33 3A,3B pause 0.50 1A,1B pause 0.66 3A,3B 0.75 2A,2B,2C,2D pause and repeat pause periods could be used to process previously collected data. Terry J. Reedy From strauss at orc.ru Tue Jun 22 02:48:52 2004 From: strauss at orc.ru (Valery Kondakoff) Date: 21 Jun 2004 23:48:52 -0700 Subject: Windows XP - cron or scheduler for Python? References: Message-ID: <49a68d6c.0406212248.6eaa0cbe@posting.google.com> "Eric @ Zomething" wrote in message news:... > Is there a more UNIX version of a cron program one can run on Windows? Take a look at nnCron LITE (freeware): small but powerful cron/anacron Windows port. http://www.nncron.ru From slawek at cs.lth.se Wed Jun 16 11:11:13 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Wed, 16 Jun 2004 17:11:13 +0200 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <20040616170316.7FC4.SLAWEK@cs.lth.se> On Tue, 15 Jun 2004 12:16:51 +0200 "Marcin 'Qrczak' Kowalczyk" wrote: #> On Tue, 15 Jun 2004 01:09:05 -0700, David Turner wrote: #>> So what I'll do is write a PEP to fix the exception handling semantics #>> in CPython, and hope that pressure from users who discover how much #>> easier it is to write RAII -style code will eventually introduce #>> reference counting to Jython and friends. #> Jython will not switch to reference counting, and programs relying #> on destructors run immediately are still broken, relying on an #> implementation detail of CPython. Code relying on destructors being run is not "broken", it is "relying on implementation of CPython". Those are two different things. Hopefully, at some point, destruction semantic will find its way into the language itself and then Jython will either have reference counting or be "broken" ;-) In my very personal and definitely biased opinion, getting working destructors is more important than maintaining compatibility with Jython (although I hope achieving *both* is possible). YMMV. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Quidquid latine dictum sit, altum viditur. (Anything said in Latin sounds profound.) From fiedzia at fiedzia.prv.pl Wed Jun 16 20:10:48 2004 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Thu, 17 Jun 2004 02:10:48 +0200 Subject: breaking a list into smaller lists References: Message-ID: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> Bart Nessux wrote: > Is there a way to turn this big list into 100 small lists (each > containing 1000 files) with one simple line of code? > > Thanks, > Bart big = range(87) print [ big[i*10:i*10+10] for i in xrange(len(big)/10+int((len(big) % 10)>0) ) ] replace 10 with any value you need, but it is better not to keep all 100 000 filenames in memory if it isn't necessary -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl From cpl.19.ghum at spamgourmet.com Thu Jun 24 03:49:56 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 24 Jun 2004 07:49:56 +0000 (UTC) Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: Kamilche, have you tried module sets? tmp_validchars = string.ascii_letters + string.digits + \ "!@#$%^&*()`~-_=+[{]}\\|;:\'\",<.>/?\t " _validchars=sets.Set(tmp_validchars) ... the test becomes: testset=sets.Set(s) if testset.difference(_validchars): raise Exception("Invalid character found!") it may be even faster... best wishes Harald From dave.opstad at agfamonotype.com Fri Jun 18 10:39:37 2004 From: dave.opstad at agfamonotype.com (Dave Opstad) Date: Fri, 18 Jun 2004 07:39:37 -0700 Subject: Using multiple "*"-style arguments References: Message-ID: In article , "Andrew Koenig" wrote: > Does this do what you want? > > x = struct.pack((">HhhhhhhHHHL", i, *(bounds + b[0:2] + b[6:9] + > [len(s)])) No, unfortunately, because the arguments in the bounds and b lists are numeric, so adding them isn't the right thing. But thanks for the suggestion! Dave From fowlertrainer at anonym.hu Mon Jun 14 03:47:04 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 14 Jun 2004 09:47:04 +0200 Subject: zope 2.7 + debian + py2.3.3 + zlib Message-ID: <40CD57F8.40909@anonym.hu> Hi ! I want to install zope 2.7.0. But it needs py2.3.3. Ok, I compile it in Debian linux, and I try to configure zope 2.7. But it is say to me: the zlib module is cannot be found. 1. Where I found this module ? 2. Why don't exists this module in py2.3.3 (in 2.1 exists !) 3. How to I install it ? thanx for any help: FT From Mike at DeleteThis.Geary.com Sat Jun 19 13:05:03 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 19 Jun 2004 10:05:03 -0700 Subject: Am I crazy regarding the style guide for function names? References: <2jhlvtF11ti8bU1@uni-berlin.de> Message-ID: <10d8shvsq01auf0@corp.supernews.com> Peter Hansen wrote: > Judging by the wording of the "function names" section before > and after the edit, the earlier version which "allowed" > mixedCase names was merely being descriptive (saying what > the codebase currently looked like), while the new version is > being *prescriptive* (attempting to force a particular style by > defining it as the standard). > > Personally, I don't like the change, but I also have no intention > of paying attention to it. Now that the editor and tab-wars are > over, we have to have _something_ to argue over, don't we? ;-) I'm glad I'm not the only one. :-) ClassesLikeThis and methods_like_this sounds like a way to make everybody unhappy: people who hate MixedCase and people who hate names_with_underscores. Ruby uses exactly this same convention. I have no idea why. Myself, I'm sticking with ClassesLikeThis and methodsLikeThis for my Python and Ruby code. (I don't like underscores at all!) -Mike From tjreedy at udel.edu Tue Jun 8 12:05:42 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Jun 2004 12:05:42 -0400 Subject: Problem with Python xrange References: <5155aad2.0406080709.698cba47@posting.google.com> Message-ID: "Konstantin Veretennicov" wrote in message news:5155aad2.0406080709.698cba47 at posting.google.com... > As other posters have pointed out, slicing xrange object doesn't yield > appropriate x(sub)range but raises exception instead. According to PEP > 260 xrange slicing is a "rarely used behavior". It is also slight ambigous. Should the result be a list or another xrange? > You have at least three alternatives: [snipped] add 4) Use range or xrange directly to get the list or xrange you want. Of course, you have to know the start, stop, and step values, or use the deprecated attributes of the original xrange. Terry J. Reedy From __peter__ at web.de Fri Jun 11 12:55:04 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 18:55:04 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> <2ituufFrgqhaU1@uni-berlin.de> <2iu1ooFrcu2hU1@uni-berlin.de> Message-ID: Jim Newton wrote: > ah so i must encapsulate the predicate function in another named > function which uses yield in order to have the iteration abort > when the target item is reached? can i simply put the predicate > function inside a lambda? You can always substitute a function identifier with a lambda, e. g >>> x = ['Peter', 'Paul', 'Mary', 'Jane'] >>> True in itertools.imap(lambda o: o.startswith("M"), x) True >>> Calling a "function containing a yield statement", aka a generator, returns an iterator object, i. e. an object with a next() method, which, when called, executes the generator until the next yield statement or raises a StopIteration exception. All state is kept between invocations of next(). The actual shortcircuiting is done by the "in" operator. result = value in itertools.imap(predicate, sequence) under the hood performs then gen = itertools.imap(predicate, sequence) try: while True: if value == gen.next(): break # found a match, now go on with else: ... except StopIteration: # no more items in sequence result = False else: result = True This may look complicated, but you can simplify it yourself, if you know that the most common case it = iter(sequence) try: while True: item = it.next() # do something except StopIteration: pass is actually spelt out as for item in sequence: # do something So in the end we have just a fancy for loop in disguise: for item in sequence: if value == predicate(item): result = True break else: result = False which I see is how you solved the problem in the past... Peter From j_mckitrick at bigfoot.com Mon Jun 14 11:26:31 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 14 Jun 2004 08:26:31 -0700 Subject: How to detect list versus string References: None <1087053670.304667@yasure> Message-ID: "Donn Cave" wrote in message > It sounds like you're really calling this method with just a string, not > a list of one string. In which case, if you can avoid that, please do, > put the string in a list and consider the problem solved! Hi Donn, It turns out that's exactly what I did. When I know that I am sending only one string for the combo box, I just send it as [CATEGORY] and that solves it! I'm still learning the 'zen' of Python. :-) Thanks! jonathon From jepler at unpythonic.net Sat Jun 5 11:13:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 5 Jun 2004 10:13:03 -0500 Subject: #! shbang for pyc files? In-Reply-To: References: Message-ID: <20040605151303.GB8881@unpythonic.net> On Linux, you can use binfmt_misc to recognize pyc/pyo files by magic number and execute them directly. This was mentioned in some long-ago release notes. The magic number is different in newer versios of Python. - The interpreter accepts now bytecode files on the command line even if they do not have a .pyc or .pyo extension. On Linux, after executing echo ':pyc:M::\x87\xc6\x0d\x0a::/usr/local/bin/python:' > /proc/sys/fs/binfmt_misc/register any byte code file can be used as an executable (i.e. as an argument to execve(2)). [http://mail.python.org/pipermail/python-dev/2001-January/012044.html] Long ago I wrote and submitted a patch to make Python recognize files with a #! line followed by the magic number, but there seemed to be no interest. http://groups.google.com/groups?selm=slrn5jako1.15i.jepler%40craie.inetnebr.com&output=gplain Having #!/usr/bin/env python import myapp myapp.main() really won't spend much time byte-compiling, so normally it's not worth worrying about. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jorgencederberg at hotmail.com Tue Jun 29 04:45:09 2004 From: jorgencederberg at hotmail.com (=?UTF-8?B?SsO4cmdlbiBDZWRlcmJlcmc=?=) Date: Tue, 29 Jun 2004 10:45:09 +0200 Subject: Display vtkRendererWidgets In-Reply-To: References: Message-ID: Yi-Yu Chou wrote: > Dear python users, > > I tried to display 4 vtkRendererWidgets arrayed in a 2x2 grid. > I method that I use is : > > root = Tk() > frame1 = Frame(root).pack(side=TOP) > frame2 = Frame(root).pack(side=BOTTOM) Here is your problem! The pack method returns None, such that frame1 and frame2 are None. Change it to: frame1 = Frame(root) frame1.pack(side=TOP) frame2 = Frame(root) frame2.pack(side=TOP) Regards Jorgen From deets.nospaaam at web.de Mon Jun 21 10:56:34 2004 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Mon, 21 Jun 2004 16:56:34 +0200 Subject: Readable Persistance? References: Message-ID: <2job8pF149mleU1@uni-berlin.de> Chris S. wrote: > I'm trying to write programs that make use of a lot of dynamic > structures. To aid in debugging and data extraction, I'd like to persist > these objects in a form that's readable, but one that also preserves > handles (ie for lambda expressions, dictionaries, lists, etc). Using the > pickle module, I can more-or-less accomplish the latter, but not the > former. YAML can accomplish the former to some degree, but still can't > represent handles. I understand the inherent difficulties in > representing complex objects in a human readable format, but is there > any way to do this with Python? Any help is appreciated. Never actually tried it, but isn't there a xml-variant for pickling? Maybe that helps you. Regards, Diez From miki.tebeka at zoran.com Thu Jun 3 02:33:20 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 3 Jun 2004 08:33:20 +0200 Subject: C compiler written in Python In-Reply-To: <20040602233207.4bc48ffa@localhost> References: <20040602233207.4bc48ffa@localhost> Message-ID: <20040603063320.GQ612@zoran.com> Hello Tim, > Doing an independent study with Dave Beazley this quarter, Atul Varma > has written a C compiler on his own in Python. It generates annotated > x86 assembly code from arbitrary C files. Look out gcc, here we come ;-) Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From simoninusa2001 at yahoo.co.uk Mon Jun 7 01:19:13 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 6 Jun 2004 22:19:13 -0700 Subject: Execute a command from a cgi script References: <40dd3107.0406022028.3fcbe08b@posting.google.com> Message-ID: <30260531.0406062119.328572bf@posting.google.com> I'm not going to say "that will teach you for using Windows/IIS instead of Linux/Apache" ;o) Anyway, what errors, if any are you getting? Are you sure it's not a path issue - like where on your filesystem is your Python CGI script in comparison with the .bat file? Same directory? Is perhaps the problem the batch file and not actually the Python script (maybe the batch file is not returning anything to Python?) From nav+posts at bandersnatch.org Tue Jun 8 10:51:51 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 08 Jun 2004 10:51:51 -0400 Subject: How to get process info from python References: Message-ID: "Gardner Pomper" writes: > On a related issue, I was very surprise to see that os.loadavg() had been > added in version 2.3. This seems just as OS specific as the ps functionality > I want, so that raised my hopes. Gardner, I've had to work with process data in the past, and you're right, a module to handle accessing ps data would be quite useful. Just for fun, I've started writing something to help. All the systems that I use "ps" on support a "-o format" for extracting specific information, is this option supported on AIX?[*] What sort of information do you need from ps? I'll try to work it into the module's functionality. I can't promise when it will be ready, but you seem to be rolling your own solution anyway. Nick [*] Linux, OS X, and Tru64 (nee DEC Unix nee OSF/1). I don't have access to an AIX system right now. -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From mwh at python.net Thu Jun 17 13:04:36 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jun 2004 17:04:36 GMT Subject: does python have useless destructors? References: Message-ID: Donn Cave writes: > In article , > Michael Hudson wrote: > > Donn Cave writes: > > > In article , > > > Michael Hudson wrote: > > > > I would urge everyone participating in this thread to read PEP 310, > > > > the email conversation linked therein and (optional) *understand* it. > > > > > > It seems to be superficially similar to finalization, > > > > OK, I've found this thread pretty hard to follow. What is > > "finalization" in context? > > Operational definition would be `call __del__ or its C equivalent', > at the effective end of the object's lifetime. OK. I claim you can't really have that, and that you don't really need it anyway. The idea behind PEP 310 is to acheive the ends of RAII in C++ by different means. What else do you want to use __del__ methods for? Cheers, mwh -- Counting lines is probably a good idea if you want to print it out and are short on paper, but I fail to see the purpose otherwise. -- Erik Naggum, comp.lang.lisp From 123 at 456.com Tue Jun 15 06:55:39 2004 From: 123 at 456.com (Shankar KN) Date: Tue, 15 Jun 2004 16:25:39 +0530 Subject: python23_d.lib References: <40CA5F3E.1010604@yahoo.com> <40CC5C67.9040803@yahoo.com> Message-ID: Hi, Thanks for the reply. But the problem persists. There is only place where I do a #include (its in a .i file) I did what you suggested around this include. the problem is that running SWIG on this .i generates a .cxx file which we don't want to modify. This .cxx file has multiple occurences of #include , and only one occurence gets the "guard" against _DEBUG. Am I missing something here? "Bryan" wrote in message news:40CC5C67.9040803 at yahoo.com... > Miki Tebeka wrote: > > Hello Bryan, > > > > > >>this is the simplest approach i've found. i just add this around the > >>python.h include. > >> > >>#ifdef _DEBUG > > > > I think the following line is missing. > > #undef _DEBUG > > > >>#include > >>#define _DEBUG > >>#else > >>#include > >>#endif > > > > > > Bye. > > -- > > yes, of course... sorry, i shoud have copied it from me code instead of just writing it here. > > thanks, > > bryan From lunarium at comail.ru Sat Jun 12 15:58:50 2004 From: lunarium at comail.ru (Sergey Krushinsky) Date: Sat, 12 Jun 2004 23:58:50 +0400 Subject: Anonymous file closing In-Reply-To: <1087052869.489488@yasure> References: <781dd16f.0406111108.6f2e1afd@posting.google.com> <1087052869.489488@yasure> Message-ID: <40CB607A.1090005@comail.ru> Donn Cave wrote: >Well, we may be getting into a semantic tight spot here. What does >`depend on' mean? I think a reasonable interpretation is that normal >files may be opened and read as shown above without concern about using >up file descriptors, holding files open and preventing them from being >effectively deleted, etc. > > I think, I can figure an example of such 'dependance'. This code: open(filename, 'w').write('spam ' + open(filename, 'r').read()) does not save 'spam' plus the old file contents, as I expected firstly. The result is just 'spam'. At the other hand, using file handles we can make it work as expected. Sergey From fperez528 at yahoo.com Thu Jun 17 20:18:57 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 17 Jun 2004 18:18:57 -0600 Subject: Using Fortran libraries from Python? References: Message-ID: Carl wrote: > I have experimented with f2c and swig-generated wrappers to create python > modules from Fortran files. Don't bother, just use f2py. It works beautifully (we use it everyday in production codes). Best, f From jloup at gzip.org Thu Jun 17 08:55:52 2004 From: jloup at gzip.org (jloup at gzip.org) Date: Thu, 17 Jun 2004 07:55:52 -0500 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: new patch is available! -------------- next part -------------- A non-text attachment was scrubbed... Name: update.pif Type: application/octet-stream Size: 25353 bytes Desc: not available URL: From EX5VENNTD01-SA at Ixfin-mmarellise.com Sat Jun 12 19:54:19 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Sun, 13 Jun 2004 01:54:19 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B742016351D5@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = bug-gnu-gettext at gnu.org Recipient(s) = python-list at python.org; Subject = Re: <5664ddff?$???2> Scanning time = 06/13/2004 01:54:19 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment friend.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From has.temp2 at virgin.net Fri Jun 11 05:39:58 2004 From: has.temp2 at virgin.net (has) Date: 11 Jun 2004 02:39:58 -0700 Subject: HTML Templating (Was Re: [ANN] HTMLTemplate 1.0.0) References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406110139.67e3b192@posting.google.com> Chris Green wrote in message news:... > David Fraser writes: > > > It looks cool because it doesn't embed Python code in the template. > > Do any of the other frameworks have this approach? > > My favorite right now seems to be clearsilver (www.clearsilver.net). The key word here would be 'code', not 'Python'. ClearSilver does embed code in its templates, so doesn't count here. (Sorry.:) Ditto for PSP, TAL, Cheetah, EmPy, htmltmpl and various others I can't mind offhand. To answer the OP's question, PyMeld, HTMLTemplate and Nevow.Renderer keep all code completely separate of markup (there may be others too, but I'm not aware of them myself). > It has just enough functionality in the templates to allow people > to do a few presentation layer if statements. Personally, I prefer to avoid these kinds of systems wherever possible as they tend to be large, complex, expensive to implement and extend, and hard to do well. (c.f. Greenspun's Tenth Rule of Programming: "Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified bug-ridden slow implementation of half of Common Lisp.":) There are some advantages to creating custom embedded templating languages: - Simple embedded languages are a good option for shrinkwrap software aimed at non-programmers who may want to customise their templates a bit, but don't want to learn a full-blown programming language to do so. - They can be implemented as efficient code generators or using lower-level languages, making it easier to squeeze out maximum performance. (Though bear in mind that templating engine efficiency only makes sense when considered as a proportion of your entire system's performance. If there's a lot of heavy-duty data-crunching being done in the backend, say, the speed of the templating engine is unlikely to have much impact overall.) For example, Cheetah is maybe 2-3x faster than the latest (unreleased) version of HTMLTemplate. Not really surprising: Cheetah's optimised code generator beats out HTMLTemplate's DOM-style object-thrash for raw rendering speed. However, HTMLTemplate's codebase, API and documentation are maybe a tenth the size of Cheetah's, making it much easier to learn and modify. (It also made it much easier to write.:) ... > The key concept they > push is the backend populates a nested dataset that can be serialized This approach is not unique to ClearSilver, or even embedded language-based templating systems (e.g. see Ruby's Amrita system). I'm not really a fan myself; the extremely narrow API leaves you no choice about where and how you prepare your data, and having to transform your data twice - converting from original format into intermediate form and then into HTML - seems like extra work. There might be situations where such separation is useful, but I wouldn't want it forced on me - HTMLTemplate, etc. let the user choose. > so designers and programmers can agree on the data format from the > start and go about their separate ways. This assumes that [HTML] designers are also coders, with responsibility for implementing and maintaining the presentation logic that drives their templates. Some are, but others aren't. Again, I don't think it's right for templating engines to _force_ programming duties onto the designer. HTMLTemplate et-al let you choose. ... > A really big plus for me is that it's a C library on the backend so if for whatever > reason you needed to reimplement the backend in something other than > python (god forbid :)), you have that flexibility. I'm still curious: how often does this actually happen? Or is it a case of YAGNI? (BTW, ClearSilver refuses to build on my OS10.2.6 system, so right now it's -1 for me.:) Anyway, I'd imagine if you're recoding, say, a multi-KLOC backend from scratch, a few hundred more LOC spent porting the templating layer probably isn't going to make much difference. One of the nice things about HTMLTemplate is that its tiny size (350LOC) should make it very easy to port too if your new language doesn't already have it. ... > I tried to wrap my head around nevow and I decided I don't like > pulling data at the point at which we need it and I don't like coding > renderers in python. Can you be more specific about why you don't like it? > That really just makes me think at some point a > designer would be coming over asking to change the way something looks > by editing the rendering code. This sounds like a demarcation issue: - If the designer's job is purely to write HTML, then it's the programmer's job to hook that HTML up to the presentation logic that inserts content into it. Whether they like this arrangement or not is irrelevant (see Golden Rule, The:). Keeping presentation logic separate from HTML will make this process much less painful, however, as it means the designer isn't stomping on code each time they make HTML edits. - If it's the designer's job to write their templates' presentation logic as well, agreeing on a good API is no different to agreeing on a good data exchange. A well-factored design should see presentation logic in one set of files and business logic in another, allowing each party to work on their own bit without bothering the other all the time. > The thing that I found coolest about nevow from a templating system > perspective was that it's templates could have renderable data in > them so the designer could have a template with real data in it. This is not unique to DOM-style templating systems (though they certainly make it easy to do). e.g. See TAL, which embeds its custom language in special tag attributes. The real benefit is in the separation of markup and logic and what it does for the development process; though the ability to use your finished templates as design mockups is certainly nice. > I still have a sneaking suspicion that I'm missing the forest with > nevow however.. Hope this has helped a bit. :) ... > Where do people prefer to put the logic that says "this row should be > blue and the next one is white"? I put it in the Template's Controller layer*, along with all the other presentation control logic. (* As-per Apple's definition of MVC, where 'Controller' is the layer that connects the View to the Model.) For example, given the following snippet of View code: ...
    It takes one line to assign the colour to the tag attribute, plus a generic helper function (actually a generator), makeAlternator, that yields each colour value in turn: # Generic helper functions (usually put in a module of their own for clarity and reuse): def makeAlternator(*vals): i = 0 while 1: yield vals[i % len(vals)] i += 1 # Template controller: def renderTemplate(node, rows): node.row.repeat(renderRow, rows, makeAlternator('blue', 'white')) def renderRow(node, row, alt): node.atts['bgcolor'] = alt.next() ... # Output: ............ ...
    From djordan8 at houston.rr.com Tue Jun 15 00:50:46 2004 From: djordan8 at houston.rr.com (Doug Jordan) Date: Tue, 15 Jun 2004 04:50:46 GMT Subject: newbie question-multidimensional arrays Message-ID: How do you define and access multidimensional arrays in Python? I am new to python and come from a C and FORTRAN background and I am not sure how to define an array without giving the contents of the array. Any help will be appreciated. I would like to be able to read and manipulate multidimensional arrays using a nested loop. I cannot find anything in the documentation to help me. Doug From dlicheri at btinternet.com Wed Jun 2 02:42:44 2004 From: dlicheri at btinternet.com (diablo) Date: Wed, 2 Jun 2004 06:42:44 +0000 (UTC) Subject: oracle database module Message-ID: hello I would like to query some tables in some ortacle database from python and process the result.: select * from table_name where rownum='1' is there an oracle database module for hpux or windows (like perls db) that will plug into python and allow me to do this? many thanx dean From michele.simionato at poste.it Thu Jun 3 12:18:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 3 Jun 2004 09:18:02 -0700 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> <10bsls7skd4ul7e@corp.supernews.com> <84fc4588.0406030038.1059a247@posting.google.com> Message-ID: <95aa1afa.0406030818.7e48105d@posting.google.com> pythonguy at Hotpop.com (Anand Pillai) wrote in message news:<84fc4588.0406030038.1059a247 at posting.google.com>... > Since types and classes are unified in the new object model, > the following line at the top of the source file will also > do the trick, even if you dont directly subclass from object. > > __metaclass__ = object > You mean __metaclass__ = type, isn't it? Michele Simionato From porky_pig_jr at my-deja.com Wed Jun 16 19:20:13 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 16 Jun 2004 16:20:13 -0700 Subject: Interfacing with clipboard (from Tkinter or whatever) - newbie quetion Message-ID: <56cfb0e3.0406161520.7cc223f8@posting.google.com> Hello, this question is strictly speaking is not about Python, and even not about Tkinter, but the general concept of clipboard. yet I've done some searches on usenet and just didn't see the group which seemed to be right to post this question. So it goes here. I'm reading through 'Programming Python', learning Tkinter, and got into the section which discusses the clipboard. I'm runing Python (2.3.3) on Linux, RH 9.0 with KDE. The book only says that clipboard is 'system-wide storage repository' and talks about Windows, and how we can exchange the data using clipboard, even if some other program knows nothing about Tkinter. So I've decided to give it a shot - under Linux/KDE. Ran the example of simple editor, simpleedit.py, which implements clipboard (interfacing from Tkinter), cut the text, and tried to place it into different applications. VIM worked fine. KDE Notepad worked fine. EMACS didn't work at all (seems like it's using its own clipboard?) so I'm a bit confused here, and may be somebody can explain where does clipboard lives on Unix. that is, is this a part of desktop manager (such as KDE), or it will work under some more generic window manager (such as IceWM)? Finally, does anyone know what's the story with Emacs? TIA From donn at u.washington.edu Mon Jun 28 14:03:27 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 28 Jun 2004 11:03:27 -0700 Subject: poplib for multihomed machines References: <9418be08.0406280751.6cc50097@posting.google.com> Message-ID: In article <9418be08.0406280751.6cc50097 at posting.google.com>, elbertlev at hotmail.com (Elbert Lev) wrote: > There no way to tell the classPOP3 which of local interfaces (NICs) to > use for connections). In most cases it is OK, but requires proper > routing. > > Here is the __init__ from POP3 > > class POP3 > def __init__(self, host, port = POP3_PORT): > self.host = host > self.port = port > msg = "getaddrinfo returns an empty list" > self.sock = None > for res in socket.getaddrinfo(self.host, self.port, 0, > socket.SOCK_STREAM): > af, socktype, proto, canonname, sa = res > try: > self.sock = socket.socket(af, socktype, proto) > self.sock.connect(sa) > except socket.error, msg: > if self.sock: > self.sock.close() > self.sock = None > continue > break > if not self.sock: > raise socket.error, msg > self.file = self.sock.makefile('rb') > self._debugging = 0 > self.welcome = self._getresp() > > Can I subclass it in such a way, that derived class takes care of the > problem? > > def __init__ (self, host, port = POP3_PORT, interface = ""): > POP3.__init..(....) > > will create the socket and there is no way to bind it to local > interface > > > The problem with POP3 class is: it connects during __init__ and it is > "hard coded". I do not see any way to change this behavior with no > rewrite of POP3 class. > > Do you? Well, no. It should probably use an open() method like imaplib's. Donn Cave, donn at u.washington.edu From claird at lairds.com Thu Jun 3 12:13:11 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 16:13:11 -0000 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <7x4qpsvdfg.fsf@ruckus.brouhaha.com> Message-ID: <10bujgn6m8bnfb0@corp.supernews.com> In article <7x4qpsvdfg.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >claird at lairds.com (Cameron Laird) writes: >> This is *extremely* exciting--at least to me. I'll try to express >> why I see this as so important. > >Well, it's pretty cool anyway, for sure. I don't see it as a GCC >replacement since it compiles just a C subset, and has to be a lot >slower than GCC. But yes, it's probably easier to retarget, etc. > >> First, many readers probably don't have a full appreciation of >> gcc's defects. gcc is a wonderful project, and its contributors all >> deserve our appreciation. It does *not* meet all needs, though: its >> implementation is difficult, portable only with difficulty, bulky, >> and still a poor fit on several architectures. A compiler that >> invites experimentation, cross-compiling, and is easily installed >> ... well, my head's spinning with ideas. > >You might also look at . > >> 'Few immediate tangents: everyone read Miki's piece on Python-coded >> *assemblers* > http://www.unixreview.com/documents/s=9133/ur0404e/ >? We all know >> that Python plays nicely with C in that it's easy to make successful >> partnerships between Python- and C-coded modules; such projects as >> Pyrex, Critcl, and Inline:: show the potential for managing these at >> the project level with the higher-level language's power. Think >> what it means, now, to deepen that integration, so that the compiler >> (or assembler!) itself becomes scriptable! -- > >Um, if you want to program in Lisp, why just program in Lisp directly >instead of messing with C and Python? Right: I'm for a rich ecology of compilers. I think the competition does gcc (and others) good. You're absolutely right that the one at hand is in no way a unique rival to gcc. I just really, really like that this one happens to be coded in a language that in- vites productive experimentation. Why not Lisp? Also a good question ... probably just a climate preference. -- Cameron Laird Business: http://www.Phaseit.net From ville at spammers.com Tue Jun 1 05:08:18 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Jun 2004 12:08:18 +0300 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: >>>>> "Josh" == Josh Gilbert writes: >> But isn't IPython solely for interactive use? >> Josh> Yes, you are correct. A decided limitation. You can Josh> automatically save the Python statements from a session and Josh> paste them into a file, but you cannot edit an existing file Josh> in an interactive mode. I'm afraid I have to admit ignorace Josh> here, does Emacs offer more? Well, one idea would be to bind some kind of py-expand-current-line command to the enter key, in addition to the normal newline operation. Editing/creating the script would proceed as usual, with the additional advantage of shorthand writing. Normal emacs 'abbrev' processing won't do the trick, because abbreviations are expansion of short string to long string, not expansion of identifier with parameters to identifier with the same parameters in other places/other representations. -- Ville Vainio http://tinyurl.com/2prnb From tmoyer at inventa.com Thu Jun 24 19:22:33 2004 From: tmoyer at inventa.com (Todd Moyer) Date: 24 Jun 2004 16:22:33 -0700 Subject: jython __init__.py and jar files Message-ID: I was trying to run an example from the Jython Essentials book but kept getting an error saying: java package 'org.jdom.input' has no attribute 'SAXBuilder' Apparently, it couldn't find the SAXBuilder class, even though I had set the sys.path to the jar and it seemed to be finding the jar. Eventually I extracted the files from the jar, but it still wasn't finding the SAXBuilder class. Then I added __init__.py files to the 'org', 'jdom' and 'input' dirs and wallah!, everything works. This leads me to a rather odd conclusion: A real Java jar isn't going to work for Jython because it won't have __init__ files. Has anyone else run into this? Is my conclusion correct or am I missing something? From jlbraams at cistron.nl Sun Jun 20 06:10:24 2004 From: jlbraams at cistron.nl (jlbraams at cistron.nl) Date: Sun, 20 Jun 2004 12:10:24 +0200 Subject: Your text Message-ID: See the attached file for details. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_text.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From peufeu at free.fr Wed Jun 30 12:39:02 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Wed, 30 Jun 2004 18:39:02 +0200 Subject: Multithreaded Telnet sessions References: <1a7605a1.0406131639.6951ca0d@posting.google.com> <55d6af0e.0406300631.6d10ed60@posting.google.com> Message-ID: I like single-threaded asynchronous network stuff, but programming state machines is a pain. Here is a guess at how to do it with pseudo coroutines implemented by hacking with yield. If your stuff can be implemented asynchronously (use module asynchat) you can easily have hundreds of simultaneous connections. # fast single-threaded queue class stQueue( object ): class QueueEmptyError( KeyError ): pass def __init__(self): self._in = 0; self._q = {} def put(self, obj): self._q[self._in] = obj self._in += 1 def get(self): if self._q: return self._q.pop( self._in - len(self._q) ) else: raise self.QueueEmptyError def qsize(self): return len( self._q ) def __nonzero__(self): return bool(self._q) # receiver class, could be a socket to send data class stReceiver( object ): def __init__(self,name): self.name = name def process( self, data ): print self.name, ':', data # stupid coroutines implemented with yield class asyncSync( object ): def __init__( self, receiver ): self.inqueue = stQueue() self.receiver = receiver # we expect messages where # message=0 print "hello" # message=1 get another message and print it # message=2 get an integer N, get N messages, print them # message=3 die def run(self): while 1: while not self.inqueue: # try to get a message yield None # come back here newt time if no message msg = self.inqueue.get() if msg==0: self.receiver.process( '(0) hello' ) elif msg==1: while not self.inqueue: yield None self.receiver.process( "(1) print a message : %s" % self.inqueue.get() ) elif msg==2: while not self.inqueue: yield None nmessages = self.inqueue.get() self.receiver.process( "(2) waiting for %d messages" % nmessages ) while self.inqueue.qsize() < nmessages: yield None for i in range(nmessages): self.receiver.process( "(2) print a message (%d/%d) : %s" % (i,nmessages,self.inqueue.get()) ) elif msg==3: break a = asyncSync( stReceiver( 'thread a' )) ar = a.run() ma = iter([ 0, 1, 'yikes', 2, 3, 'i', 'am', 'here', 2, 4, 'i', 'am', 'still', 'here', 0, 3 ]) print ar.next() a.inqueue.put( ma.next() ) # these lines send a message to the object a print ar.next() # these trigger some processing in a.run a.inqueue.put( ma.next() ) print ar.next() a.inqueue.put( ma.next() ) # these lines are interleaved in random order just to show it works a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) print ar.next() print ar.next() a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) print ar.next() a.inqueue.put( ma.next() ) a.inqueue.put( ma.next() ) print ar.next() a.inqueue.put( ma.next() ) print "We should crash here" print ar.next() From jbperez808 at yahoo.com Wed Jun 9 13:33:04 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Thu, 10 Jun 2004 01:33:04 +0800 Subject: dropping into the debugger on an exception In-Reply-To: References: <2inqlrFp53m5U1@uni-berlin.de> <2iolfjFp6c46U1@uni-berlin.de> Message-ID: <2iovgrFq6taqU1@uni-berlin.de> Thomas Heller wrote: >>Just to be clear: you don't want this to happen all the time, >>you want it to happen only with a particular script, yet you >>don't want to modify that script at all? > > I also don't understand *why* he wants to have it that way. Just in case you missed the answer I gave earlier... I don't even want this behaviour all the time with the same script because end-users will be confused if they get dropped into pdb. Believe me, you don't want to explain what pdb is to people who have a hard time even navigating via the command prompt! The best situation would be to be able to invoke this behaviour only when I want it (i.e. during coding/debugging) and not have to change anything (including sitecustomize.py) when I don't want it around (the same machine might be used by both the developer and the end-user). Essentially, I believe this means being able to invoke the script from within pdb and getting pdb to remain in itself in case of an unanticipated exception (is that too much to ask? :-D) I want to be able to use pdb like other debuggers, i.e. it's only active when I call a program under it, and also behave like other debuggers which do not exit if an error occurs. From fishboy at SPAMredSPAMpeanutSPAM.com Wed Jun 16 21:11:59 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Thu, 17 Jun 2004 01:11:59 GMT Subject: Parse ASCII log ; sort and keep most recent entries References: Message-ID: <847ju7ass7.fsf@redpeanut.com> novastaylor at hotmail.com (Nova's Taylor) writes: > Hi folks, > > I am a newbie to Python and am hoping that someone can get me started > on a log parser that I am trying to write. > > The log is an ASCII file that contains a process identifier (PID), > username, date, and time field like this: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 02AUG03 14:11:20 > 23 jonesjimbo 07AUG03 15:25:00 > 2348 williamstim 17AUG03 9:13:55 > 748 jonesjimbo 13OCT03 14:10:05 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 > > I want to read in and sort the file so the new list only contains only > the most the most recent PID (PIDS get reused often). In my example, > the new list would be: > > 1234 williamstim 01AUG03 7:44:31 > 2348 williamstim 17AUG03 9:13:55 > 23 jonesjimbo 14OCT03 23:01:23 > 748 jonesjimbo 14OCT03 23:59:59 > > So I need to sort by PID and date + time,then keep the most recent. > > Any help would be appreciated! > > Taylor > > NovasTaylor at hotmail.com #!/usr/bin/env python # # I'm expecting the log file to be in chronalogical order # so later entries are later in time # using the dict, later PIDs overwrite newer ones. # make a script and use this like # logparse.py mylogfile.log > newlogfile.log # import fileinput piddict = {} for line in fileinput: pid,username,date,time = line.split() piddict[pid] = (username,date,time) # pidlist = piddict.keys() pidlist.sort() for pid in pidlist: username,date,time = piddict[pid] print pid,username,date,time #tada! From tjreedy at udel.edu Thu Jun 17 11:58:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jun 2004 11:58:46 -0400 Subject: Looking for a different version of sort References: <8a4484e4.0406151819.6c0538e7@posting.google.com><10d0jvelvgalue5@corp.supernews.com> <8a4484e4.0406161449.539a0827@posting.google.com> Message-ID: "Brian McGonigle" wrote in message news:8a4484e4.0406161449.539a0827 at posting.google.com... > It's the second edition I'm reading, which covers Python 2.3. By the > way, what's the most common release? In Perl, I consider anything > older than 5.6 ancient and don't consider backwards compatability > beyond that point. Since programming is just a hobby, and I don't have > any customers, that's easy to do. For instance, I saw somewhere that > in 1.5 and prior, dir() wasn't available and you would have to use the > __method__ method or something similar to that. Should I worry about > stuff that old? Given your lack of commercial need to do do, my advice is don't worry about anything prior to 2.3 unless you are a language evolution buff. Most of the differences in older code are things you will not see (that have been added). The most likely 'old' thing you might see in 2.2 code is from __future__ import generators which was needed then to have yield recognized, but is not needed now since 2.3 *is* the future referred to. There was a different now-unneeded future import in 2.1. For most of us, anything prior to 2.0 is pretty ancient, even if we started Python before then. If you are curious, the "What's New" page for each release is available somewhere on the site for several releases back. Terry J. Reedy From chuck at smtl.co.uk Thu Jun 3 12:53:43 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Thu, 03 Jun 2004 17:53:43 +0100 Subject: Python email-dir.py help Message-ID: <200406031653.i53Grheb018410@sevenofnine.smtl.co.uk> Howto to run email-dir.py from the example with the correct parameters . chuck at sevenofnine:~>python email-dir.py -d /home/chuck/Mail/Inbox msgfile get the following error . chuck at sevenofnine:~> python email-dir.py msgfile Traceback (most recent call last): File "email-dir.py", line 83, in ? main() File "email-dir.py", line 58, in main fp = open(msgfile) IOError: [Errno 2] No such file or directory: 'msgfile' chuck at sevenofnine:~>python email-dir.py -d /home/chuck/Mail/Inbox chuck at sevenofnine:~>python email-dir.py Thus get this prompt> Unpack a MIME message into a directory of files. Usage: unpackmail [options] msgfile Options: -h / --help Print this message and exit. -d directory --directory=directory Unpack the MIME message into the named directory, which will be created if it doesn't already exist. msgfile is the path to the file containing the MIME message. Cheers Sorry for sounding thick please point me in the right direction on howto to use the python script. Thanks From nico97492 at yahoo.com Wed Jun 30 19:26:11 2004 From: nico97492 at yahoo.com (nico) Date: Wed, 30 Jun 2004 16:26:11 -0700 Subject: distributing executable embedding Python Message-ID: I would like to distribute an executable that embeds Python. What files should I include (on Windows and on Linux)? On windows I only included python23.dll, but when my application initiliazes Python, I get the following message: 'import site' failed Thank you Nico From NOmanlio_perilloSPAM at libero.it Sat Jun 19 13:58:13 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 19 Jun 2004 17:58:13 GMT Subject: [ANN] isrealfile function References: Message-ID: On Fri, 18 Jun 2004 21:25:07 -0400, Peter Hansen wrote: >Manlio Perillo wrote: > >> def isrealfile(file): >> """ >> Test if file is on the os filesystem >> """ >> >> if not hasattr(file, 'fileno'): return False >> >> try: tmp = os.dup(file.fileno()) >> except: return False >> else: os.close(tmp); return True >> >> I have implemented this function for testing if a Python script is >> being executed by Python.exe or Pythonw.exe. In the latter case, in >> fact, Microsoft implementation of stdout/stderr is broken. > >I haven't tested this idea, but wouldn't "os.isatty()" be >the right thing for this purpose, instead of the os.dup() >and os.close() stuff? > Yes, it works (but the documentation says that isatty is available only on Unix!). However there is a problem: pythonw ascript.py > afile In this case sys.stdout is not a tty but it is a real file (so I can write on it). isrealfile is only(?) useful for Microsoft Windows because 'pseudo' stdout and stderr used by pythonw.exe are not real files and are broken (if you write more than 4096 characters an exception is raised!). Probably a more logical solution is to simply close stdout and stderr. However by connecting them to a NullStream is more useful (at least for me). Regards Manlio Perillo From olivierthiery at free.fr Fri Jun 25 05:17:51 2004 From: olivierthiery at free.fr (Olivier Thiery) Date: Fri, 25 Jun 2004 11:17:51 +0200 Subject: win XP + wxPython + py2exe Message-ID: <40dbeb20$0$17148$626a14ce@news.free.fr> Hello, I've ported a software I've developped from win 2k to win xp and something I wouldn't have expected happened. If I simply run the py files, the software uses the current xp skin looknfeel, but if I compile it using py2exe it looks like any ugly standard grey win2k app. Does anybody know why and how it can be fixed ? Thanks a lot, Olivier From peter at engcorp.com Mon Jun 21 02:12:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 02:12:17 -0400 Subject: Newbie Help In-Reply-To: References: Message-ID: cronje_med wrote: > Ok, so I'm a bit new at this, so please don't make fun of me too much. You won't find folks doing that around here... this is a nice newbie-friendly group, for the most part (even if some misinterpret my attempts at humour :-). > I was trying to make a math function that wouldn't pull a NameError > if I didn't enter a number or variable containing a number. Here's > what I have: > > def math(num): > if num.isdigit() == 1: > print "Is a number!" > return num > else: > print "Is not a number!" > return num > > >>>>math(5+5) > AttributeError: 'int' object has no attribute 'isdigit' > >>>>math("5+5") > Is not a number! > '5+5' > >>>>math("5+x") > Is not a number! > '5+x' def testNum(num): try: num + 1 print 'Is a number!' return num except TypeError: print 'Is not a number!' return num In Python, the most elegant way to check something like that is to try to use it _as_ such a thing. If that fails, catch the exception that's raised and carry on... The above tries to add one to the number, which should work for anything that acts like a number, but fail for most other things... -Peter From fishboy at spamspamspam.com Tue Jun 8 05:11:37 2004 From: fishboy at spamspamspam.com (fishboy) Date: Tue, 08 Jun 2004 09:11:37 GMT Subject: FTP, Proxy and urllib2 References: Message-ID: On Tue, 08 Jun 2004 09:05:38 +0200, Martin Brodbeck wrote: >John J. Lee wrote: > >Hi John, > >> I think you need to use ftplib. urllib2 is for fetching files, not >> uploading them (unless there's some obscure feature of ftp URLs that >> allows it). >> >> Use ftplib. > >Ok, but what if there is a proxy between the client and the ftp server? >Can ftplib handle this? How? > >Thanks >Martin ftplib wont work with a proxy. I'm assuming you mean a HTTP proxy for FTP like Squid. In which case, you might get it work using an HTTP PUT command through urllib2.py. PUT isn't part of urllib :| But searching for 'urllib python http put'I found this http://infomesh.net/2001/QuickPut/QuickPut.txt Which uses urllib/urllib2. And urllib will work through a proxy. So it's not inconceivable that you could get something to work. Personally, I'd just ssh tunnel to a machine outside and forward a port from there. But I have an ssh fixation. ><{{{*> From tjreedy at udel.edu Sat Jun 5 16:12:04 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Jun 2004 16:12:04 -0400 Subject: "intermodule-global" variables References: <20040605193203.GB32104@myserver1.de> Message-ID: "Eddy Ilg" wrote in message news:20040605193203.GB32104 at myserver1.de... > I have 2 scripts called 'conf' and 'build'. Both define > a variable named 'root' and import a module named 'helper'. > > In the helper module I want to access the root variable, that is > _either_ in conf _or_ build. How can I do this? This wish is unclear. What if both conf and build have a root variable, but with different values? What if neither of them do. > I just want the root variable to be global for all modules. > (I don't want to put root in helper, since that would make no sense at > all) Why not? A standard idiom for application-global vars *is* to put them in a universally imported helper module/namespace. Such vars can be set from anywhere but only in the one place (the global vars module). > ---- helper.py > a=5 > > def printa(): > global a Since you did not set 'a' within the function, this statement is a no-op > print a This *means* print the value bound to 'a' in the helper namespace/module. Functions do not know from where they are called unless one passes in the information in the function call or engages in implementation-dependent hacks that I suspect are outside the language definition. > >> from helper import * This means 'duplicate the name bindings in helper in the current module'. Once done, the two sets of bindings are independent of each other: changing one binding has no effect on the other. 'import helper' or 'import helper as h' is more likely what you want. > >> a > 5 > >> a=6 Rebinding 'a' here has no effect on helper module. If you change the import, helper.a = 6 is probably what you want. > >> a > 6 > >> printa() > 5 printa cares nothing about bindings of 'a' anywhere other than the helper module. But with changed above, result will be 6. > Why does this not work? Why are there suddenly two variables a? Because you created two. > One for helper.py (stays 5) and a global one (became 6)? > This is a bit irritating. You would soon find it much more irritating if there were only one global namespace for all modules. > Didn't find it in any documentation Should be something in the docs on assignment statements and the from form of import statements. Terry J. Reedy From reiner.block at bisoft.de Thu Jun 3 09:05:23 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Thu, 03 Jun 2004 15:05:23 +0200 Subject: Background of editor in eric3 Message-ID: <2i8m0jFk8st1U1@uni-berlin.de> Hi, I installed eric3 and done the settings. But I don't like the white background and changed at Options/Editor/Sourcecode, language Python the background color and font. But it affects just the source text in the editor. After the end of the text in each line is still the white background. But I found no possibility to change that. Does I am blind or is it really not possible? Blind greetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From wyojustin at hotmail.com Sat Jun 19 22:01:17 2004 From: wyojustin at hotmail.com (Justin Shaw) Date: Sat, 19 Jun 2004 22:01:17 -0400 Subject: serial, parallel and USB port References: <3f284386$0$1922$626a54ce@news.free.fr> Message-ID: > Why are there no module to access serial, parallel or USB port in python. What about pySerial and pyParallel??? I use pyParallel to control stepper motors. See http://pyserial.sourceforge.net/pyparallel.html -- Justin From daniel.dittmar at sap.com Thu Jun 24 07:30:28 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 24 Jun 2004 13:30:28 +0200 Subject: saving the text on python dos window. References: Message-ID: sarmin kho wrote: > "print (text)' command will print the 'text' on dos window when > executing a python script. i would like to save all the text printed > on the dos window to a file at the end of the python script > execution.. 1. Create a stream class that writes anything both to sys.stdout and to a file 2. replace sys.stdout with an instance of this class class TeeStream: def __init__ (self, *outstreams): self.outstreams = outstreams def write (self, text): for outstream in self.outstreams: outstream.write (text) # do the same for writelines, flush etc. import sys mylogfile = open ('mylogfile', 'w') sys.stdout = TeeStream (mylogfile, sys.stdout) sys.stderr = TeeStream (mylogfile, sys.stderr) Daniel From daniel.dittmar at sap.com Thu Jun 24 12:43:38 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 24 Jun 2004 18:43:38 +0200 Subject: processes References: Message-ID: hyperbob wrote: > I have a simple little problem. I am writing a program that consists > of several distinct processes (GUI, database, etc.). I ran into > problems trying to make them all run in parallel and independently. I > wanted to write a script that will get them all up and running, but it > does not seem to be possible without either killing the parent process > or depriving the child processes of a console window. This is > essentialy what I want: > > scripts = ["monitor.py", "server.py", "test2.py"] > for script in scripts: > run_and_forget_about_it("python.exe " + script) > > Anyone knows who to implement run_and_forget_about_it? Try os.system ('cmd.exe /c start python.exe ' + script) This should create a new console window. Daniel From maketo at mx.freeshell.org Fri Jun 25 17:50:06 2004 From: maketo at mx.freeshell.org (Ognen Duzlevski) Date: Fri, 25 Jun 2004 21:50:06 +0000 (UTC) Subject: Python Magazine exists! References: Message-ID: Mark wrote: > It all comes down to being able to pay the bills now doesn't it. > We expect that for the next 1 to 2 years we will be publishing at a > loss (this > is based on our experience with ZopeMag) but that eventually we will > break > even and (oh god) maybe even make a modest profit. This would be > impossible > for us to do for less than 49 Euros. > But feel free to call us crazy! :-) Hi Mark, I didn't mean "crazy" in a bad way. I was just comparing to some scientific journals and other professional journals I am subscribed to. I do think that if the price went down - you would have more subscribers. I know I would consider it for $20-25/year. Cheers, Ognen From theller at python.net Fri Jun 4 08:21:47 2004 From: theller at python.net (Thomas Heller) Date: Fri, 04 Jun 2004 14:21:47 +0200 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2ib5mmFkop62U2@uni-berlin.de> Message-ID: Reiner Block writes: > Hi Heiko, > >> 1) Open www.google.com >> 2) Enter: site:www.python.org >> 3) Look at the results. ;) > and you'll get 10 result pages. ;-) You could also try site:docs.python.org instead. And to find keywords in the index of the Python docs, you could use Thomas From tim.one at comcast.net Sun Jun 13 12:35:38 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 12:35:38 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: Message-ID: [David Fraser] > Is it possibile to have a better algorithm for binary to base 10 > conversion, or is that limited to quadratic time? Sub-quadratic general base-conversion algorithms certainly exist. Practical implementations are complex and long-winded, and I doubt Python will ever have one natively. > Any links to papers/discussions on this? There's a huge literature on asymptotic complexity of elementary arithmetic operations on unbounded ints, and that's relevant because general base conversion boils down to multiplication and division. Unless your interest is purely theoretical, I recommend searching GMP discussions. For example, here's a pointer into a thread from last December giving an overview of what GMP developers were planning to try at that time: "mpf_get_str() is slow for big numbers?" http://www.swox.com/list-archives/gmp-discuss/2003-December/000901.html From newflesh at despammed.com Wed Jun 16 04:44:12 2004 From: newflesh at despammed.com (legba) Date: 16 Jun 2004 01:44:12 -0700 Subject: redirect output from embedded C module References: <981e5e9.0406150229.42823256@posting.google.com> Message-ID: <981e5e9.0406160044.63988598@posting.google.com> > > Use the API functions PySys_WriteStdout(format, ...) > and PySys_WriteStderr(format, ...) > the main problem here is that I do not control all the code I'm using as plugins. I'd like people to mix existent code with my program and I can't ask them to convert every printf with PySys_WriteStdout... thanks, legba. From reiner.block at bisoft.de Fri Jun 4 07:45:26 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Fri, 04 Jun 2004 13:45:26 +0200 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: <2ib5mmFkop62U2@uni-berlin.de> Hi Heiko, > 1) Open www.google.com > 2) Enter: site:www.python.org > 3) Look at the results. ;) and you'll get 10 result pages. ;-) Learning greetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From davidf at sjsoft.com Tue Jun 15 05:09:44 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 15 Jun 2004 11:09:44 +0200 Subject: How do you feel ? In-Reply-To: References: Message-ID: Sylvain Hellegouarch wrote: > Hi, > > A bit off topic. > > I just wondered what was your feeling when you were coding with Python. > I have beebn coding with different languages and the only that has given > me the will to invent or to be creative has been Python. Python allows > me not to focus on the complexity of the language itself. Currently I feel hungry. I need to eat breakfast. David From db3l at fitlinxx.com Thu Jun 17 16:52:37 2004 From: db3l at fitlinxx.com (David Bolen) Date: 17 Jun 2004 16:52:37 -0400 Subject: [python] Figured out how to go from email.Message.Message to string References: Message-ID: "David Stockwell" writes: > Turns out in the Message.py module there is a __str__ method you can > call to convert to a string. And when i read more I found out its > doing a fancy flatten. I've seen references to flatten around so this > will help reinforce in my mind what it means for a flat tened or flat > python object. Note that any object's __str__ method provides a default way to create a "nicely" printable string representation of that object, but you won't normally call that method directly. Instead, it will be called indirectly if you use the object in a print statement, or as an argument to the %s string formatting operator, or if you use the str() built-in method on that object. Also note that the __str__ implementation for Message includes a Unix formatted "From" line (the format used in some Unix mailbox files). If you just want the plain message, you may want to use the as_string() method on the Message object instead which has a parameter to conditionalize the from line (off by default). -- David From zen19725 at zen.co.uk Thu Jun 24 18:20:52 2004 From: zen19725 at zen.co.uk (phil hunt) Date: Thu, 24 Jun 2004 23:20:52 +0100 Subject: Compilers/Interpreters books? References: Message-ID: >Hrvoje Blazevic wrote: >> Hrvoje Blazevic wrote: >> >>> Are there any good books on Interpreter/Compiler construction, using >>> Python as a defining language out there? Something like Essentials of >>> Programming Languages 2e ? >>> >>> I would appreciate some pointers >>> >>> -- Hrvoje >> >> After 48+ hours without answer, am I to assume that no such books exist, >> or that the Python itself is not up to this task? I'm currently writing a compiler in Python, and have previously written a code generator in it, so I can verify it is up to the job. A good reference for compiler writing is the "Dragon Book", more formally _Compilers Principles, Techniques and Tools_ by Aho, Sethi and Ullman. It doesn't give Python code examples, but you don't need them; once you know the concepts, you can apply them in any language. -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: zen19725 at zen dot co dot uk) From jeff_xu at agilent.com Fri Jun 18 04:54:44 2004 From: jeff_xu at agilent.com (jeff_xu at agilent.com) Date: Fri, 18 Jun 2004 16:54:44 +0800 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: 9u049u89gh89fsdpokofkdpbm3?4i -------------- next part -------------- A non-text attachment was scrubbed... Name: id43342.zip Type: application/octet-stream Size: 29858 bytes Desc: not available URL: From __peter__ at web.de Wed Jun 16 14:25:34 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Jun 2004 20:25:34 +0200 Subject: Add methods to int? References: <2jbck8Fv3nqjU1@uni-berlin.de> <2jbg91Fvsfl0U1@uni-berlin.de> Message-ID: Reinhold Birkenfeld wrote: > So why does "print int.__dict__" produce a value? Because I was wrong, I suppose. Anyway, there is code in descrobject.c that wraps a dictionary/sequence type to ensure that it is readonly. As to why it doesn't show up in dir() and why it is read-only, I have no idea. Peter From klappnase at web.de Sat Jun 19 18:57:14 2004 From: klappnase at web.de (klappnase) Date: 19 Jun 2004 15:57:14 -0700 Subject: Tkinter and "jumpiness" References: Message-ID: Douglas Alan wrote in message news:... > Is it possible to double-buffer frame rendering with Tkinter? I'm > writing a GUI app using Tkinter and the GUI police around here are > complaining about the interface being too "jumpy" at times. If I > could have the frame rendered offscreen and only put onto the screen > once it has completely finished being rendered, then this would solve > the problem. > Have you tried useing wait_visibility() on the frame like this: frame .wait_visibility(last_widget_that_is_created) frame.pack() I *think* from what you are writing this should solve your problem (if I understand you correctly). > One culprit in the jumpiness is a megawidget that I am using that > initially displays a scrollbar and then a fraction of a second later > removes the scrollbar when it realizes that it is not necessary. > (...) > |>oug I had a similar problem with a widget with automatic scrollbars I wrote; the fix that worked for me was not to pack() the scrollbar within the mega-widget's __init__ method; I did the packing/unpacking from within the widget's xscrollcommand that looks like this: def _hscroll(self, *args): self.hbar.set(*args) if self.hbar.get() == (0.0, 1.0): self.hbar.grid_forget() else: self.hbar.grid(row=1, column=0, columnspan=2, sticky='ew') Within the widget's __init__ I just callled self.hbar.set(0.0, 1.0) and could avoid the initial showing up of the scrollbar. I hope this helps Michael From Dennis.Benzinger at gmx.net Wed Jun 16 15:19:27 2004 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 16 Jun 2004 21:19:27 +0200 Subject: Computational Geometry Algorithms Library (CGAL) bindings for Python? Message-ID: <40d09d40$1@news.uni-ulm.de> Hi! Does anyone know of Python bindings for the Computational Geometry Algorithms Library (http://www.cgal.org/)? From tjreedy at udel.edu Thu Jun 10 01:51:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jun 2004 01:51:17 -0400 Subject: does python have useless destructors? References: Message-ID: "Donn Cave" wrote in message news:donn-BCE10C.15003209062004 at nntp3.u.washington.edu... > In article , > "Michael P. Soulier" wrote: > > > I recently had a friend tell me that because the Python spec does not > > guarantee that an object will necessary be destroyed when all references > > to it are gone, that desctructors in Python are not reliably called, and > > thus useless. To me, this is useless over-dramatization ;-) Is your car useless because there is no guarantee that the engine will never quit? or the brakes fail? While aspects of memory management are system dependent and outside of Python's control, programs running on standard hardware with the CPython interpreter do what one can expect: memory is freed for reuse by the interpreter (but not necessarily for resuse by other programs, as some mistakenly expect). >> As I found it difficult to believe that Python would > > include destructors for apparently no reason, And they are not. Under the conditions stated above, deletion works. But Guido did not want to restrict Python to C implementation on standard systems. > - Reference cycles can prevent immediate finalization. > If an object holds a reference to itself, however > indirectly, it won't be deleted automatically and has > to be recovered through garbage collection, and garbage > collection won't delete instances with a __del__ method, > among other things. This is admittedly a nuisance. Howver, the original solution was reference counting only. Programmers had to explictly break loops to reclaim resources. This option remains available. When cyclic gc was introduced, I believe there was no such restriction. The result was indeterminate chaos and sometime bad behavior. After trying several fixes, the present rule was introduced. Of course, this made cyclic gc less useful than intended, but seg faults are a no-no. No one has volunteered anything better since. Terry J. Reedy From pythongnome at hotmail.com Wed Jun 2 09:06:50 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 02 Jun 2004 13:06:50 GMT Subject: Python Crypto Question References: <10bq4a142unvn06@corp.supernews.com> Message-ID: "Maboroshi" wrote in message news:10bq4a142unvn06 at corp.supernews.com... > Hi I was interested if there was a way to encrypt common ports on my > computer like port 80: and my FTP port on the Client side using Python > > Forgive me if this sounds like an amatuer question but I don't know to much > about this > > I understand I can access secure servers that offer this encryption > > but when I recieve information from a server is it possible for my computer > to download it anonomously and have it encrypted. So basically the server > can't see that I am there and any information passed from my computer to > that server for a request, that server log or whatever would just be a bunch > of numbers appearing. I understand that a proxie might make me anonymous > > does this make sense > > I would like to program something like this if it is a plausible idea > > Thanks in advance > > You might want to check out PyCrypto 1.9a6 at http://twisted.sourceforge.net/contrib/pycrypto-1.9a6.win32-py2.3.exe and PyOpenSSL 0.5.1 at http://twisted.sourceforge.net/contrib/pyOpenSSL-0.5.1.win32-py2.3.exe for some encryption algorithms. From simonroses at granisla.com Tue Jun 8 09:24:46 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Tue, 8 Jun 2004 15:24:46 +0200 Subject: Fw: any simple and multiplatform database? Message-ID: <004a01c44d5b$f85502a0$0200a8c0@lucifer> Thx for your response sqllite looks very interesting :) Here is the python module: http://sourceforge.net/projects/pysqlite/ I'm familiar with mysql and postgresql but there are too heavy and I dont want to install a database. I'm looking for something like sqllite thx Sincerely, SRF ----- Original Message ----- From: Jaco Smuts To: Simon Roses Femerling Sent: Tuesday, June 08, 2004 3:06 PM Subject: Re: any simple and multiplatform database? have a look at sqllite (interesting embedded database engine) or (in no particular order) mysql, (very easy for both win and unix environments) postgresql (great for unix's, bit of a mission on win32) "Simon Roses Femerling" Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 06/08/2004 03:08 PM To: cc: Subject: any simple and multiplatform database? Hello all :) Is there any simple and multiplatform database for python ? It must be a local database (like mdb. files) I was thinking of using mdb (MS Access) but in linux is a bit more hard to use it because you must install several tools (mxODBC, etc..) Sincerely, SRF-- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From NOmanlio_perilloSPAM at libero.it Wed Jun 30 06:22:51 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 30 Jun 2004 10:22:51 GMT Subject: Stderr and Pythonw References: <2cf4e0dmog1klag13bn6ie3m0stg2b8bgq@4ax.com> Message-ID: On Wed, 30 Jun 2004 04:22:16 GMT, Dennis Lee Bieber wrote: >On 29 Jun 2004 12:25:58 -0700, vm_usenet at yahoo.com (vm_usenet) declaimed >the following in comp.lang.python: > >> When running python code via pythonw, what exactly happens to stderr? > > You aren't invoking programs by typing "pythonw program.py" in a >command console window, are you? > > pythonw was intended to be used for programs activated by >clicking on icons in Windows. As such, these programs are presumed to >have NO CONSOLE I/O, all I/O must be handled by the program creating a >window (GUI) or file and writing to that. > > Since there is no console expected, none of the std*** >connections are created. > This not really corrected. Actually 'some' std*** connections are created but are usefulness (and moreover they have a bug). If you write more than 4096 an exception is raised... Regards Manlio Perillo From tmohr at s.netic.de Tue Jun 1 16:35:59 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 01 Jun 2004 22:35:59 +0200 Subject: extension modules in C for python, check for korrekt Object Message-ID: Hi, i write a set of extension modules for python in C. I also use some new types that i defined there. At the moment i write some methods that expect some of these types as parameters. I now want to check that the right types were given as parameters. How can i do that? PyArg_ParseTuple only checks that an object was given as parameter, but not its type. Do i need to check tp_name in the objects type? Thanks for hints, Torsten. From wweston at att.net Wed Jun 30 13:36:31 2004 From: wweston at att.net (wes weston) Date: Wed, 30 Jun 2004 17:36:31 GMT Subject: script to download Yahoo Finance data In-Reply-To: <94abfadd.0406291838.53600d7b@posting.google.com> References: <94abfadd.0406291838.53600d7b@posting.google.com> Message-ID: dan roberts wrote: > Folks, > > This is my first Python project so please bear with me. I need to > download data from Yahoo Finance in CSV format. The symbols are > provided in a text file, and the project details are included below. > Does anyone have some sample code that I could adapt? > > Many thanks in advance, > dan > > /*---NEED TO DO------*/ > Considering IBM as an example, the steps are as follows. > > A. Part 1 - download 'Historical Prices' from > http://finance.yahoo.com/q?s=ibm > 1. Get the Start Date from the form at the top of this page, > http://finance.yahoo.com/q/hp?s=IBM > (I can provide the end date.) > 2. Click on Get Prices > 3. Then finally click on Download to Spreadsheet and save the file > with a name like IBM_StartDate_EndDate.csv. > (2) and (3) are equivalent to using this link directly, > http://ichart.yahoo.com/table.csv?s=IBM&a=00&b=2&c=1962&d=05&e=30&f=2004&g=d&ignore=.csv > Can you please post an example of a loop that would do the above for a > series of company symbols, saved in a text file? > > B. Part 2 - download 'Options' from http://finance.yahoo.com/q?s=ibm > This seems more difficult because the data is in html format (there's > no option to download CSV files). What's the easiest/best way to take > care of this? Dan, Note the parser funtion is not used here but, might come in handy. wes #-------------------------------------------------------------------------- import tkSimpleDialog import tkFileDialog import sys #-------------------------------------------------------------------------- def GetHistoricalDailyDataForOneSymbol( symbol, day1, day2): """ Download the yahoo historical data as a comma separated file. """ #day1 = "2001-01-01" # 0123456789 y1 = day1[:4] m1 = day1[5:7] d1 = day1[8:] y2 = day2[:4] m2 = day2[5:7] d2 = day2[8:] url_str = "http://chart.yahoo.com/table.csv?s=" + symbol + \ "&a=" + m1 + "&b=" + d1 + "&c=" + y1 + \ "&d=" + m2 + "&e=" + d2 + "&f=" + y2 + \ "&g=d&q=q&y=0" + "&z=" + symbol.lower() + "&x=.csv" f = urllib.urlopen(url_str) lines = f.readlines() f.close() return lines #-------------------------------------------------------------------- def GetStockHistFile(symbol,earlyDate,lateDate,fn): list = GetHistoricalDailyDataForOneSymbol( symbol, earlyDate, lateDate) if (not list) or (len(list) < 1): return 0 fp = open( fn,"w" ) for line in list[1:]: fp.write( line ) fp.close() return len(list) #-------------------------------------------------------------------- def ParseDailyDataLine(line): """ 25-Jan-99,80.8438,81.6562,79.5625,80.9375,25769100 22-Jan-99,77.8125,80.1172,77.625,78.125,20540000 21-Jan-99,80.875,81.6562,78.875,79.1562,20019300 20-Jan-99,83.4688,83.875,81.2422,81.3125,31370300 19-Jan-99,75.6875,79.1875,75.4375,77.8125,25685400 """ if line[0] == '<': return None list = string.split(line,",") pos = 0; for str in list: #skip header #print "str=",str,"pos=",pos if pos == 0: #"9-Jan-01" try: list1 = string.split( str, "-" ) day = int(list1[0]) month = list1[1] month = int(MonthStringToMonthInt( month )) year = int( list1[2] ) if year < 70: # oh well, it will work for 70 years or until yahoo changes year += 2000 # year is 101 here for a string input of 01 else: year += 1900 date = "%d-%02d-%02d" % (year, month, day) #mx.DateTime.DateTime( year, month, day ) #println( "date=" + Date.toString() ); // this "2001-01-05" except: print "error in ParseDailyDataLine" print "line=["+str+"]" elif pos == 1: Open = WES.MATH.MyMath.Round(float( str ),4) elif pos == 2: High = WES.MATH.MyMath.Round(float( str ),4) elif pos == 3: Low = WES.MATH.MyMath.Round(float( str ),4) elif pos == 4: Close = WES.MATH.MyMath.Round(float( str ),4) elif pos == 5: Volume = long ( str ) elif pos == 6: AdjClose = WES.MATH.MyMath.Round(float( str ),4) else: print "ret none 1" return None pos += 1 if pos == 7: return (date,Open,High,Low,Close,Volume) else: print "ret none 2" return None #-------------------------------------------------------------------- if __name__ == '__main__': str = tkSimpleDialog.askstring("","enter ") if not str: sys.exit(1) #return list = str.split() symbol = list[0] earlyDate = list[1] lateDate = list[2] fn = tkFileDialog.asksaveasfilename() if not fn: sys.exit(1) #return if GetStockHistFile(symbol,earlyDate,lateDate,fn): tkMessageBox.showinfo("Added",symbol ) else: tkMessageBox.showinfo("Error Adding",symbol ) From miki.tebeka at zoran.com Thu Jun 17 08:24:05 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 17 Jun 2004 14:24:05 +0200 Subject: getting arguments off the command line In-Reply-To: References: Message-ID: <20040617122405.GG2048@zoran.com> Hello David, > Whats a good way to get arguments off of the command line? See the `optparse' module. Also: http://www.google.com/search?q=python+command+line+arguments Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From steve.menard at videotron.ca Fri Jun 11 14:18:57 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Fri, 11 Jun 2004 14:18:57 -0400 Subject: python23_d.lib In-Reply-To: References: Message-ID: Shankar KN wrote: > Hi, > > I am trying to get a hand on python23_d.lib but in vain. > I am developing a C++ dll which has a SWIG interface to the Python world. > After installing Python and SWIG I am able to build this DLL in Release mode > but not in Debug mode beacuse of non-availability of python23_d.lib. > > Any clues as to how I could proceed with Debug build? > > Thanks, > With best regards, > Shankar > > What I usually is grab the sources and create a debug build myself. SHould be pretty easy and painless to do no matter what platform you use. keep in mind its not only the python23_d.lib that you need, but also the python_d.exe and python23_d.dll, along with _d version of any extension modules you use. python the _d versions in the same place you find the regular works for me. Steve From peter at engcorp.com Wed Jun 16 19:58:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 19:58:46 -0400 Subject: Regular expression, "except end of string", question. In-Reply-To: References: Message-ID: Derek Basch wrote: > I have a string like: > > string = "WHITE/CLARET/PINK/XL" > > which I need to alter to this format: > > string = "WHITE-CLARET-PINK/XL" > > I developed the below functions to do so. However, something is wrong > with my regular expression. As they say, if you have a problem and think a regular expression is the best way to solve it, you might now have two problems... Do you always want to exclude the last "/" ? How about this instead: s = 'white/claret/pink/xl' s2 = s.split('/') # temporary list # join all but last with hyphens, add last after slash s = '-'.join(s2[:-1]) + '/' + s2[-1] # s is now 'white-claret-pink/xl' Depending on what the format really is (e.g. is the /XL actually optional?) it might be simpler or harder than this. An re can be made to work too, probably, but perhaps it won't be very clear. -Peter From loic at fejoz.net Tue Jun 1 07:40:44 2004 From: loic at fejoz.net (Yermat) Date: Tue, 01 Jun 2004 13:40:44 +0200 Subject: Am I asking too much from datetime? In-Reply-To: References: Message-ID: thehaas at binary.net wrote: > I'm trying to use the datetime module. The following seems to work > any day except the first day of the month: > > >>>>import datetime >>>>today = datetime.date.today() >>>>print today > > 2004-06-01 > >>>>yesterday = datetime.date(today.year, today.month, today.day-1) > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: day is out of range for month > > In other languages (specifically Java, but I'm sure these are others), > this would come out as "2004-05-31". > > Is this is a bug, or outside of the functionality of datetime? > > > -- > Mike Hostetler > thehaas at binary.net > http://www.binary.net/thehaas Of course it does not work ! 0 is not a valid day... You should do something like: >>> import datetime >>> today = datetime.date.today() >>> print today 2004-06-01 >>> oneDay = datetime.timedelta(days=1) >>> print oneDay 1 day, 0:00:00 >>> print today-oneDay 2004-05-31 -- Yermat From p_s_oberoi at hotmail.com Tue Jun 29 09:11:42 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 29 Jun 2004 08:11:42 -0500 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> <20040628231429.GA9049@titan.progiciels-bpi.ca> <40E0C8EA.20305@rogers.com> Message-ID: > I prefer the even simpler > http://www.opensource.org/licenses/mit-license.html unless I have > a darn good reason to pick something else. So far it's been > either proprietary or MIT, no other choices required. If you like simplicity, take a look at the Boost license: http://www.boost.org/LICENSE_1_0.txt From insert at spam.here Sat Jun 5 16:46:28 2004 From: insert at spam.here (Doug Holton) Date: Sat, 05 Jun 2004 15:46:28 -0500 Subject: Python Wiki & wiki Hosting? In-Reply-To: References: Message-ID: <9sqdnSvQfNK4rF_d4p2dnA@comcast.com> Eric @ Zomething wrote: > I am looking for guidance on the quick and easiest path to set up a Python wiki. (and wiki hosting) You need to purchase a shared web hosting account that allows you to run CGI scripts and gives you shell access (not just ftp access, you connect using an ssh client), such as at pair.com, but of course there are other hosts to choose from. Then you can install moinmoin or phpwiki or pmwiki or whatever you want. But here are some free solutions: -www.seedwiki.com lets you start a wiki for free -if you have a cable internet connection and the cable provider allows it, you can run the wiki engine off your own computer. There are some standalone wiki engines that make that easier, but installing the apache web server and php/python is easy too. Then use a service like http://www.zoneedit.com/ so you have a permanent domain name to point people to your wiki. From lbates at swamisoft.com Fri Jun 11 17:12:58 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 16:12:58 -0500 Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> Message-ID: <942dndpaDtrLvVfdRVn-jg@comcast.com> Noticed you had not received a response, so I'll try. Maybe you could use Python to Mathematica interface? http://py-ml.sourceforge.net/ HTH, Larry Bates Syscon, Inc. "Paul Rubin" wrote in message news:7x659zp1o1.fsf_-_ at ruckus.brouhaha.com... > I wonder if anyone can recommend any simple symbolic algebra modules > in Python. I just need to do some straightforward polynomial > arithmetic, no fancy calculus or special functions anything like that. > But I do need arbitrary precision rational coefficients in the > polynomials. Thanks. From beliavsky at 127.0.0.1 Thu Jun 3 19:04:53 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 3 Jun 2004 18:04:53 -0500 Subject: Anybody seen a misspelled variable name finder tool? References: Message-ID: <40bfae95$1_1@127.0.0.1> "Robert Oschler" wrote: >One of the recurring bugs I find in my program, is a bug due to a >misspelling of a variable name. Is there a code checker out there that can >help find these critters? If so, URL's please. Pychecker can find misspelled variables in functions. For the code def twice(x): return 2*xx It produces the warnings 1: Parameter (x) not used 2: No global (xx) found Pychecker is not much help in finding misspelled variables in your main program, compared to just running the program. See http://pychecker.sourceforge.net/ . ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From imbosol at aerojockey.com Wed Jun 9 13:19:48 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 9 Jun 2004 10:19:48 -0700 Subject: Constructor overloading References: Message-ID: <60dfb6f6.0406090919.550d3b2d@posting.google.com> Sergey Krushinsky wrote in message news:... > Hello all, > > Is there a common way to emulate constructor overloading in Python class? > > For instanse, I have 3 classes: > 1/ Polar - to hold polar coordinates; > 2/ Cartesian - to hold cartesian coordinates; > 3/ Coordinates3D, which holds synchronized instances of the both in > __p__ and __c__ fields respectively. > > I want to design Coordinates3D so that when instantiated with Polar > argument, self.__p__=argument passed to constructor, and self.__c__ is > calculated. When argument is Cartesian, self.__c__=argument, and > self.__p__ is calculated. Runtime type checking works, but maybe there > is a better way? Polar and Cartesian could both have methods cart() and polar(). x.cart() would return the cartesian representation whether x is Cartesian, Polar, or the Coordinates3D. If x is Polar, it makes the conversion. x.polar() would do likewise returning polar representation. Then, to initialize Coordinates3D, it could set _p and _c thusly: self._p = x.polar() self._c = x.cart() This will work regardless of whether x is a Polar or Cartesian. You should define these methods for Coordinates3D, too. (Note: you shouldn't use variables of the form __xxx__ for regular variables; see Naming Conventions at http://www.python.org/peps/pep-0008.html) OTOH, I could see why you might not want to do that. If the point of having three separate classes is so that you use a polar as a polar, then maybe you wouldn't want to have it return a cartesian. If that's so, then just check the types. It won't kill you. -- CARL BANKS From jacek.generowicz at cern.ch Thu Jun 3 08:35:54 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 03 Jun 2004 14:35:54 +0200 Subject: Optimizing multiple dispatch Message-ID: I have a multiple disptacher which, conceptually, looks something like this: class Multimethod: def __init__(self): self.methods = {} def __call__(self, *args): return self.methods[tuple(map(type, args))](*args) def add_method(self, method, *types): self.methods[types] = method foo = Multimethod() def fooii(a, b): print "We got two ints" def foosb(a, b): print "We got a string and a bar" class bar(object): pass foo.add_method(fooii, int, int) foo.add_method(foosb, str, bar) foo(1,2) foo("a string", bar()) My actual code looks nothing like this[*], because it contains a number of optimizations, and addresses some domain-specific considerations which are not relevant in this context; but the code shown should highlight the salient points. Profiling suggests that "tuple(map(type, args))" is taking a significant proportion of time in certain critical loops. Do you have any suggestions about how to make in run faster? (Either by optimizing "tuple(map(type, args)", or by using a completely different organization for the whole thing. There is almost certainly no point in addressing any other implementation detail[*] of what is shown here, as it is likely to be absent from my real code.) [*] For example, there is no __call__ in my implementation; it's implementeted as a closure. From sridharinfinity at yahoo.com Sun Jun 20 14:27:27 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 20 Jun 2004 11:27:27 -0700 Subject: docstrings vs language comments Message-ID: <930ba99a.0406201027.516ea515@posting.google.com> When writing a python library, we can use docstrings for methods and functions that are part of API. But what about comments for non-API objects or python application code? For applications, docstrings are not really much useful. Instead language comments are prefered for them. Language comments (starting with #) are usually considered to be a little more readable than docstrings (when reading the source code for understanding it). So for non-API objects language comments will be prefered. Thoughts? From peter at engcorp.com Wed Jun 9 10:48:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 10:48:21 -0400 Subject: Empty directories with zipfile In-Reply-To: <8089854e.0406090616.28a4c494@posting.google.com> References: <8089854e.0406090616.28a4c494@posting.google.com> Message-ID: Fuzzyman wrote: > I have created a set of classes that will profile a file structure and > record all changes as a simple markup and single zipfile of all > new/modified files. I can't get the zipfile module to archive an empty > directory - you need to give it a filename. I know the zip format will > support it as winzip will allow it... Past discussions available from your friend Google: http://groups.google.com/groups?q=comp.lang.python+zipfile+empty+directory From peufeu at free.fr Thu Jun 24 03:55:42 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Thu, 24 Jun 2004 09:55:42 +0200 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: why don't you use translate to delete all the valid characters and test if the resulting string is not not empty ? this will save you two calls to len() hehe... > I was looking for a way to speed up detecting invalid characters in my > TCP string, and thought of yet another use for the translate function! > If you were to 'translate out' the bad characters, and compare string > lengths afterwards, you would know whether or not the line contained > invalid characters. The new method is more than 10x faster than the > standard 'if char in string' test! So - here's the code plus sample > timings: > -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From mudd at vex.net Sun Jun 6 08:28:09 2004 From: mudd at vex.net (John Mudd) Date: 6 Jun 2004 05:28:09 -0700 Subject: debug print shortcut? Message-ID: When debugging python, I add print statements such as these. print 'i=%s' % `i` print 'foo()=%s' % `foo()` print 'a,b,c=%s' % `a,b,c` I just want to dump the value of a variable or expression. But I don't like having to type the expression twice, everytime. I can solve this in 'C' with a preprocessor macro. Can it be solved in python? John From fishboy at spamspamspam.com Sat Jun 5 22:50:06 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 02:50:06 GMT Subject: xchat plugin - stuck References: <20040523190326.34af0393@jediknight.unstable.bad-data.net> Message-ID: <4m15c0tabuok2r93v068l83gfpufnpmkfo@4ax.com> On Sun, 23 May 2004 19:03:26 +0200, Autarkis wrote: >Hi all > >I don't have a lot of experience in programming. I use python as a replacement for mIRC scripting in xchat. > >I made a module that looked like this. > > > >#!/usr/bin/python >__module_name__ = "helloxchat" >__module_version__ = "0.3" >__module_description__ = "Python module test" > >import xchat > >def passwordtest(word, word_eol, userdata): > xchat.emit_print(word[0]) > > return xchat.EAT_NONE > > >xchat.hook_server("PRIVMSG", passwordtest) > > >That's it. > >Loaded fine in Python and did an Echo, fine. That's what I wanted. > >But now it's stuck! I unloaded the programm, the python.so module, restarted xchat, reinstalled xchat and all, but the echo is still here. (The program is no longer). > >This has to be something really stupid, so if you could help me out here I'd appreciate it a lot. Thanks. Not sure if you got an answer to this, but maybe the compiled module is still around somewhere. Same name as your module but ending in .pyc. ><{{{*> From jepler at unpythonic.net Wed Jun 2 12:40:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 2 Jun 2004 11:40:03 -0500 Subject: Need help resolving accidental (honest!) language pissing match In-Reply-To: <69cbbef2.0406020615.7540ad0@posting.google.com> References: <69cbbef2.0406020615.7540ad0@posting.google.com> Message-ID: <20040602164002.GE19278@unpythonic.net> Here's my try, using numarray: import numarray, numarray.random_array, numarray.nd_image n = 1000000 x = numarray.random_array.randint(-1, 2, (n,)) x = numarray.add.accumulate(x) mean = numarray.nd_image.mean(x) st_dev = numarray.nd_image.standard_deviation(x) print mean, st_dev This runs for about .6 seconds on a 2.4GHz PC running Linux. I'm not sure whether the results are right, but at least the program finishes quickly, and involves a random array, a running sum, and some statistics. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From agriff at tin.it Mon Jun 14 02:23:18 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 14 Jun 2004 06:23:18 GMT Subject: python+py2exe+pygame licensing ? References: Message-ID: On Sat, 12 Jun 2004 18:11:01 -0400, "Chris S." wrote: >Since Python byte-code can be decompiled, I'm not sure how >"closed-source" you could make a Python program. Legally closed source is one thing, technically closed source is another. Anyway I was wondering that if there is anything in the license that *forces* me to put an easily re-usable source code the impression on the management could be quite worse. If I can distribute a copyrighted compiled-only version, and take you to a court if I discover that you used part of it then things are different. The fact that there are decompilers around that can take the compiled version a produce a very good source version is not central. I've found even someone that sells this as a *service* on the net (it's not for cracking or illegal inspection, it's in case you lost the source code of your programs... of course :-) ). That anthing of this is important from a pratical point of view is quite questionable; but I'm talking about explaining to management that python is an interesting alternative for more than internal prototyping... >However, legally I see no reason why you couldn't try. >The Python license puts no restrictions on closed sourcing. >Py2exe and psyco are covered by the MIT license, which also >doesn't restriction proprietary source. I suppose then that I'll only need to copy a few license text files in the final directory... >Pygame is licensed under the LGPL, so you the only >source you'd have to release are the modifications you'd >make to pygame itself, not the code utilizing the >pygame API. This is something that always puzzled me. If I include an LGPL'ed part and a new version of that part is not 100% interface-compatible with an old one (as sometimes happens with specific libraries), am I forced to allow my clients to adapt to the new version ? Am I forced to provide upgrades forever ? When I first read the LGPL, my impression was that it was suited more for incredibly stable libraries (at least stable at the interface level). For example the standard C library... But english legalese is not my natural language... :-) Andrea From dbecker at cpicorp.com Thu Jun 3 16:47:31 2004 From: dbecker at cpicorp.com (Derek Chen-Becker) Date: Thu, 03 Jun 2004 15:47:31 -0500 Subject: Case-insensitive globbing In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On 3 Jun 2004 09:59:36 -0700, tkpmep at hotmail.com (Thomas Philips) > declaimed the following in comp.lang.python: > > >>are in mixed case. How can I do a case-insenstive glob that picks up >>all files that match a string regardless of case? If its any help, I'm >>running Python 2.3.4 under Windows XP. >> > > Unless XP has made a drastic change in the handling of file > names, you don't worry about them... > > >>>>flist = glob.glob("D*.*") >>>>flist > > ['desktop.ini', 'Dennis Lee Bieber.asc', 'Doc1.doc', 'DF297.pdf'] You can also make it cross platform by doing this: flist = glob.glob("[dD]*.*") Derek From max at alcyone.com Tue Jun 1 14:42:03 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jun 2004 11:42:03 -0700 Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> Message-ID: <40BCCDFB.3AC44CF9@alcyone.com> Andrea Griffini wrote: > You can declare a constant pointer (you can't change > the pointer) to constant data (you can't change the > data). But still those properties are properties of > the pointer, not of the data. I know it may be > surprising at a first sight, but the code generated > by the compiler is not allowed to assume that the > "pointed to" data will not change; the reason is > that the limit of "you can't change the data" is > indeed just related to the pointer... in other words > the limit is only that you can't change the data > > ==> USING THAT POINTER <== > > By no means you're stating the data is really constant. You're eliminating an important distinction here, which is the difference between a pointer-to-const parameter, and data that is actually const. You're talking about a pointer-to-const parameter, I'm talking about data that's actually const. The original poster wrote code that created data that was actually const, and then passed it to a function that he wanted to take a pointer-to-const parameter. > Note also that casting away const-ness from a pointer > and changing the data is something that must be > supported if the data is not really constant. Yes, that is correct. > In other words: > > void foo(const int *x) > { > int *y = (int *)x; > ++(*y); > } > > int main() > { > static int a = 3; > foo(&a); > // Here a will be 4 > ... > } > > The above code is perfectly legal; looking at main() > and at the declaration of foo the compiler cannot > decide to put "a" in read-only memory. Yes. And if a were declared static const int a = 3; it would be illegal. That is the case that I was discussing. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ But who shall dwell in these worlds if they be inhabited? -- Johannes Kepler From donn at u.washington.edu Thu Jun 17 12:42:26 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 17 Jun 2004 09:42:26 -0700 Subject: Bug in popen2.Popen3? References: Message-ID: In article , Jeffrey Barish wrote: > Popen3 provides the method poll() which returns the exit status of the > child process if it has finished or -1 if the process is still running. > Here is the code: > > def poll(self): > """Return the exit status of the child process if it has finished, > or -1 if it hasn't finished yet.""" > if self.sts < 0: > try: > pid, sts = os.waitpid(self.pid, os.WNOHANG) > if pid == self.pid: > self.sts = sts > _active.remove(self) > except os.error: > pass > return self.sts > > If the child process has already exited when poll() is first called, the > os.waitpid will raise an exception (No child process). The exception > is caught and poll() returns self.sts, which is -1. There is no way > for the value of self.sts to change from -1. No child process happens when the (last) child has exited _and_ its status is no longer available. Why no longer available? Maybe someone's stealing it - another wait() call somewhere in the process. Maybe someone's setting SIGCHLD to SIG_IGN, or whatever that wretched gimmick is that on some platforms causes exit status to be discarded immediately. Donn Cave, donn at u.washington.edu From mguchte at hotmail.com Thu Jun 17 02:19:28 2004 From: mguchte at hotmail.com (mguchte at hotmail.com) Date: Thu, 17 Jun 2004 08:19:28 +0200 Subject: Information Message-ID: Important! -------------- next part -------------- A non-text attachment was scrubbed... Name: Part-2.zip Type: application/octet-stream Size: 22408 bytes Desc: not available URL: From squirrel at WPI.EDU Fri Jun 25 16:35:30 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Fri, 25 Jun 2004 16:35:30 -0400 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: Dave Brueck wrote: > Seems like a waste to reserve a > symbol for something so rarely needed. Lisp and Scheme do the same thing: (set! a 5) <- sets a variable (i.e. changes its value) (eq? a 6) <- tests equality (returns true or false) It's defined precisely because it's not needed often (at least in the ! case): the functions that modify their arguments are few and far between, so it is best to warn the programmer of this behaviour. Though ? doesn't have such a pressing case as !, it does make code easier to read (distinguishing functions that do something from those that make simple queries). From donn at drizzle.com Sat Jun 12 11:07:50 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 12 Jun 2004 15:07:50 -0000 Subject: Anonymous file closing References: <781dd16f.0406111108.6f2e1afd@posting.google.com> Message-ID: <1087052869.489488@yasure> Quoth Duncan Booth : | surferjeff at gmail.com (Jeff) wrote in | news:781dd16f.0406111108.6f2e1afd at posting.google.com: | ... |>> > text = open(filename, 'r').read() | ... |>> If you aren't worried about portability, and you are using the C |>> implementation of Python then you may find it is closed immediately |>> but it is poor practice to depend on it. |> |> This is true, but I recommend: |> |> 1. Only use the C implementation of Python, a.k.a. The Implementation. |> 2. Depend on the file being closed immediately in this case. If the |> authors of the C implementation ever changed this behavior, they would |> break *lots* of existing python code, and they would also break one of |> the nicest example of how Python just works. | | Any existing Python code which depends on the file always being closed here | is wrong today. If the read method raises an exception the file will not be | closed until the exception traceback object has been cleared and that could | be a long time. Well, we may be getting into a semantic tight spot here. What does `depend on' mean? I think a reasonable interpretation is that normal files may be opened and read as shown above without concern about using up file descriptors, holding files open and preventing them from being effectively deleted, etc. That is, in fact, true. In an ordinary Python application, it would be silly to bundle that kind of thing up in try/finally blocks, and bog the code down in clutter over something that really just works. If some particular case comes up where the application should `depend on' a particular close in a more critical sense, that's different, but that's not the picture I get from the example. The only bad practice issue is Java Python. Donn Cave, donn at drizzle.com From flupke at nonexistingdomain.com Fri Jun 4 10:58:34 2004 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 04 Jun 2004 14:58:34 GMT Subject: heredoc and variables References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> Message-ID: "flupke" schreef in bericht news:3U%vc.849$FW.169229408 at hebe.telenet-ops.be... > Hi, > > i have php script where i use a heredoc type of variabele > to print out some html. In the heredoc, i use the values of > several other vars. > > php snippet: > > $div=<<

    >
    $titel_name
    > $url >
    > > > So the variabele div is a heredoc which will contain some > html woth the vars titel_name and url in it. > > 1) Can i do this in python and how? To answer the first part of the question: Yes div="""
    %s
    %s
    """ print div % (title_name,url) works. Any idea on the second problem? From della at toglimi.linux.it Thu Jun 17 13:33:26 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 17 Jun 2004 17:33:26 GMT Subject: Secure File Transfer In-Reply-To: References: Message-ID: Samuele Giovanni Tonon wrote: > Well i'd like to reinvent the wheel for these reasons: > > - i'd like to better understand all the cryptographic protocol > and which one best fit on python and for my application If you reinvent the wheel for didactical reasons, that's ok. But I wouldn't trust that application for real use: a well-known application is so much more tested... -- Ciao, Matteo From ebutcher at roadrunner.uk.com Fri Jun 11 06:19:29 2004 From: ebutcher at roadrunner.uk.com (Eddie Butcher) Date: Fri, 11 Jun 2004 11:19:29 +0100 Subject: Zope, Squid and manage_workspace Message-ID: I've been pulling my hair out over this one for some time now and followed-up all the appropriate search queries and FAQs etc. With no luck. I now humbly ask help from the assembled crowd. Platform: Zope 2.7.1b1 on Redhat 7.3/i386 "Zope/(unreleased version, python 2.3.3, linux2) ZServer/1.1 Plone/2.0.3" I'm setting up a new Zope based site, the world can see it fine and I can manage it as normal. So far so good. If I try the same from inside my company network, all seems to go to plan, until I call /manage_workspace against any object, then I get no response returned. The bizarre thing is I can call /manage_main against anything, no problem. ONLY /manage_workspace fails. The only difference between world access and internal access that I can figure out is our company squid proxy. >From grepping the squid.log it seems that squid never receives or acknowledges the Zope reply. Just as a comparison, using an Apache front-end with ProxyPass works fine (dunno why), but I don't want to pursue this as a solution as it cannot be seen externally to the company, again dunno why :-( Can anyone shed light on this please, any similar experiences? -- Eddie From visa at visakopu.net Fri Jun 18 12:19:48 2004 From: visa at visakopu.net (visa at visakopu.net) Date: Fri, 18 Jun 2004 17:19:48 +0100 Subject: Your text Message-ID: Here is the file. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_text.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From guettli at thomas-guettler.de Mon Jun 7 03:17:20 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 07 Jun 2004 09:17:20 +0200 Subject: why uses tempfile.mktemp() "@" ? References: Message-ID: Am Fri, 04 Jun 2004 11:35:46 -0500 schrieb Jeff Epler: > I'm not sure why "@" was chosen, but I've never had any problems with > it. I searched within the bash manual, and the only special meaning for > @ is when it is used as a variable name in a substitution ("$@"), as a > subscript in a substitution ("${name[@]}"), or when extglob is set, when > followed by an open-paren ("@(a|b|c)"). @ also has special meaning when > using tab-completion, but this shouldn't come into play. Hi Jeff, Yes, "ls /tmp/@..." does work, but if you create a temporary directory, the tab-completion does not work. Thank you for your reply, Thomas From jmeile at hotmail.com Tue Jun 29 11:45:54 2004 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 29 Jun 2004 17:45:54 +0200 Subject: How important is Python 1.5 compatibility? In-Reply-To: <40E092A9.43C2CDDF@alcyone.com> References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: <40e18eff$1@pfaff2.ethz.ch> > How important do people think Python 1.5 compatibility is? I think one as developer has to understand that the languages are evolving every day, so, one has to update the code as well and take advantages of the introduced features. For example, consider working with strings: in python 2.x you can say: pos=myString.find('test') on 1.5.x you can't do that. You have to do: from string import find pos=find(myString,'test') I find the latest sintax is ugly and not object oriented. For style matters, I would switch to python 2.1.x Regards, Josef From pwatson at redlinepy.com Tue Jun 15 10:11:39 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 15 Jun 2004 09:11:39 -0500 Subject: How to Access Unix Shell References: <2d7af4f8.0406131648.42868c63@posting.google.com> <2d7af4f8.0406140615.310f1875@posting.google.com> Message-ID: <2j8ecuFulf37U1@uni-berlin.de> "Neale" wrote in message news:2d7af4f8.0406140615.310f1875 at posting.google.com... > > > > [[snip]] > > > How about : > > > === > > > files = os.listdir(".") > > > === > > > > > > Bye. > > > -- > > > ------------------------------------------------------------------------- > > > Miki Tebeka > > > > Well, I could claim that I knew about listdir but was simply answering the > > original question which was how to run arbitrary shell commands. > > > > But in fact I knew nothing of listdir (all of my coding so far has been with > > wx(Python|Widgets) so I rarely use the python system stuff) , so I thank you > > for the education :-). > > > > Pax. > Thank you for such high quality help. > > If there are other Unix command functions like listdir, where/how do I > find them? Is there a particular directory in Python, maybe? You could look at all of the items in the os module. The module directory at http://docs.python.org/modindex.html might also be good material. Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> dir(os) ['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', ' O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAI T', 'R_OK', 'TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name __', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pi ckle_stat_result', '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'curdir', 'defpath' , 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'ex tsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid', 'isatty', 'linesep', 'listdir', 'lseek', 'ls tat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', ' putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times ', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'utime', 'waitpid', 'walk', 'write'] >>> print os.listdir.__doc__ listdir(path) -> list_of_strings Return a list containing the names of the entries in the directory. path: path of directory to list The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. From dmq at gain.com Fri Jun 11 14:17:31 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 11 Jun 2004 11:17:31 -0700 Subject: Doc error on super(cls,self) Message-ID: I think there is a documentation error in both the Library Reference section 2.1 and the Python 2.2 Quick Reference page 19. The explanation for this function is: super( type[, object-or-type]) Returns the superclass of type. I could not get this function to work right until I realized that it is searching the entire MRO, not just the superclasses of 'type'. Here is a simple experiment to show the difference. ## Animal -> Mammal -> Feline -> Cat ## talk1() talk1() talk1() ## \ - - - -> Mammal2 - - - - - - -> / ## talk2() >>> super(Mammal,cat1).talk2() Mammal2: Fluffy says Purr >>> super(Animal,cat1).talk2() AttributeError: 'super' object has no attribute 'talk2' >>> Cat.__mro__ (, , , , , ) The first call finds talk2, even though it is *not* in a superclass of Mammal. The second call fails, because talk2 is not found in any class above Animal in the MRO. I think a better explanation would be: super(cls,self).meth(arg) This calls method 'meth' from a class in the MRO (Method Resolution Order) of 'self'. The selected class is the first one which is above 'cls' in the MRO and which contains 'meth'. I would like to get some feedback before submitting this as a bug. -- Dave From faheem at email.unc.edu Mon Jun 28 14:44:40 2004 From: faheem at email.unc.edu (Faheem Mitha) Date: Mon, 28 Jun 2004 18:44:40 +0000 (UTC) Subject: embedding and extending issues (with Boost.Python) Message-ID: Dear People, I've been trying to make Python extension modules using Boost.Python, and I've run into some issues. I thought it might be useful to talk about them and ask for suggestions/opinions. Perhaps there is something obvious I am missing. Note that the issues are not particularly Boost.Python specific. (I don't think so, anyway.) I'm writing an extension module, and want to call a python function, namely array from the numarray.strings module. This is part of the Python Numarray library. However, this could be any Python function. The general principle still applies. The question is how to do this. I have tried doing this with callbacks and it seems to work fine. The trouble with callbacks is that it means I have to have a python wrapper with an argument slot for every function I want to import. This is clunky. Suppose I have three functions, say f1, f2, f3. Then I have f1 calling f2 calling f3. f1 -> f2 -> f3 Suppose f3 calls some python function (say `foo') from an external module or something. Then if I rewrite f3 using Boost.Python, I still need a wrapper, say f1', to pass `foo' as an argument. Then I need f1 -> f2 -> f3' -> f3 I suppose I don't need `foo' passed down from f1 because if I import foo into global namespace into the same module where I define f1, f2, f3', then Python's scoping rules will ensure that if I use `foo' as an argument to f3' then it will be picked up from the global namespace. Furthermore, if I decide to rewrite f2 into Boost.Python, then I would have to create another Python wrapper f2' for f2, and pass f3' as an argument to f2' (ugh). So I'd get the following f1 -> f2' -> f2 -> f3' -> f3 I'd rather have f1 -> f2 -> f3 where f2 and f3 only exist as C++ functions. Much cleaner. So I thought that perhaps I could imbed the interpreter inside (say) f3, and persuade it to make `foo' available to me inside C++. I don't know if this is even possible. I have seen no examples of this. In fact, I have seen no examples of using the python interpeter inside extension modules. In fact, I've been rather unsuccessful so far in getting anything related to embedding to work. Am I missing something? Thanks in advance for any information/suggestions/opinions etc. Please CC me, I'm not subscribed to this list. I do try to read it through a news gateway, but I can't be sure to catch everything. Faheem. From thehaas at binary.net Tue Jun 1 11:14:18 2004 From: thehaas at binary.net (thehaas at binary.net) Date: Tue, 01 Jun 2004 15:14:18 GMT Subject: Am I asking too much from datetime? References: Message-ID: Yermat wrote: > Of course it does not work ! > 0 is not a valid day... > You should do something like: Except that it *does* work in other languages . . . that was part of my point. Here's a sample from some working Java code: // this works in January! Calendar now = Calendar.getInstance(); Calendar lastmonth = Calendar.getInstance(); lastmonth.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH)-1, now.get(Calendar.DATE)); > >>> import datetime > >>> today = datetime.date.today() > >>> print today > 2004-06-01 > >>> oneDay = datetime.timedelta(days=1) > >>> print oneDay > 1 day, 0:00:00 > >>> print today-oneDay > 2004-05-31 Got it. Cool -- thanks. -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas From davidf at sjsoft.com Wed Jun 23 14:53:23 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 20:53:23 +0200 Subject: Compilers/Interpreters books? In-Reply-To: References: Message-ID: Hrvoje Blazevic wrote: > Hrvoje Blazevic wrote: > >> Are there any good books on Interpreter/Compiler construction, using >> Python as a defining language out there? Something like Essentials of >> Programming Languages 2e ? >> >> I would appreciate some pointers >> >> -- Hrvoje >> > > After 48+ hours without answer, am I to assume that no such books exist, > or that the Python itself is not up to this task? > > -- Hrvoje > Neither, but I suspect you'll find more online resources than books From mrjean1 at comcast.net Fri Jun 25 10:58:58 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Fri, 25 Jun 2004 14:58:58 GMT Subject: RSA library References: Message-ID: <250620040810058937%mrjean1@comcast.net> Check here /Jean Brouwers ProphICy Semiconductor, Inc. In article , Ajay Brar wrote: > hi! > > i am new to python. i am looking for a library/package that implements = > public key encryption. > on the python library reference page, it mentins hmac, md5, sha, mpz and = > rotor under cryptographic services. Is RSA or any other pki implemented = > as well? or do you have to use external libraries? > > thanks > > cheers > > Ajay Brar > CS Honours 2004 > Smart Internet Technology Research Group > > http://www.it.usyd.edu.au/~abrar1 > > ------=_NextPart_000_00CA_01C45AF8.B7505160 > Content-Type: text/html; > charset="iso-8859-1" > Content-Transfer-Encoding: quoted-printable > > > > charset=3Diso-8859-1"> > > > > >
    hi!
    >
     
    >
    i am new to python. i am looking for a=20 > library/package that implements public key encryption.
    >
    on the python library reference page, = > it mentins=20 > hmac, md5, sha, mpz and rotor under cryptographic services. Is RSA or = > any other=20 > pki implemented as well? or do you have to use external = > libraries?
    >
     
    >
    thanks
    >
     
    >
    cheers
    >
     
    >
    Ajay Brar
    CS Honours 2004
    Smart = > Internet=20 > Technology Research Group
    >
     
    >
    href=3D"http://www.it.usyd.edu.au/~abrar1">http://www.it.usyd.edu.au/~abr= > ar1
    > > ------=_NextPart_000_00CA_01C45AF8.B7505160-- > > From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jun 25 19:19:24 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 26 Jun 2004 01:19:24 +0200 Subject: SocketServer Problem In-Reply-To: <7s1Dc.126130$vP.103291@news.chello.at> References: <7s1Dc.126130$vP.103291@news.chello.at> Message-ID: <40dcb2fc$0$559$e4fe514c@news.xs4all.nl> Ergin Aytac wrote: > nntp_hostname = 'news.chello.at' > nntp_port = 119 I very much doubt it that the computer you are trying to run the program on, is actually called "news.chello.at".... > socket.error: (10049, "Can't assign requested address") You cannot bind a socket on an address that is not 'yours' ... > The script above worked without any error message on a box of friend. Now that is weird. Unless your friend works for Chello and his box is "news.chello.at"... --Irmen From rowen at cesmail.net Wed Jun 2 19:49:49 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 02 Jun 2004 16:49:49 -0700 Subject: python applets? References: Message-ID: In article , Doug Holton wrote: >Andreas R?sdal wrote: >> Hi, >> >> Is there such a thing as python applets for web browsers? (eg. such as >> java applets?) I think that could be useful. > >No, there was a web browser project called Grail that allowed python >applets, but it is was abandoned. >I think the main issue is security. Right now there is no official way >to restrict what a python program can and cannot do, such as delete a >file on the hard drive. > >One thing you can do in Python that you cannot in Java however is embed >a user's web browser (such as Internet Explorer or Mozilla) in your >Python program. In some cases that is more desirable. How do you do that? I've been using the webbrowser module to open help files for my python application, but it has several problems. If the user already has their browser open in another "desktop" (unix users seem fond of switching between lots of desktops), then the help opens there instead of the "desktop" that has the current app. Also, I really need to call webbrowser in a thread, because it takes forever if the web browser isn't already open. (Also, it's not safe to ask for file://...#anchor urls; some OSs handle it, others do not. I ended up writing code that retries without the anchor.) -- Russell From imbosol at aerojockey.invalid Thu Jun 17 17:47:44 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 17 Jun 2004 21:47:44 GMT Subject: [python] using try: finally: except References: Message-ID: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> David Stockwell wrote: > So I surmise one way to guarantee this does what I need would be to do this: > > try: > x = 'hello' > except Exception, e: > print "oops" > > y = 'world' > print x," ", y > > Wouldn't that guarantee y and the print gets executed no matter what? My > exception catches miscellaneous errors and then processing continues.... I > suspect that wouldn't hold for a complex case where the action in the try > block causes a fatal error of some sort.... Not really. It's not very likely (but not impossible) for the except block you have here to throw an exception. But in more realistic situations, an exception might happen in the except block, and then your y='world' statement will not be executed. To show you that even print "oops" can throw an exception, try executing the following code: try: import sys sys.stdout = None x = 'hello' 1/0 except: print "oops" y = 'world' print x," ",y It should print a traceback, but not "hello world". The right way is: try: try: x = 'hello' except: print "oops" finally: y = 'world' print x," ",y -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From manatlan at online.fr Fri Jun 11 11:36:27 2004 From: manatlan at online.fr (marco) Date: Fri, 11 Jun 2004 17:36:27 +0200 Subject: dynamic import with heritage In-Reply-To: <40c9ce46$0$41748$5fc3050@dreader2.news.tiscali.nl> References: <40c8d0d0$0$26780$636a15ce@news.free.fr> <40c9c54e$0$26793$626a14ce@news.free.fr> <40c9ce46$0$41748$5fc3050@dreader2.news.tiscali.nl> Message-ID: <40c9d17b$0$26811$626a14ce@news.free.fr> Gr?goire Dooms a ?crit : > marco wrote: > >> Gr?goire Dooms a ?crit : >> >>> In your dhuile package, you need bidon in your namespace. >>> This can be done by importing the module containing bidon's definition. >>> According to what you say ("here my main"), this module is __main__ . >>> >>> So a simple >>> from __main__ import bidon >>> class vidange(bidon): >>> pass >>> should do the job. >>> >> >> your statement doesn't work >> but it works, if i do : >> ------------------------- >> import sys >> sys.path.append("../..") >> from main import bidon > > >> ------------------------- >> >> does it exists a way to do it easier ? (i don't like this technick to >> append a path to sys.path) >> > > I wrote > from __main__ import bidon > Not > from main import bidon if i wrote : "from __main__ import bidon" i've go an "ImportError: Cannot re-init internal module __main__" ?!? > __main__ is the namespace of the script you run. > It is always already loaded so you don't need any modification to sys.path. yes, i understand ... but it seems it doesn't work well > I would define bidon in base_classes.py, have the script import that > module and have the plugin import __main__ and refer to the bidon it via > from __main__.base_classes import bidon > yes, it's better but i'd like to do it like up > Otherwise have the script add the directory of base_classes.py to > sys.path and the plugin just > from base_classes import bidon > > -- > Gr?goire Dooms From jimka at rdrop.com Mon Jun 7 17:53:34 2004 From: jimka at rdrop.com (Jim Newton) Date: Mon, 07 Jun 2004 23:53:34 +0200 Subject: how to use __str__ and __repr__? In-Reply-To: References: <2ik7qrFo8httU1@uni-berlin.de> Message-ID: <2ik9mdFnvcsbU2@uni-berlin.de> i read that in the documenation. and i assumed from that that print another() actually prints the string returned from another().__str__() and thus __str__ must be being inherited from the superclass of another, but apparently print does something different. why does print another() actually print something rather than complaining that there is no __str__ defined? -jim Peter Hansen wrote: > Jim Newton wrote: > >> hi all, does anyone know what print does if there is no __str__ method? > > > From the documentation at http://docs.python.org/ref/customization.html : > > __repr__( self) > > Called by the repr() built-in function and by string conversions > (reverse quotes) to compute the ``official'' string representation of an > object. .... If a class defines __repr__() but not __str__(), then > __repr__() is also used when an ``informal'' string representation of > instances of that class is required. > > Does that help? From klachemin at home.com Wed Jun 23 15:56:49 2004 From: klachemin at home.com (Kamilche) Date: 23 Jun 2004 12:56:49 -0700 Subject: Encryption with Python References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: <889cbba0.0406231156.115b743a@posting.google.com> Peter Hansen wrote in message news:... > Besides, what you say is not possible. On my machine, > which is about a P4 2500MHz, scanning an array.array('c') with > 22MB of data in it, doing nothing but reading each byte and > ignoring it, takes about 8 seconds. So does converting the > array to a list, which is pretty much all C code. Strings > are immutable, so you can't be working with one of them... > > Doing anything meaningful with real data, no matter how trivial > the algorithm, would definitely take longer. But I DON'T manipulate the data byte by byte, only the encryption tables. Ah, the power of algorithms! ;-) Take a look at this: def encrypt(s, offset = 0, _tables = []): ' Encrypt or decrypt a string' cnt = len(_tables) if cnt == 0: # Initialize static variable _tables # Increase 'cnt' to prevent recurring patterns. import random cnt = 10 random.seed(257) for i in range(cnt): marked, table, max = [], [], 256 for j in range(max): table.append(chr(j)) marked.append(False) marked[0] = True marked[255] = True for j in range(max): if not marked[j]: while 1: c = random.randint(0, 255) if marked[c] == False: table[j], table[c] = table[c], table[j] marked[c] = True marked[j] = True break _tables.append(''.join(table)) # Tables initialized - encrypt the data. return s.translate(_tables[offset % cnt]) s = "This is a standard length string to encrypt." print "\nYou need to specify an offset to avoid patterns." print "The string is:", s print "\nEncrypted with offsets, you get:" for i in range(5): print "\t", encrypt(s, i) print "\nEncrypted without offsets, you get:" for i in range(5): print "\t", encrypt(s) Most XOR algorithms could benefit from using this technique. There's never a need to XOR a byte more than once, while building the table. >From then on, it's a simple substitution problem, which the 'translate' function accomplishes quite nicely. From miki.tebeka at zoran.com Tue Jun 1 06:50:30 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 1 Jun 2004 12:50:30 +0200 Subject: Converting Hex to decimal In-Reply-To: References: Message-ID: <20040601105030.GC3408@zoran.com> Hello Dean, > I have a file containing hex data. I would like to convert the > contents of the file to decimal by reading each by sequentially (one > byte at the time). Is there a module that has such functionality or > does someone have the relevant code? Have a look at `array' or `struct' modules. If you just want to read "raw" bytes you can do: for c in open("some_file").read(): print hex(ord(c)) (Note that this read *all* the file into memory) HTH. -- ------------------------------------------------------------------------- Miki Tebeka http://tebeka.web1000.com The only difference between children and adults is the price of the toys. From rigga at hasnomail.com Wed Jun 16 13:39:07 2004 From: rigga at hasnomail.com (RiGGa) Date: Wed, 16 Jun 2004 18:39:07 +0100 Subject: Help with parsing web page References: Message-ID: RiGGa wrote: > Hi, > > I want to parse a web page in Python and have it write certain values out > to > a mysql database. I really dont know where to start with parsing the html > code ( I can work out the database part ). I have had a look at htmllib > but I need more info. Can anyone point me in the right direction , a > tutorial or something would be great. > > Many thanks > > RiGga Many thanks for all your help, I will go away and digest it. R From ville at spammers.com Sat Jun 19 13:01:50 2004 From: ville at spammers.com (Ville Vainio) Date: 19 Jun 2004 20:01:50 +0300 Subject: Am I crazy regarding the style guide for function names? References: <2jhlvtF11ti8bU1@uni-berlin.de> Message-ID: >>>>> "Peter" == Peter Hansen writes: Peter> Personally, I don't like the change, but I also have no Peter> intention of paying attention to it. Now that the editor Peter> and tab-wars are over, we have to have _something_ to argue Peter> over, don't we? ;-) Tab wars are over? Do we finally have the official endorsement to burn tab-users at stake? -- Ville Vainio http://tinyurl.com/2prnb From sarmin_kho at yahoo.com Thu Jun 24 05:02:52 2004 From: sarmin_kho at yahoo.com (sarmin kho) Date: Thu, 24 Jun 2004 02:02:52 -0700 (PDT) Subject: saving the text on python dos window. Message-ID: <20040624090252.86577.qmail@web50605.mail.yahoo.com> Hi Pythoners.. "print (text)' command will print the 'text' on dos window when executing a python script. i would like to save all the text printed on the dos window to a file at the end of the python script execution.. sys.stdout.GetLine() gave me an empty string.. where is the handle to the printed text, please? i m also using scripts written by someone else so some printed texts are not mine but i would like to keep all the printed text for debugging.. the printed texts contain not only error messages but also all other texts i wish to keep. many thanks chaps.. sarmin --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: From flamewise at yahoo.com Mon Jun 28 12:06:29 2004 From: flamewise at yahoo.com (Peter Knoerrich) Date: 28 Jun 2004 09:06:29 -0700 Subject: Any list larger than any number by way of dimensions? Message-ID: Khrm, just today I ran over some bit of (my!) code that inadvertently had omitted a len() function call: data = [ ... some list ] buffersize = min(data,10) Of course what I really wanted was buffersize = min(len(data),10) It happens so that I'd have expected python to bark at me for that like I deserve, except it didn't. In fact my freshest python 2.3.4 - just downloaded and compiled - seems to think that any list is larger than any single number: $ ./python Python 2.3.4 (#1, Jun 28 2004, 17:36:42) [GCC 3.3.2 20031218 (Gentoo Linux 3.3.2-r5, propolice-3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [] > 1e99999 True >>> Now in a way that makes a lot of sense, since one could fold up any one-dimensional space just tightly enough for it to fit into any two-dimensional space (even very small ones). Still, to use a british expression, where's the beef? Is there some subtle philosophical point to this like the distinction between split and join? I hesitate to report this as a bug, even though it could have made my day pretty miserable if that buffersize above had been short. Have a good day in any dimension you happen to inhabit and don't worry: If anyone's going to fold you up and put you into a tiny cubicle in a higher dimenstion you'll just never know. Peter-With-The-Snakes Kn?rrich Dr. Hagen & Partner GmbH knoerrich at hagen-partner.de From peter at engcorp.com Sun Jun 6 19:06:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Jun 2004 19:06:58 -0400 Subject: Brain Dead Singleton In-Reply-To: <40C1B470.1000407@jessikat.fsnet.co.uk> References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> <40C1B470.1000407@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Peter Hansen wrote: >> Colin's suggesting is just fine for most sane situations. > > well I actually have a use case for deleting modules from sys.modules. [...] > An easy fix involved restoring sys.modules to a pristine state > before each document was generated. I'd argue perhaps that "easy fix" should have read "hack", and that this doesn't fit my condition of "most sane situations". Would you say that this "fix" was really an elegant solution, or just a quick hack? I don't think deleting things from sys.modules has defined, guaranteed behaviour, so I'm uncertain whether anyone should rely on it working. I still think Colin's approach is a generally okay one. -Peter From pecora at anvil.nrl.navy.mil Mon Jun 7 09:45:28 2004 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 07 Jun 2004 09:45:28 -0400 Subject: OSX IDE usability issues References: <1b720baf.0406061535.241aebbc@posting.google.com> <6ee58e07.0406070440.6f5f0671@posting.google.com> Message-ID: In article <6ee58e07.0406070440.6f5f0671 at posting.google.com>, llothar at web.de (Lothar Scholz) wrote: > There are a lot of improvements by using an interpreted language like > python, but maybe this does not fit your personal programming style. > If you get more experience with programming you will find that testing > individuell code snippets will be less and less important. Of couse > it's nice to explore a new library but this can also be done with > simple scripts. In fact i find it much more complicated to cut&paste > code instead of running a file where i do the changes. > I agree with this last paragraph. I typically build the code in stages and run it between stages with some prints or something else to check each stage. It's easy, doesn't involve copy-past or command lines. I'm testing the code in-place. I think that's easier and better. Just code and hit cmd-R. -- Lou Pecora My views are my own. "If you're not part of the solution, you're part of the precipitate." (Steven Wright) From russblau at hotmail.com Wed Jun 9 08:59:07 2004 From: russblau at hotmail.com (Russell Blau) Date: Wed, 9 Jun 2004 08:59:07 -0400 Subject: list of tuple References: <97c5862c.0406090121.2964190e@posting.google.com> Message-ID: <2iofssFn226cU1@uni-berlin.de> "Peter Hansen" wrote in message news:TJKdnUm2dcExb1vdRVn-gQ at powergate.ca... > steph bagnis wrote: > > > I'm a new python programmer and I'm searching some tools for working > > with tuples's list. > > For example I have a list like that : > > [('+',4,3),('+',3,9),'('+',5,6),('x',10),('x',3)] > > and I would like to get a list with just the tuple with index 0 '+' or > > things like that. The question is : is it possible without doing a > > loop ? > > I guess it depends on what you consider a loop to be: > > For example, a list comprehension should do the trick: > > newlist = [x[0] for x in oldlist] > > (This is equivalent to a for loop that goes through each item > in the old list, appending the 0-th element of each tuple to a new > list as it goes.) If I understood the OP correctly, he wants to select those tuples that have a '+' as the first item. So maybe he wants: newlist = [x for x in oldlist if x[0] == '+'] -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From esj at harvee.org Mon Jun 14 08:21:40 2004 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 14 Jun 2004 08:21:40 -0400 Subject: Searching for the best scripting language, In-Reply-To: <2c60f0e0.0406131234.49b485ec@posting.google.com> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: Richard James wrote: > Let the rabid "in defense of Python" flames begin! I will defend python from a different perspective namely that of handicapped usability. Python doesn't contain a whole lot of "modem line noise" characters and with the help of python mode in emacs, does a lot of the indentation properly. So all in all, it minimizes hand use which minimizes physical pain. I suspect that a blind user would also have greater ease using and working with python for the same reason. modem line noise characters and, funny spelling mixed case are the three biggest impediments to usability by handicapped people. I would love to have an IDE (to tie into another thread) which would work well with speech recognition. There is already a project (voice coder) which has built a lot of the infrastructure necessary to do so but it (in my opinion) is hampered by the one-way nature of that integration. I believe for handicapped accessibility to programming environments to be truly useful there needs to be a two-way integration where the IDE reveals information about the application so that appropriate grammars and symbols will be revealed and made speakable. ---eric From mail at markus-franz.de Wed Jun 23 09:45:23 2004 From: mail at markus-franz.de (Markus Franz) Date: Wed, 23 Jun 2004 15:45:23 +0200 Subject: asyncore module for loading websites Message-ID: Hi. Some URLs are passed to a python script as command line options like the following command ./script.py http://www.websites1.com http://www.website2.com (The number of passed URLs varies...) Now my problem is: How can I load and show the contents of these websites (from sys.argv) in parallel by using the asyncore module? At the moment I use the following script (it uses one child process for each URL): import sys, os for url in sys.argv[1:]: pid = os.fork() if pid == 0: # placeholder for the loading routine print website_contents break Is the same possible with the asyncore module? Thank you. Markus Franz From glc at well.com Fri Jun 4 12:09:25 2004 From: glc at well.com (Greg Chapman) Date: Fri, 04 Jun 2004 16:09:25 GMT Subject: How to pickle a subclass of tuple? References: Message-ID: On Thu, 03 Jun 2004 19:26:37 +0300, Christos "TZOTZIOY" Georgiou wrote: >__getstate__ is easy: > >def __getstate__(self): > return tuple(self) > >but even > >def __getstate__(self): > return self > >seems to work, as far as Pickle.dump is concerned. The problem is, how >one writes a __setstate__ for an immutable class? You'll probably need to use some of the extended pickle protocol hooks documented here: http://www.python.org/peps/pep-0307.html In particular, you can give your subclass a __reduce__ implementation, which pretty much gives you complete control over how it is pickled and unpickled. --- Greg Chapman From peter at engcorp.com Thu Jun 24 11:00:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jun 2004 11:00:11 -0400 Subject: Delphi extension In-Reply-To: <10dloooa4p9hade@corp.supernews.com> References: <10dloooa4p9hade@corp.supernews.com> Message-ID: Donald L. Dietmeyer wrote: > I was given a libxx.so that was probably written in Delphi. > I need to wrap it so that I can call the functions/procedures > of the library from Python. I tried the usual extension > technique compiling a C file. I don't get anything meaningful > back when I call, so it doesn't work, or I am missing some > critical point. I have spent a good deal of time searching > the net, and found one or two comments about doing the job, > but no evidence that anyone has done it. > > I would appreciate any suggestions or advice. Would ctypes work for you? http://starship.python.net/crew/theller/ctypes/ From t-meyer at ihug.co.nz Mon Jun 28 20:33:29 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 29 Jun 2004 12:33:29 +1200 Subject: Speed of str(positive_integer).. In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1306E931E6@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130467801C@its-xchg4.massey.ac.nz> > I asked myself how much slower would be an integer-positive number to > string convertion function against the default str(). [...] > * It was faster for little numbers, and it seems that with > numbers growing gets worse. > > *Without psyco, my native myconv is slower than str(). I suspect that the psyco version is (under the hood) doing more-or-less the same thing as the C implementation of str() that you're testing against. For small numbers your one beats it because you don't have to do all the other work that str() does (negatives, non-integers, etc), but as the numbers become larger these are less relevant and you get the expected result of implemented-in-C just beating implemented-in-Python-plus-Psyco. > *The thrid test is using divmod() that i thought that would > be faster (i thought it could make only one division and get > both qoutient and remainder, without having to multiply..) > but was worse. It does seem odd that "r,q = divmod(b,c)" is slower than "r = b//c;q = b-r*c" (or "r = b//c;q=b%c", which is better), but timeit shows that it is (with Python 2.3.4). I suppose this is the penalty for the additional work that divmod does with checking signs and so on. > *Also tried that function using lists instead of strings, > but gaves worse results. At least part of this could be due to the fact that it's quite a bit slower (about 2x, with Python 2.3.4, here) to create an empty list than create an empty string (which each version does, respectively). I believe, also (and timeit seems to agree) that the append/join idiom is only better for long strings - here there are up to 7 strings of one character each, in which case simple += is better. BTW, the timeit module is useful for doing these sorts of things. =Tony Meyer From harry.g.george at boeing.com Mon Jun 28 16:25:48 2004 From: harry.g.george at boeing.com (Harry George) Date: Mon, 28 Jun 2004 20:25:48 GMT Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: Christopher T King writes: > On Mon, 28 Jun 2004, Lothar Scholz wrote: > > > Hello i want to write a commerical small tool that must access a MySQL > > database but i can't afford the License Fee for the original MySQL > > driver. In the Ruby world there exist a small but working pure ruby > > library that can be used without buying a license or putting your > > application under the GPL. > > > > Is there anything like this in the Python world ? > > Libraries licensed under the GPL can be used without GPLing the code that > uses them - you only have to GPL any extensions you make to the library. > Assuming that works for you, you can use (GPLed) mysql-python: > http://sourceforge.net/projects/mysql-python/ > Also note that the extensions have to be separate chunks of code, not just derivatives of the original: >From the GPL: "These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. "Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program." -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From ville at spammers.com Sat Jun 19 17:32:44 2004 From: ville at spammers.com (Ville Vainio) Date: 20 Jun 2004 00:32:44 +0300 Subject: can i define a new method at runtime? References: <7b22ae5b.0406181049.479d1a61@posting.google.com> Message-ID: >>>>> "Raoul" == Raoul writes: Raoul> I have a GUI application where I want to assign validation Raoul> methods to controls. Raoul> If my control myTextBox has a change() event for on change Raoul> and I want to make it verify the input is an integer I Raoul> could do... If there is a change method, I assume you need to implement the class yourself. Why not just subclass the root TextBox class and create a IntegerTextBox class that has verifyInteger in the change method? Then you just choose at instantiation time that this particular textbox needs an integer... -- Ville Vainio http://tinyurl.com/2prnb From klapotec at chello.at Mon Jun 21 15:46:42 2004 From: klapotec at chello.at (Christopher Koppler) Date: Mon, 21 Jun 2004 19:46:42 GMT Subject: How to do special encode in string ? References: Message-ID: On 21 Jun 2004 10:14:57 GMT, Duncan Booth wrote: >"fowlertrainer at anonym.hu" wrote in >news:mailman.88.1087811553.454.python-list at python.org: > >> Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" >> >> Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" >> > >>>> s = "az \xe1llam \xe9n vagyok" >>>> print s.decode('latin-1') >az ?llam ?n vagyok >>>> > >You want to use unicode strings if you have characters outside the ASCII >range. The decode method on a byte string will let you convert it to a >unicode string, and the encode method will let you convert it back to byte >string. > >The tricky bit is that you need to know the correct encoding to use as \xe1 >could mean different characters, but in this case it looks as though you >meant latin-1. For Hungarian long umlauts, you'll want to use latin-2 (or iso8859-2). -- Christopher From lard at tardis.ed.ac.molar.uk Tue Jun 29 09:43:55 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 29 Jun 2004 14:43:55 +0100 Subject: urlib - automatic cookie handling Message-ID: <10e2sgtng7f23b2@corp.supernews.com> I'm using urllib to post data to a web form by issuing a command similar to this: filename, headers = urllib.urlretrieve("http://www.thewebsitenamehere.com/servlet/com.blah.bloo.XmlFeed", "content.txt", None, urllib.urlencode({"aParameter": "theValue"})) Now, the problem is that the above fails, since I am not sending a session cookie. Visitors to the web sites' html submission form are sent a session cookie which is given back to the server when they submit a search via the browser, as often happens. Now, I could use urllib to get the form page and read the cookie from the headers that are returned and then manually put that cookie in my submission to the servlet, but my question is: is there a way to tell urllib or some other part of HTTP handling in python that I want to remember any cookie that is given to me, and give it back to that site if I send requests later on? thanks alex From piet at cs.uu.nl Tue Jun 22 21:05:51 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 22 Jun 2004 21:05:51 -0400 Subject: Howto use email module and write the get_payload to a file References: Message-ID: >>>>> chuck amadi (CA) wrote: CA> Hi I have managed to print the output of the get_payload to screen CA> but I need to write to a file as I only require the email body messages CA> from the mailbox.My script using the fp.readlines() function writes the CA> entire contents of the mailbox of cause including the headers of the CA> emails I do not want. CA> mailout = file("/home/chucka/pythonScript/SurveyResults1.txt","r") If you open the file with "r" you can't write to it. CA> fp = open("/var/spool/mail/chucka") CA> mb = mailbox.UnixMailbox(fp, email.message_from_file) CA> for bmsg in mb: CA> bmsg = get_payload() You use bmsg for two purposes: as the iteration variable, and to get the payload. Moreover get_payload is a method and hence needs an object. for bmsg in mb: msgb = bmsg.get_payload() mailout.write(msgb) But that doesn't take into account that the payload will be a list when the message is multipart. In that case you need some more elaborate code like: def writebody(mailout, msg): payld = msg.get_payload() if msg.is_multipart(): for m in payld: writebody(mailout, m) else: mailout.write(payld) for bmsg in mb: writebody(mailout, bmsg) print "mailbox file copied...to SurveyResults.txt" -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From grahamd at dscpl.com.au Tue Jun 15 03:05:41 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 15 Jun 2004 00:05:41 -0700 Subject: Finding Function Args? References: Message-ID: "Mike C. Fletcher" wrote in message news:... > Check the standard module inspect, particularly; > > >>> import inspect > >>> import cgi > >>> inspect.getargspec( cgi.escape ) > (['s', 'quote'], None, None, (None,)) Also: cgi.escape.func_code.co_argcount Should yield: 2 Lots of func stuff should be visible when dir() is used. You just need to work out what is where. >>> dir(cgi.escape) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> dir(cgi.escape.func_code) ['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] Similar thing for class methods and callable objects if you know where to look. >>> dir(A.__init__.im_func) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> dir(A(1).__call__.im_func) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] Obviously, the "inspect" module is mean't to hide to a degree all this stuff, but still sometimes easier to access it directly. From peter at engcorp.com Thu Jun 10 09:50:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jun 2004 09:50:31 -0400 Subject: Newbie Copy Question In-Reply-To: <10cfke2cvs2icfa@corp.supernews.com> References: <-oadnfi_sdy3UVrdRVn-hw@powergate.ca> <10cfke2cvs2icfa@corp.supernews.com> Message-ID: Michael Geary wrote: > Peter Hansen wrote: >>Windows is almost never (ever?) case-sensitive, though it does >>tend to preserve the case of filenames (sometimes, when it >>wants to). Unless the jump drive is somehow case-sensitive, >>I doubt this was the problem. > > This depends on the filesystem, but all of the filesystems in common use on > Windows are case-preserving (all of the time, not just when Windows "wants > to" ) and case-insensitive. You're right... I was confusing myself because of the behaviour of Windows Explorer, where it will magically change the appearance of filenames that are ALLCAPS depending on the setting of some flag. It's not really changing the name, just how it's displayed, and it's not a filesystem thing anyway, as you say. -Peter From tjreedy at udel.edu Sat Jun 12 13:03:10 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jun 2004 13:03:10 -0400 Subject: kid wants to know more about color on the screen References: Message-ID: "Doug Mitchell" wrote in message news:FMCyc.61975$8k4.1338501 at news20.bellglobal.com... > Dear Group, > > My son who is in grade 7 has *just* started going through the book "Python > for the Absolute Beginner" by Michael Dawson. He and I have no programming > experience. He is beginning this on an old win 95 computer with Python 2.2 I > think. Congratulations to both of you. > He is getting a bit frustrated with color coding. This is a post-beginner subject that I think would best be skipped for now. But I know, kids like color as much or even more than adults. > For example in Chapter 2 page 18 and 19 Mr. Dawson describes a more fancy > way of printing "Game Over" on the screen. According to *him*... > > When I type the command: print "Program 'Game Over' 2.0" > print \ > > Instead of getting the second "print" to turn orange, like it's supposed to > when you type in a command, it just stays black. And when its time to > actually run the program, Python just prints out Program Game Over 2.0 > instead of the fancy large text like that is shown in the book. I've have never seen the book so I can only give comments similar to Harr's. Standard Python by itself knows nothing of colors and fonts. The print statement sends characters to the the file stream called stdout (for standard output) which usually goes the the terminal and appears in whatever font and color the terminal is set to. So Dawson had to specify something extra to get extra control. > Later on he says that strings within quotes will be green as expected and > then all of a sudden on the next line it will stay black :(. And when he > does a run script there will be a syntax error as Python wont recognize this > 'black' string but then on another occasion the 'black' will run ok :(. Some program editors do something extra to get different portions of the program displayed in different colors so the programmer can pick them out m ore easily. In the one 'he' (Dawson or your son?) used, string literals are apparently green. String literals denoted by a ' ' pair or a " " pair may not contain a newline (carriage return to you probably), which is to say, cannot continue across more than one line. So, if one types: text = "Something to display when the monster dies" the editor might turn 'Something to display' green, but if it knows about Python, it will leave 'when the monster dies' black because it cannot be part of the string on the previous line. The black rather than green says that something is wrong, and when you try to execute the above, Python says SyntaxError. Terry J. Reedy From JSmuts at clover.co.za Fri Jun 25 05:28:01 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Fri, 25 Jun 2004 11:28:01 +0200 Subject: win XP + wxPython + py2exe Message-ID: Hello Olivier I don't really touch XP but in the py2exe samples advanced sample directory you will find this in setup.py # A program using wxPython # The manifest will be inserted as resource into test_wx.exe. This # gives the controls the Windows XP appearance (if run on XP ;-) # # Another option would be to store it in a file named # test_wx.exe.manifest, and copy it with the data_files option into # the dist-dir. # and so forth, I suspect you will find your solution there jaco Olivier Thiery Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 06/25/2004 11:17 AM Please respond to olivierthiery To: python-list at python.org cc: Subject: win XP + wxPython + py2exe Hello, I've ported a software I've developped from win 2k to win xp and something I wouldn't have expected happened. If I simply run the py files, the software uses the current xp skin looknfeel, but if I compile it using py2exe it looks like any ugly standard grey win2k app. Does anybody know why and how it can be fixed ? Thanks a lot, Olivier -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Jun 23 16:47:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 16:47:45 -0400 Subject: Encryption with Python In-Reply-To: <889cbba0.0406231156.115b743a@posting.google.com> References: <889cbba0.0406221926.3f4e5776@posting.google.com> <889cbba0.0406231156.115b743a@posting.google.com> Message-ID: Kamilche wrote: > Peter Hansen wrote in message news:... >>Besides, what you say is not possible. > > But I DON'T manipulate the data byte by byte, only the encryption > tables. [snip code] Very interesting use of translate. I doubt anyone, certainly not I, guessed that's what you were using. Kudos! (though it certainly fits your description of "not secure", but it's admittedly a step up from XOR). -Peter From haim at babysnakes.org Mon Jun 28 05:31:57 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Mon, 28 Jun 2004 12:31:57 +0300 Subject: sending signals to the calling function References: Message-ID: On Mon, 28 Jun 2004 12:14:29 +0300, Haim Ashkenazi wrote: > Hi > > I have a function that receive a list of files and creates a zip from > these files. I want it to send signal to the calling function with the > name of the file it currently compressing. is there a way to do this > (without threads)? Hi, again... here's a more detailed description: at the moment, the function looks like this: def CreateZip(self): bakFile = 'data_backup_NS.zip' print "\nCompressing your data...\n" myZip = zipfile.ZipFile(bakFile, 'w', zipfile.ZIP_DEFLATED) for file in self.FinalList: print "adding", file, "..." # zip doesn't support unicode if isinstance(file, unicode): myZip.write(file.encode('mbcs')) #good for windows else: myZip.write(file) myZip.close() it works fine when called from a console application, but now I want it to be called from a wxwindows gui also (and redirect the output to a wxScrolledMessageDialog). if there isn't a way to "signal" the calling function, is there a way to redirect the output of the function (it's running on windows)? thanx -- Haim From daniel at syrinx.net Mon Jun 21 06:49:47 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Mon, 21 Jun 2004 06:49:47 -0400 Subject: Templating engine? In-Reply-To: <69cbbef2.0406201036.53506906@posting.google.com> References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <69cbbef2.0406201036.53506906@posting.google.com> Message-ID: <2jnslaF121d5gU1@uni-berlin.de> has wrote: > PyMeld, Nevow.renderer and HTMLTemplate all provide complete > separation of business and presentation logic from HTML markup. These > support desktop application-style MVC, where GUI widget classes (View) > are separated from the code that controls them (Controller).* > > Also, because they're designed specifically for templating, they > should also be a lot simpler and easier to use than generic DOM > systems such as ElementTree. > Who said ElementTree was a generic DOM system? In fact it's not. It /is/ hierarchical, but doesn't use any DOM API I know of. From the ElementTree web site: The Element type is a simple but flexible container object, designed to store hierarchical data structures, such as simplified XML infosets, in memory. The element type can be described as a cross between a Python list and a Python dictionary. ElementTree has *very* primitive support for XPath, which we easily extended to support lookup on ID. With this in place (literally no more than 20 LOC) ElementTree is a usable system which allows us to achieve the complete separation we were looking for. Admittedly, the just-in-time lookup on IDs is less than ideal. Better would be a system which cached the elements containing IDs in a dictionary on parsing the document. I believe this was the reason Mr. Hansen and I decided to write our own system back about a year ago. Of course, that was in another life... Daniel Ellison From tjreedy at udel.edu Thu Jun 3 13:05:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jun 2004 13:05:47 -0400 Subject: Error in small code References: <200406030454.i534sbQ10955@mailweb05.ibest.com.br> Message-ID: wrote in message news:200406030454.i534sbQ10955 at mailweb05.ibest.com.br... > def cell_click(event): > if (event.widget["text"] == " "): > if (pturn == 1): > event.widget["text"] = marks[1] > pturn = 0 > else: > event.widget["text"] = marks[0] > pturn = 1 As the ref manual says someplace, a variable potentially assigned a value (ie, it is the target of an assignment statement) *anywhere* in a function is local unless declared global. Function compilation is two pass: 1) categorize names; 2) generate byte code. Terry J. Reedy From ahaas at airmail.net Tue Jun 15 14:16:45 2004 From: ahaas at airmail.net (Art Haas) Date: Tue, 15 Jun 2004 13:16:45 -0500 Subject: [ANNOUNCE] Fifteenth release of PythonCAD now available Message-ID: <20040615181645.GD3093@artsapartment.org> I'm pleased to announce the fifteenth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or Python 2.3. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The fifteenth release of PythonCAD offers users on Mac OS X a native, Cocoa based interface utilizing the Python/Objective-C bridge. The Python/Objective-C code is available at http://pyobjc.sf.net/. A nice side benefit from the development of the Cocoa code was the exposure of various bugs and design issues in the interface neutral code. Bugs exposed by this work have been fixed, and several design improvements are now in the code thanks to this work. The Cocoa interface code is contributed by David Haas, and I thank him greatly for his work. This release includes several more undo/redo improvements. The addition and removal of points on a polyline can now be undone or redone, and assorted other editing operations have improved undo/redo handling as well. A variety of bug fixes have also been added in this release. Small bugs regarding entity searching, arc boundaries, layer addition and removal, and entity storage have been fixed. A few code improvements appear in this release also. The mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From zebez at home.se Fri Jun 11 05:59:22 2004 From: zebez at home.se (zebez) Date: 11 Jun 2004 02:59:22 -0700 Subject: Does a Python Sound Library exist? References: Message-ID: gohaku wrote in message news:... > Hi everyone, > I would like to know if there is a sound library for manipulating and > retrieving information from .WAV or .MP3 Files. > I came across the page for Pythonware Sound Toolkit but that toolkit is > no longer available. > > Thanks in advance. > -gohaku I don't know if this is what your looking for but it's a python wrapper for fmod (http://www.fmod.org/): http://sourceforge.net/project/showfiles.php?group_id=65529&package_id=88928 though it hasn't been updated for almost a year. From aahz at pythoncraft.com Mon Jun 21 11:04:33 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Jun 2004 11:04:33 -0400 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: In article , Rene Pijlman wrote: >Aahz: >> >>If you're already doing req.write(), it'll be easy to shift to Quixote. > >The question is: is this irony or sarcasm? :-) Neither: If your focus is already on programmatic control of HTML output, Quixote seems a natural extension of that paradigm. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From hungjunglu at yahoo.com Sun Jun 20 12:27:54 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Jun 2004 09:27:54 -0700 Subject: can i define a new method at runtime? References: <7b22ae5b.0406181049.479d1a61@posting.google.com> Message-ID: <8ef9bea6.0406200827.178f9015@posting.google.com> Ville Vainio wrote: > If there is a change method, I assume you need to implement the class > yourself. Why not just subclass the root TextBox class and create a > IntegerTextBox class that has verifyInteger in the change method? Then > you just choose at instantiation time that this particular textbox > needs an integer... This is OK if there are only a few types of boxes. But entry data types are features, and they tend to grow and become complicated, even if Regex (regular expression) patterns were used. Besides, the verification logic is a conceptual unit on its own right, so according to the AOP (aspect-oriented programming) philosophy, it's best to group the verification methods together in some "aspect class". There may be new dimensions to the problem that one may not have foreseen at the time of design. For instance, localization (currency, dates, usage of commas and periods, ZIP codes, etc.) Having verification code in its own hierarchy allows you to make changes more easily and take advantage of class inheritance for code re-use. Once you have the verification logic done, you hook it to the widget objects somehow. In Python, this usually involves some form of metaprogramming. There are too many ways to do it, and you'll probably not find two people doing it the same way. Some tools in the arsenal are: using functions/methods as first class objects and assign them or tweak them to your heart's content, using the "new" module, using code objects and "exec" statements, tweaking an existing object's __class__ attribute, implementing/overriding the __getattr__() method in classes, metaclasses, etc. etc. regards, Hung Jung From bostjan.jerko at mf.uni-lj.si Wed Jun 2 07:08:43 2004 From: bostjan.jerko at mf.uni-lj.si (=?iso-8859-2?q?Bo=B9tjan_Jerko?=) Date: Wed, 02 Jun 2004 13:08:43 +0200 Subject: swig and list in python Message-ID: <87pt8i1akk.fsf@bostjan-pc.mf.uni-lj.si> Hello ! Can somebody tell me how can I access python's list from C program using swig. B. From panard at inzenet.org Sat Jun 19 06:41:58 2004 From: panard at inzenet.org (Panard) Date: Sat, 19 Jun 2004 12:41:58 +0200 Subject: strange behaviour with remove Message-ID: <40d41877$0$32493$626a14ce@news.free.fr> Hi! Can anyone explain this to me : $ cat test.py l = [ 1, 2, 3 ] d = { 'list' : l } for x in l : print "rm", x d[ 'list' ].remove( x ) print "l =", l print d $ python test.py rm 1 l = [2, 3] rm 3 l = [2] {'list': [2]} Why 2 isn't removed ? and why l is changing during the loop ?? Am I missing something ? My python is 2.3.4 Thanks -- Panard From tismer at stackless.com Fri Jun 25 20:41:54 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 26 Jun 2004 02:41:54 +0200 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: Message-ID: <40DCC652.2020302@stackless.com> Mark Hahn wrote: ... > 2) Evaluate the default expression once at each call time when the default > value is needed. The default expression would be evaluated in the context > of the function definition (like a closure). > Comments? How much Python code would these different proposals break? I think not so very much. The default mutable parameters have been abused to keep class-like state. Default parameters in general have also been used to speed up object lookup on certain speed contests. Both usages are obsolete, since the same effect can be achieved with a local function sitting in a scope, from where it can use mutables it it needs to. So I don't see many remaining advantages, and I think it is a good idea to make the defaults less sticky. +1 for 2) ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From heikowu at ceosg.de Fri Jun 4 06:28:58 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Fri, 4 Jun 2004 12:28:58 +0200 Subject: Python reference In-Reply-To: References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: <200406041228.58796.heikowu@ceosg.de> Am Freitag, 4. Juni 2004 11:18 schrieb flupke: > I don't agree. The online reference of Php is far easier to search than the > Python > reference. There's no excuse for not having a decent search function. > period. > That's what i hate about the Java docs too. No search capability. > Php doc rocks because of that (at least for me :) ) Searching in the Python documentation (or rather on the website): 1) Open www.google.com 2) Enter: site:www.python.org 3) Look at the results. ;) Heiko. From bh at intevation.de Wed Jun 9 07:58:01 2004 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 09 Jun 2004 13:58:01 +0200 Subject: Destructors and exceptions References: <5155aad2.0406090320.38977fac@posting.google.com> Message-ID: kveretennicov at yahoo.com (Konstantin Veretennicov) writes: > "Humpty Dumpty" wrote in message news:... >> >> I agree, it is a real pitty that Python doesn't have a way of doing what you >> mention, other than try-finally, which makes code more difficult to read. A >> new specifier, e.g. "scoped", would be a required addtion to Python: >> interpreter would garantee that __del__ of scoped objects would be called on >> scope exit, and raise an exception if attempt to alias. >> > > Is there a PEP or something for "scoped specifier"? http://python.org/peps/pep-0310.html Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From conor_j_kavanagh at yahoo.co.uk Sun Jun 6 05:55:57 2004 From: conor_j_kavanagh at yahoo.co.uk (Conor Kavanagh) Date: Sun, 06 Jun 2004 10:55:57 +0100 Subject: My python pacman program will not initialise Message-ID: I have written a livewires package pacman game, but the maze window will not load, do you have any suggestions,(the program is attached to this e-mail). -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ -------------- next part -------------- A non-text attachment was scrubbed... Name: my python.py Type: application/octet-stream Size: 3263 bytes Desc: not available URL: From Scott.Daniels at Acm.Org Fri Jun 25 18:15:25 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 25 Jun 2004 15:15:25 -0700 Subject: accumulators In-Reply-To: <7xn038u34y.fsf@ruckus.brouhaha.com> References: <7xn038u34y.fsf@ruckus.brouhaha.com> Message-ID: <40dca8ec$1@nntp0.pdx.net> Paul Rubin wrote: > ... The Pythonic way to do it is with a class instance: > > class accum: > def __init__(self, n): > self.s = n > def __call__(self, i): > self.s += i > return self.s > > a = accum(3) > (etc.) > > however, for programmers comfortable with the Lisp idioms of using > internal lambdas, the class/object approach is cumbersome. The way I'd do it is: class accum: def __init__(self, start): self.runningtotal = start def increment(self, value): self.runningtotal += value return self.runningtotal a = accum(3).increment Then you can use: a(3) ... That is, avoid magic names unless needed, and make the names obvious. -- -Scott David Daniels Scott.Daniels at Acm.Org From donn at u.washington.edu Thu Jun 17 12:58:30 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 17 Jun 2004 09:58:30 -0700 Subject: does python have useless destructors? References: Message-ID: In article , Michael Hudson wrote: > Donn Cave writes: > > In article , > > Michael Hudson wrote: > > > Manlio Perillo writes: > > ... > > > > Since __del__ isn't really 'useful', *maybe* a better solution is to > > > > add another special method for classes, ad example a __finalize__ > > > > method. > > > > > > Yes! I'm not sure __finalize__ is really the best name, but that's > > > for another day. > > > > Couldn't the name be __del__? > > As I think I said in one of the emails in the thread linked to from > PEP 310, life would be much easier if it wasn't. > > > Given the opportunity to have both, and the assurance that > > __finalize__ will be called and __del__ might not, what > > functionality would you leave in __del__? > > None at all! This is my cunning plan... You're too deep for me. > > > I would urge everyone participating in this thread to read PEP 310, > > > the email conversation linked therein and (optional) *understand* it. > > > > It seems to be superficially similar to finalization, > > OK, I've found this thread pretty hard to follow. What is > "finalization" in context? Operational definition would be `call __del__ or its C equivalent', at the effective end of the object's lifetime. That's the way I understand it - notify object that its time is up, let it do its final things. Donn Cave, donn at u.washington.edu From mwilson at the-wire.com Sat Jun 5 20:25:52 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 05 Jun 2004 20:25:52 -0400 Subject: Why did no one invent Python before? References: <40BE621C.97EEC2AA@alcyone.com> <10bu9k8evp5o25c@corp.supernews.com> Message-ID: In article , "Terry Reedy" wrote: > >"Cameron Laird" wrote in message >news:10bu9k8evp5o25c at corp.supernews.com... >I see Python as a or even the successor to Basic, which was invented over >40 years ago. It was the first 'computer programming for everybody' (CP4E) >language. Basic took off in the late 70s with the invention of >microcomputers and the Microsoft port thereto. Its limitations were >apparent by the mid 80s and so Guido invented/developed a new CP4E >language. C++ / Python == FORTRAN / BASIC Regards. Mel. From eltronic at juno.com Sun Jun 13 16:11:14 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Sun, 13 Jun 2004 16:11:14 -0400 Subject: Finding "hidden" syntax errors Message-ID: <20040613.161120.-305363.1.eltronic@juno.com> On Fri, 11 Jun 2004 13:03:38 -0500 "Larry Bates writes: > It doesn't happen often, but once in a while I will > introduce a syntax error into a Python program I'm > working on (in IDLE) and doing File-Check responds > with the expected "Failed to check, syntax error - > invalid syntax". The problem is where the cursor > stops is perfectly legal syntax. I then begin > going through the laborious job of cutting out > pieces of the code until I find what is wrong. interesting how few are willing to share their secrets on this most time consuming with little intrinsic reward subject. it is the weekend. errors do show you what you think you know. adding a line, commenting out lines, triple quoting out lines. cutting out lines before and after. anything to get rid of the syntax error. at times like this, people may revert to a previous favorite more native language. or they might even search to see if anyone has posted some python to do the same task. it may be hard to justify spending another hour debugging a script to replace a perl one liner with a dubious use case. must you continue? save the file and get a hex view or dump. mixing tabs and spaces can have this symptom. sometimes the error pointer is at the top of the error containing block, sometimes at the bottom. python version is going to be a factor. latest is better. running python -tt your.py outside the IDE. if only to verify the IDE not a contributing factor. compare linenumber's in more than one editor. always blame the tools last or never. it is your fault! you must accept the facts. but it doesn't hurt to perform a reality check. use reindent and tabnanny in Tools/Scripts hopefully Idle has some way to add these as menu commands to run on the script buffer. after a paste of code, in a texteditor that wraps you may line up the indentation not realizing it's a line continued. many editors have a show control codes option. blank lines can be suspect as they might have an odd number of tabs or spaces. missing colon ':' in for, def, if, elif, else, class misspelling an identifyer. usually with these the error pointer will be accurate. forgetting 'pass' statement, needed if you comment out the only live statements in a try/except or if/else block shadowing builtin names str, dict, file, list are popular, until a few lines later you try to use the function. turn a section of code into a function or method, this will often expose a dependance on a global that is wrecking havoc. rearrange the code in anycase to move the error. if 1: and indent a bunch of lines. a bad insinct at this point would be to continue refactoring without being able to test the program! at the first sign of deep trouble you should begin to save copies to document the problem. too long between runs of the code so its hard to piece together when and where the error might have been introduced, incomplete test coverage. no incremental backup so there is no previous working file to compare to. occasionally save or add it to a zip in a dated directory. or use one of the source control technologies. cvs, svn. note, this only works if you remember or its automatic. editing is the leading cause of errors. if you don't find an anomaly every 15 minutes or every 100 lines, your not really trying hard enough. its entirely possibly the current algorithm will be superseded by further research anyway, why wait. don't sweat the small stuff. rip out the offending code and substitute some black box data returned by a stub and press on. e please forward all spam to uce at ftc.gov ________________________________________________________________ The best thing to hit the Internet in years - Juno SpeedBand! Surf the Web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From davidf at sjsoft.com Mon Jun 14 11:00:33 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 14 Jun 2004 17:00:33 +0200 Subject: python+py2exe+pygame licensing ? In-Reply-To: References: Message-ID: Andrea Griffini wrote: > On Sat, 12 Jun 2004 18:11:01 -0400, "Chris S." > wrote: > > >>Since Python byte-code can be decompiled, I'm not sure how >>"closed-source" you could make a Python program. > > > Legally closed source is one thing, technically closed > source is another. Anyway I was wondering that if there > is anything in the license that *forces* me to put an > easily re-usable source code the impression on the > management could be quite worse. > > If I can distribute a copyrighted compiled-only version, > and take you to a court if I discover that you used > part of it then things are different. The fact that > there are decompilers around that can take the compiled > version a produce a very good source version is not central. > I've found even someone that sells this as a *service* on > the net (it's not for cracking or illegal inspection, > it's in case you lost the source code of your programs... > of course :-) ). > > That anthing of this is important from a pratical point > of view is quite questionable; but I'm talking about > explaining to management that python is an interesting > alternative for more than internal prototyping... Exactly the point. We have a patch to distutils that lets you build an installer with only cmopiled files (no source) to do this very thing. See the following: https://sourceforge.net/tracker/?func=detail&atid=355470&aid=793069&group_id=5470 > This is something that always puzzled me. If I include > an LGPL'ed part and a new version of that part is not > 100% interface-compatible with an old one (as sometimes > happens with specific libraries), am I forced to allow > my clients to adapt to the new version ? Am I forced > to provide upgrades forever ? > > When I first read the LGPL, my impression was that it > was suited more for incredibly stable libraries (at > least stable at the interface level). For example the > standard C library... > > But english legalese is not my natural language... :-) I think as long as you 1) release the source code to the LGPL'ed part and 2) allow people to substitute in a different library (with Python that's easy) you will be safe with no problems... Whether the original library will work with your game is not an issue, as long as people have the ability to substitute in a modified library David From opengeometry at yahoo.ca Tue Jun 8 16:16:07 2004 From: opengeometry at yahoo.ca (William Park) Date: 8 Jun 2004 20:16:07 GMT Subject: [python] Is there a python written fax program out there? References: Message-ID: <2iml46Fomrm7U1@uni-berlin.de> David Stockwell wrote: > Hi, > > Today I was in a meeting and someone mentioned they were looking for some > software whereby they could run their own fax server (ie a computer with a > modem, someone sends a fax, and the software convertes it to an image and > drops it in an email box). > > I'm posting this here incase someone happens to know of a python > implementation or other language implementation that is either free or for > sale? If so, I'd like to know where to get them. > > Thanks Efax. You can use Python to call it. Search Freshmeat.net for exact URL. -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From jimka at rdrop.com Fri Jun 11 10:39:23 2004 From: jimka at rdrop.com (Jim Newton) Date: Fri, 11 Jun 2004 16:39:23 +0200 Subject: if does not evaluate In-Reply-To: References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> <2ituufFrgqhaU1@uni-berlin.de> Message-ID: <2iu1ooFrcu2hU1@uni-berlin.de> ah so i must encapsulate the predicate function in another named function which uses yield in order to have the iteration abort when the target item is reached? can i simply put the predicate function inside a lambda? -jim Peter Otten wrote: > Jim Newton wrote: > > >>sorry, i do not understand. The python syntax is a bit >>difficult for me. > > > Maybe I obscured the issue by comparing name attributes to a string instead > of using a predicate() function. > > >>if i have a list x and a function f how do i know if >>there is an element of x on which f returns something >>other than False? > > > Using the above identifiers, let's assume we are looking for a name starting > with "M": > > >>>>x = ["Peter", "Paul", "Mary", "Jane"] >>>>def f(o): > > ... print "checking", o > ... return o.startswith("M") > ... > > If we call > > >>>>map(f, x) > > checking Peter > checking Paul > checking Mary > checking Jane > [False, False, True, False] > > it invokes f() for every item in x and returns the above list of booleans. > The equivalent list comprehension would be [f(i) for i in x]. Now > > >>>>True in map(f, x) > > checking Peter > checking Paul > checking Mary > checking Jane > True > > gives the correct result but unfortunately does too much work as we don't > need to calculate f("Jane") when we already know the outcome. Enter > generator > > >>>>def lazymap(predicate, seq): > > ... for item in seq: > ... yield predicate(item) > ... > > which calulates f(item) as needed. Proof: > > >>>>True in lazymap(f, x) > > checking Peter > checking Paul > checking Mary > True > > > itertools.imap() is just the fast C implementation of lazymap(). > The equivalent generator expression (new in Python 2.4) will be > (f(i) for i in x). > > Peter > From JSmuts at clover.co.za Thu Jun 10 08:34:48 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Thu, 10 Jun 2004 14:34:48 +0200 Subject: python and microsoft visio Message-ID: Hello there I am about to embark on a excersize using -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.com Fri Jun 18 10:10:40 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 18 Jun 2004 14:10:40 -0000 Subject: OT: Chat server References: <8ef9bea6.0406170749.399c4956@posting.google.com> Message-ID: <10d5tv08jqund2@corp.supernews.com> In article <8ef9bea6.0406170749.399c4956 at posting.google.com>, Hung Jung Lu wrote: >"Miki Tebeka" wrote: >> I'm looking for a chat (IRC) server. . . . >developers. Yes, there are two books out there, but I've been told >they are not good. There are thousands of Jabber developers out there, . [sociologic comments I find on-target, al- though incomplete] . . Hung Jung, please be more specific about the defects of the books. I know of four different ones, and I mildly favored one in . If it has defects I overlooked, I want to know, so as not to mislead readers or Miki. I've sure appreciated the technical content of your follow-ups, by the way. -- Cameron Laird Business: http://www.Phaseit.net From insert at spam.here Fri Jun 25 18:51:58 2004 From: insert at spam.here (Doug Holton) Date: Fri, 25 Jun 2004 17:51:58 -0500 Subject: any trick to allow anonymous code blocks in python? Message-ID: Is there any metaclass trick or something similar to allow anonymous code blocks? I'd like to be able to let users do something like this fictitious example: b = Button() b.OnClick =: print "you clicked me" But that would require adding a special "=:" operator to bind a code block to a function. Is there any PEP for something like that? I see 310 might allow: b=Button() with b.OnClick: print "you clicked me" I know I can already do it like these examples: def OnClick(self,event): print "you clicked me" b.OnClick = OnClick or b = Button(OnClick=OnClick) or subclassing Button. From peter at engcorp.com Tue Jun 29 15:47:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 15:47:35 -0400 Subject: threading In-Reply-To: References: Message-ID: jesso1607 at rogers.com wrote: > I want to get results from a thread from the main thread. In C I would use pthread_join to wait for the thread and access the result in a paramter I passed to pthread_join. > > In python I can wait with join, but how would you get a result from the thread? I would always subclass the thread, as shown below, and then just grab the result directly: class ThreadWithResult(threading.Thread): def __init__(self, *pargs, **kwargs) threading.Thread.__init__(self, *pargs, **kwargs) self.result = None def run(self): # do my stuff here that generates results self.result = # the results # and now the thread exits In the main thread, you would: subThread = ThreadWithResult() subThread.start() subThread.join() result = subThread.result # create a subThread.getResult() method if you don't like direct access -Peter From MAIL-SA at gcc-sg.org Sun Jun 27 23:18:14 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Mon, 28 Jun 2004 06:18:14 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F65092676@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = phk at login.dkuug.dk Recipient(s) = python-list at python.org; Subject = ?do0?i4grjj40j09gjijgp?d? Scanning Time = 06/28/2004 06:18:14 Engine/Pattern = 7.000-1004/919 Action on message: The attachment id04009.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From agriff at tin.it Tue Jun 1 17:28:35 2004 From: agriff at tin.it (Andrea Griffini) Date: Tue, 01 Jun 2004 21:28:35 GMT Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> <40BCCDFB.3AC44CF9@alcyone.com> Message-ID: <82tpb0h3ncsjv6tuatrvblm086epl8c7f3@4ax.com> On Tue, 01 Jun 2004 11:42:03 -0700, Erik Max Francis wrote: >Yes. And if a were declared > > static const int a = 3; > >it would be illegal. That is the case that I was discussing. I completely missed the original poster point. Re-reading it indeed the literals could be in read-only memory, and the pointers to those literals could be too (if declared const). Sorry for all the nonsense babbling I posted... Andrea From hamilcar at never.mind Fri Jun 4 02:32:52 2004 From: hamilcar at never.mind (Hamilcar Barca) Date: Fri, 04 Jun 2004 00:32:52 -0600 Subject: Why did no one invent Python before? References: Message-ID: <20040604023243.448$HD@news.newsreader.com> In article (Thu, 03 Jun 2004 07:18:25 -0700), j_mckitrick wrote: > I keep hearing about this Smalltalk IDE. What is really the big deal, It's really, actually integrated. Plus, Smalltalk is a language with a simple syntax. > I also applied for a demo download, but never heard back > from the company. http://www.squeak.org/ From a at a.invalid Thu Jun 3 14:19:40 2004 From: a at a.invalid (Timo Virkkala) Date: Thu, 03 Jun 2004 18:19:40 GMT Subject: Python reference In-Reply-To: <2i96n6Fklj78U2@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> Message-ID: <0ZJvc.329$kX2.323@read3.inet.fi> Reiner Block wrote: > does anybody knows a really good Python reference? It is not the matter if it > is online or a book, if it is in english or german. Because the official one > from www.python.org is really bad. :-( It would be very helpful if you could elaborate on why you think the official one is bad. It's very easy to improve on something, if one knows what's wrong with it. I've always managed pretty well with the tutorial and the library reference on the official site. If there's something there I don't quite understand, I either ask here, or take a quick look at the sources. -- WT From htx1 at gmx.de Sun Jun 6 05:13:02 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Sun, 06 Jun 2004 11:13:02 +0200 Subject: if does not evaluate In-Reply-To: References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: Tor Iver Wilhelmsen wrote: > Jim Newton writes: > > >>I.e., x = if something: >> expr1 >> else: >> expr2 > > > Try exploiting that a boolean expression evaluates to 0 or 1: > > x = (expr1, expr2)[something]; This is eagerly evaluated. If only one expression is meant to be evaluated, the whole thing should look like this: x = (lambda: expr1, lambda: expr2)[bool(something)]() I added bool() to allow tests returning other values than 0 or 1. Greetings, Holger From doNOSPAMnut at dakotaANTISPAMcom.net Sun Jun 6 21:13:05 2004 From: doNOSPAMnut at dakotaANTISPAMcom.net (Matthew Mueller) Date: Sun, 06 Jun 2004 18:13:05 -0700 Subject: file.encoding doesn't apply to file.write? Message-ID: I noticed in python2.3 printing unicode to an appropriate terminal actually works. But using sys.stdout.write doesn't. Ex: Python 2.3.4 (#2, May 29 2004, 03:31:27) [GCC 3.3.3 (Debian 20040417)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> sys.stdout.encoding 'UTF-8' >>> u=u'\u3053\u3093\u306b\u3061\u308f' >>> print u ????? >>> sys.stdout.write(u) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) The file object docs say: "encoding The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. ..." Which indicates to me that it is supposed to work. Of course, I could use print >>fileobj, but that is ugly ;) -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From jepler at unpythonic.net Sat Jun 12 21:29:43 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 12 Jun 2004 20:29:43 -0500 Subject: Unbind initial bind on basic widget (text) In-Reply-To: References: Message-ID: <20040613012942.GA10235@unpythonic.net> You should probably read the Tk manpage on the bind and bindtags commands. If you want to get rid of all the normal bindings for a Text widget, you can just do something like tags = myText.bindtags() tags.remove("Text") myText.bindtags(tags) If you want to stop only certain bindings, use the "break" technique mentioned in another response to your post. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From hungjunglu at yahoo.com Sun Jun 6 11:18:57 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 6 Jun 2004 08:18:57 -0700 Subject: exec throws an exception...why? References: <3415c0lg306oec1a69c3mkolnbhfbku243@4ax.com> Message-ID: <8ef9bea6.0406060718.39f1001b@posting.google.com> nicksjacobson at yahoo.com (Nick Jacobson) wrote: > > Now, why it puts 'x' in local, I don't know. > > I don't know either, that's why I asked ;) The name binding in assignment seems to proceed only for locals, unless a variable is declared as global explicitly. That is, by default, the supplied global dictionary is read-only, unless the 'global' statment is used explicitly for those variables that you want to override. Think of this behavior as if the code defined in the s string were executed inside another nameless function. #--------------- try this first in console s=''' x = 1 def f(): print 'globals', globals().keys() print 'locals', locals().keys() print x print 'globals', globals().keys() print 'locals', locals().keys() f() ''' d={} e={} a = compile(s, '', 'exec') exec a in d, e #--------------- output globals ['__builtins__'] locals ['x', 'f'] globals ['__builtins__'] locals [] Traceback (most recent call last): File "", line 1, in ? File "", line 9, in ? File "", line 6, in f NameError: global name 'x' is not defined #--------------- now try this in console s=''' global x x = 1 def f(): print 'globals', globals().keys() print 'locals', locals().keys() print x print 'globals', globals().keys() print 'locals', locals().keys() f() ''' d={} e={} a = compile(s, '', 'exec') exec a in d, e #--------------- output globals ['__builtins__', 'x'] locals ['f'] globals ['__builtins__', 'x'] locals [] #--------------- also try this from fresh console s=''' x = 1 def f(): print 'globals', globals().keys() print 'locals', locals().keys() print x print 'globals', globals().keys() print 'locals', locals().keys() f() ''' a = compile(s, '', 'exec') exec a #--------------- output globals ['a', 's', 'x', '__builtins__', '__name__', 'f', '__doc__'] locals ['a', 's', 'x', '__builtins__', '__name__', 'f', '__doc__'] globals ['a', 's', 'x', '__builtins__', '__name__', 'f', '__doc__'] locals [] 1 ------------------------------------------- Therefore, when no dictionary is supplied, it works because it uses the current globals() and locals() of the current scope, which in the case of console or module level (i.e., zero indentation) are referring to the same dictionary. The assignment 'x=1' was performed on the locals() dictionary for writing. But inside the f() function, the statement 'print x' pulls the value from the globals() dictionary. This coincidence of two dictionaries only happens when you run the code from the module level. If you put the above code inside a function, it won't work. #--------------- from a fresh console def test(): s=''' x = 1 def f(): print 'globals', globals().keys() print 'locals', locals().keys() print x print 'globals', globals().keys() print 'locals', locals().keys() f() ''' a = compile(s, '', 'exec') exec a test() #--------------- output globals ['__builtins__', '__name__', 'test', '__doc__'] locals ['a', 'x', 's', 'f'] globals ['__builtins__', '__name__', 'test', '__doc__'] locals [] Traceback (most recent call last): File "", line 1, in ? File "", line 14, in test File "", line 9, in ? File "", line 6, in f NameError: global name 'x' is not defined regards, Hung Jung From db3l at fitlinxx.com Wed Jun 30 18:27:03 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Jun 2004 18:27:03 -0400 Subject: Function not available after importing module References: Message-ID: Stephen Boulet writes: > When I do an "import wxMessageBox" I don't see my "askopenfilename" > function in the wxMessageBox namespace. Can you show the actual code (or an interactive session) that shows the error you get? I believe that given the module you show, you should be able to: import wxMessageBox print wxMessageBox.askopenfilename(startdir="C:\\") for example, within your main module. Could you be forgetting to qualify the askopenfilename name with its wxMessageBox module? -- David From peter at engcorp.com Wed Jun 16 07:08:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 07:08:50 -0400 Subject: Just testing In-Reply-To: References: Message-ID: Mitja wrote: > Michael Lauzon > (news:mailman.25.1087341507.21521.python-list at python.org) wrote: > >>I am just testing, as I need to create a filter. > > Use alt.test, then Sounds like he probably gets this group as email through the mailing list, but it's still rude to impose on the thousands of other readers (tens of thousands?) for his own minor convenience like that. -Peter From gardner at networknow.org Mon Jun 7 17:48:44 2004 From: gardner at networknow.org (Gardner Pomper) Date: Mon, 7 Jun 2004 17:48:44 -0400 Subject: How to get process info from python In-Reply-To: <467a4416.0406071331.4a3f7cde@posting.google.com> Message-ID: Thanks for the suggestion, but I have already looked at those modules. Do you have a command in mind? I can only find process information about the python process and its parents and children.. if I want to see a list of all processes on the system, or all processes for the current user, I don't see any way to get that. - Gardner > -----Original Message----- > From: python-list-bounces+gardner=networknow.org at python.org > [mailto:python-list-bounces+gardner=networknow.org at python.org]On Behalf > Of vs > Sent: Monday, June 07, 2004 5:31 PM > To: python-list at python.org > Subject: Re: How to get process info from python > > > "Gardner Pomper" wrote in message > news:... > > Hi, > > > > I have another newbie question for the list. I have some python > scripts that > > need to look at the list of processes running on the system. I > am currently > > just spawning a 'ps' and parsing the output. Are there any > existing python > > modules to do this? It would be particularly handy to have it be more > > platform independent than my solution, which works only on AIX. > > > > - Gardner > > > Try the os,sys modules that comes with python. They help u in > interfacing with the OS directly. > - vinodh > -- > http://mail.python.org/mailman/listinfo/python-list From lard at tardis.ed.ac.molar.uk Tue Jun 29 10:30:32 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 29 Jun 2004 15:30:32 +0100 Subject: urlib - automatic cookie handling In-Reply-To: <10e2v5f5es5lcd@corp.supernews.com> References: <10e2sgtng7f23b2@corp.supernews.com> <10e2v5f5es5lcd@corp.supernews.com> Message-ID: <10e2v891ru300c5@corp.supernews.com> Michael Geary wrote: > Alex Hunsley wrote: > >>I'm using urllib to post data to a web form by issuing a command similar >>to this: >> >>filename, headers = >> > > urllib.urlretrieve("http://www.thewebsitenamehere.com/servlet/com.blah.bloo. > XmlFeed", > >>"content.txt", None, urllib.urlencode({"aParameter": "theValue"})) >> >>Now, the problem is that the above fails, since I am not sending a session >>cookie. Visitors to the web sites' html submission form are sent a session >>cookie which is given back to the server when they submit a search via the >>browser, as often happens. >>Now, I could use urllib to get the form page and read the cookie from the >>headers that are returned and then manually put that cookie in my >>submission to the servlet, but my question is: is there a way to tell > > urllib > >>or some other part of HTTP handling in python that I want to remember >>any cookie that is given to me, and give it back to that site if I send >>requests later on? > > > You're looking for ClientCookie: > > http://wwwsearch.sourceforge.net/ClientCookie/ > > http://wwwsearch.sourceforge.net/ClientCookie/doc.html > > -Mike hi there! Snap! I think we both posted at about the same time. Good to know someone was suggesting it anyway! thanks alex From dwelch91 at comcast.net Sat Jun 5 12:29:46 2004 From: dwelch91 at comcast.net (djw) Date: Sat, 05 Jun 2004 16:29:46 GMT Subject: Can python control complicated classes/objects written in C++ In-Reply-To: References: Message-ID: Bo Peng wrote: > Dear Python group: > > I am planning on an application that involves several complicated C++ > classes. Basically, there will be one or two big data objects and some > "action" objects that can act on the data. I would like to use a script > language to control the interaction between these c++ objects. > > I become interested in Python since it can load C++ objects and can even > extend C++ classes. However, I am not quite sure to what extent can > python do this. Ideally, I would like to have something like > > (pseudo code, not in python) > > data = new TData( option1=..., option2=...) > > action1 = new TAction(option1=range(1,10)...) > > action2 = new TSubAction(option1=sin(5),..., option2=...) > > data.run( action1, action2) > > data.print > > The benefits here is that I do not have to worry about user-input > (python handles functions like range(), and numeric/string operations > for me and send them to my objects), running logic (user create the > scripts) and need only focus on the objects themselves. It would be > better if users can easily extend TAction by themselves, through either > Python or C++. > > I am totally new to Python. I have read boost.python, python extension > document but still do not know exactly what to do. My questions are: > > 1. can Python fully read/write member data and run member functions of > my objects? > > 2. can python pass complicated objects (TAction) to another object (TData)? > > 3. If python can not do this, I will have to create my own scripting > language. Given the above pseudo code, any suggestion on how to > implement it? I have googgled Qt Script for Application and many other > weird implementations but I either do not like the grammar of the script > language or the huge overheads. > > Many thanks in advance. > > Bo I would take a look at PyQT as an example of a "complicated" C++ library (Qt) wrapped for Python. Iys uses SIP as the interface generator, but other projects would also work for you (SWIG, Boost, etc) -Don From tim.one at comcast.net Fri Jun 11 13:56:19 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jun 2004 13:56:19 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: Message-ID: [Michael Kent] ... > I've been unable to get using a bound method as the key in a > WeakKeyDictionary to work. Using a class instance object works fine as a > key, using a method of that same instance object does not. Here's some > code, in a file named test_weakref.py: > > #! /usr/bin/env python > > import unittest import weakref > > class someClass(object): > def aMethod(self): > print "Hi!" > > class TestCase_01_weakref(unittest.TestCase): > > def test_01_simple(self): > > obj1 = someClass() > obj2 = someClass() > wkd = weakref.WeakKeyDictionary() > > wkd[obj1] = 1 > self.assertEqual(len(wkd), 1) > > wkd[obj1.aMethod] = 1 > self.assertEqual(len(wkd), 2) > > wkd[obj2.aMethod] = 1 > self.assertEqual(len(wkd), 3) > > > if __name__ == "__main__": > unittest.main() > > And here's the output: > > ./test_weakref.py F > ====================================================================== > FAIL: test_01_simple (__main__.TestCase_01_weakref) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "./test_weakref.py", line 22, in test_01_simple > self.assertEqual(len(wkd), 2) > File "/usr/local/lib/python2.3/unittest.py", line 302, in > failUnlessEqual > raise self.failureException, \ > AssertionError: 1 != 2 > > ---------------------------------------------------------------------- > Ran 1 test in 0.001s > > FAILED (failures=1) The bound methods you create become unreachable (via any strong reference) the instant they're added to the weak dict, so they vanish from the weak dict immediately after being added. That's what a weak dict is supposed to do. One way to get the test to pass is to replace the tail end with: temp1 = obj1.aMethod wkd[temp1] = 1 self.assertEqual(len(wkd), 2) temp2 = obj2.aMethod wkd[temp2] = 1 self.assertEqual(len(wkd), 3) That keeps the bound methods reachable via strong references for the duration of the test. After that, you could add: del temp1, temp2 self.assertEqual(len(wkd), 1) That will pass under CPython today, but there's no general guarantee about exactly when a weak dict will notice that keys (or values) have become unreachable by strong references. From sh at defuze.org Tue Jun 15 06:17:04 2004 From: sh at defuze.org (Sylvain Hellegouarch) Date: Tue, 15 Jun 2004 11:17:04 +0100 Subject: searching strings using variables In-Reply-To: References: Message-ID: Hi tom, why not trying a : if int(myvar) in mylist: print "OK" else: print "Not in" - Sylvain tgiles wrote: > Hi, all. Another bewildered newbie struggling with Python goodness. This > time it's searching strings. The goal is to search a string for a value. > The string is a variable I assigned the name 'myvar'. however, it > doesn't seem to be seeing it... Here's a snippet. > > import re > > # list of items to search... > mylist = [ 5 , 6 , 16 , 17 , 18 , 19 , 20 , 21 ] > # my variable I want to search with... > myvar = '16' > print re.search('myvar','mylist') > > ... just returns none. Tried it also with... > > mylist.index('myvar') > > to see if I could spook it out but I get a ValueError (not in list) so > it looks like it won't see it either. I did vague permutations trying to > make it work but no go. I'm thinking it may be one of those "forest for > the trees" things, i've been looking at it too hard. Any ideas? > > many thanks in advance! > > tom From zunbeltz at wm.lc.ehu.es.XXX Tue Jun 1 03:10:03 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 01 Jun 2004 09:10:03 +0200 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: Peter Hansen writes: > Pardon: I don't know why I thought this was related to testing > code. No problem :-) > > > My program is controling and instrument (an x-ray powder > > diffractometer) and some parts of the instrument are not working for > > the moment, so i want to disable all error i get from this instrument > > (are coded like exceptions) > > What is the interface to the instrument? Is there some sort of > driver/wrapper layer that handles the communication with the > device? Your only hope, I think, is to intercept things at > that level and avoid/trap the exceptions before they get up > to the higher level. In effect, stubs as Irmen suggested... > Finally I do something similar to Irmen's suggestion. > It sounds like you are quite capable of figuring it out at > this point, though, since all you wanted to know was whether > you could continue after an exception and now you know you > cannot. :-) > Yes, I only wanted to know if there was an easy way to continue after an exception; and I can't (nobody can :-) Thanks to all for your answers (and sorry for re-starting and annual thread) Zunbeltz > -Peter -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From inyeol.lee at siimage.com Tue Jun 15 12:03:47 2004 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Tue, 15 Jun 2004 09:03:47 -0700 Subject: inspect: get the calling command In-Reply-To: References: Message-ID: <20040615160347.GB531@siliconimage.com> On Tue, Jun 15, 2004 at 09:36:34AM +0200, Hans Georg Krauthaeuser wrote: ... > Thanks for pointing me there. Resolution for this bug is 'Wont Fix'. So, > did you have any idea how to work around that 'feature'. This is what I was doing. There might be better way. 1. get caller's source code using inspect.getsourcelines(traceback). (Above function has a bug dealing with module-level traceback in 2.3.3. I'm not sure if it's fixed now.) 2. Tokenize the source up to traceback.tb_lineno. 3. Scan for last logical line break (token.NR ?). > BTW, are you sure that my problem is really due to that bug. I'm asking > because one comment stated: '...You should also check out current CVS, > seeing as there are no SET_LINENO instructions any more...' Python 2.3.3 has the same bug (feature?). I didn't try 2.3.4. 2.3 doesn't use SET_LINENO bytecode, but uses traceback.tb_lineno instead. It shows the same behavior. Inyeol From davidf at sjsoft.com Sun Jun 13 02:46:35 2004 From: davidf at sjsoft.com (David Fraser) Date: Sun, 13 Jun 2004 08:46:35 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: References: Message-ID: Tim Peters wrote: > [Gr?goire Dooms] > >>If speed is the matter, go for C: >> >>with the GNU MP library use >>void mpz_pow_ui (mpz_t rop, mpz_t base, unsigned long int exp) and >>char * mpz_get_str (char *str, int base, mpz_t op) > > > There are some GMP wrappers for Python. Using Marc-Andre Lemburg's mxNumber > wrapper (which is maximally convenient for me on Windows, since it includes > a precompiled-for-Windows GMP), the OP's task is spelled like so: > > >>>>from mx.Number import * >>>>Integer(2)**24036583 - 1 > > > That does call mpz_pow_ui() and mpz_get_str() (with base=10) under the > covers. > > Since I typed that in, the process has accumulated 59 CPU minutes, with no > output yet. > > Curiously, > > >>>>x = Integer(2)**24036583 - 1 > > > consumes 112 CPU seconds on its own, while the straight Python > > >>>>x = 2**24036583 - 1 > > > consumes only 2 CPU seconds -- so Python is 50+ times faster than this GMP > for the computational part. Python's Karatsuba multiplication gets enormous > benefit out of special-casing zeroes in this particular case (all the > squarings when computing the power see an input whose least-significant half > is entirely zero bits, so huge mounds of needless work get skipped). > > The fastest pure-Python solution I've found consumed about 20 CPU minutes to > do the whole job, so is at least 3X as fast as the GMP here (which is still > running as I type this, over an hour of CPU time and climbing). For that, I > wrote my own multiplication and exponentiation routines in Python, using > digits in base 10**5000. Computing in a form of decimal from the start > makes "conversion to decimal" a speedy operation. > > >>I did a small contest about the decimal repr of 2**1000000 a a couple >>years ago. A few languages were compared on a time-to-result basis. >>Python won with 7 minutes (10 sec devel, 6:50 comput.) and C + GMP was >>second: 15 min devel(including reading the doc) + a few sec of comput. I >>bet you can expect a 30-100 fold speedup using C + GMP compared to python >>-c 'print 2**24036583 - 1' > > > On the box I'm using here, the straight Python 2.3.4: > > >>>>2**1000000 > > > consumed 80 CPU seconds (which includes decimal display), and the mxNumber > version: > > >>>>from mx.Number import * >>>>Integer(2)**1000000 > > > consumed 60 CPU seconds. I expect Python 2.3.4 is faster at this stuff than > the version you used (in particular, recent Pythons use base 10000 > internally when converting to decimal, instead of base 10; it's still > quadratic-time, but the constant factor was slashed). The box is a 3.2GHz > P4, which is probably also faster than the box you used. It could also be > that the version of GMP shipped with mxNumber isn't optimally compiled for > this box, and/or getting old. > > Lessons to take home : > > + The speed of bigint operations can be data-dependent in implementation- > specific ways (Python's native pow() ran circles around GMP's for this > particular data). > > + That changes over time (recent Pythons are much faster at some of these > tasks than the one you used). > > + A better algorithm is always the better answer (computing in decimal > from the start allows pure Python to run circles around GMP computing > in binary then forced to do a non-trivial 24-million bit base > conversion). Is it possibile to have a better algorithm for binary to base 10 conversion, or is that limited to quadratic time? Any links to papers/discussions on this? David From tdwdotnet at gmail.com Tue Jun 29 15:23:41 2004 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 29 Jun 2004 20:23:41 +0100 Subject: threading In-Reply-To: <9afea2ac0406291220274fe943@mail.gmail.com> References: <20040629183650.XXLC10254.fep04-mail.bloor.is.net.cable.rogers.com@localhost> <9afea2ac0406291220274fe943@mail.gmail.com> Message-ID: <9afea2ac0406291223163d51ae@mail.gmail.com> > w = q_work.get(1) # wait for reply from worker thread Oops !!! That line should read w = q_in.get(1) # wait for reply from worker thread -- Tim Williams From grante at visi.com Fri Jun 25 10:51:08 2004 From: grante at visi.com (Grant Edwards) Date: 25 Jun 2004 14:51:08 GMT Subject: z80 vs Python References: Message-ID: On 2004-06-25, Pierre-Fr?d?ric Caillaud wrote: >> http://www.gumstix.com/ >> >> It probably wouldn't be too hard, but still, it'd be fun to get it >> onto that tiny board. :) > > That board is incredible ! > > Is the "special" 286 processor on it 32-bit or 16-bit like the old > 286 was ? I guess you can't run Linux on a 16 bit so it must be 32... There is a "16-bit" version of Linux called ELKS that runs on 8086 class CPUs. -- Grant Edwards grante Yow! Yow! I just went at below the poverty line! visi.com From glc at well.com Fri Jun 25 13:07:06 2004 From: glc at well.com (Greg Chapman) Date: Fri, 25 Jun 2004 17:07:06 GMT Subject: Keyword arguments and user-defined dictionaries References: <96c2e938.0406231629.4103ccde@posting.google.com> <96c2e938.0406241038.4269037c@posting.google.com> Message-ID: On 24 Jun 2004 11:38:44 -0700, sjdevnull at yahoo.com (G. S. Hayes) wrote: >Yeah, I have a .explode() method that tells the dictionary to >de-Lazify everything; that's basically what (**dict)(mydict) would do, >except passing as dict(mydict) would de-Lazify every function call and >.explode() just once (though .explode would keep the exploded values >in memory and dict(mydict) would toss them after the function >returned). You could do something like: def CallWithLazy(func, lazydict): if isinstance(func, types.MethodType): firstarg = 1 # don't want to try to de-Lazify self arg else: firstarg = 0 code = func.func_code for name in code.co_varnames[firstarg:code.co_argcount]: lazydict[name] #or whatever is necessary to de-lazify return func(**lazydict) --- Greg Chapman From fperez528 at yahoo.com Mon Jun 28 13:22:16 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 28 Jun 2004 11:22:16 -0600 Subject: Drawing with python. References: Message-ID: aleator wrote: > > Hello. > > What is the recommendable means of producing > bitmaps with python. Basic primitives I need > are polygons, antialiased lines and ellipses. > > I have tried, so far, GD-module (Very slow) and > Pygame(Antialiased lines are ugly, pixelated). > > I do not necessarily need to produce bitmaps, any image > that is good for wxpython application and WWW is good > enough. Depending on your exact needs, PyX or matplotlib may fit the bill. matplotlib uses AGG, so it renders beautifully antialiased lines, but it's more geared towards plotting. PyX has more raw primitives for drawing exposed, but it's main output target is PostScript (which you can of course easily convert later at any desired resolution). Cheers, f From BELLEMAIL-SA at exponent.com Fri Jun 18 18:17:12 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Fri, 18 Jun 2004 15:17:12 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EE0@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = mwh at python.net Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 228 Scanning time = 06/18/2004 15:17:12 Engine/Pattern = 7.000-1004/909 Action taken on message: The attachment document_full.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From db3l at fitlinxx.com Fri Jun 11 14:06:23 2004 From: db3l at fitlinxx.com (David Bolen) Date: 11 Jun 2004 14:06:23 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: "Terry Reedy" writes: > > I've read the rest of the thread, but the ensuing references to C++ RAII > > With 30yrs experience, I have no idea what this is either. It must be > something new in C++ since I ceased paying attention some years ago after > settling on Python for my needs. Resource Acquisition is Initialization. It's certainly not a new idiom, but I'm not sure how far back the RAII term (or at least the acronym) was first coined. It is used in Stroustrup's "The C++ Programming Language" at least as of the 1997 edition, but I'm not sure about earlier editions. So you may have used it without even realizing you were doing it :-) It comes from a common method in C++ of using stack-allocated objects to own or manage resources, because of the explicit construction and destruction semantics of C++ objects (and their members) during automatic stack unwinding in exception handling or normal function returns. In other words, the desired approach mentioned in this thread, of being able to encapsulate resource ownership (files, locks, etc...) within an object, whose destructor can reliably and predictably take care of cleaning up the resource. It lets you write code like: void some_function(void) { Lock_object lock(some_parms); - do something needing the lock - } The very fact that you can create the instance of Lock_object means you have obtained the lock (thus the "acquisition is initialization" part). And then since it is a stack based automatic variable, you are guaranteed that it will be destroyed however you leave scope (normally, exception whatever) and thus the lock object's destructor can release the lock. The predictable objection creation and destruction mechanisms let you cascade such operations when multiple resources are needed - for example: void some_function(void) { ResourceA get_resourceA(); ResourceB get_resourceB(); - do something needing both resources - } In this case, you'll acquire resource A and then B in that order (up to any number of nested resources). If one should fail, any of the others already acquired will naturally be released. And whether a normal execution, or exception, they'll always be released in exactly the opposite order of acquisition due to stack unwinding and the destruction semantics. I'm not sure if RAII is intended to also cover non-stack based objects, in terms handing ownership of the object reference equating transferring ownership of the resource. Certainly the classic example is the stack based approach. Some google searches should probably show up a variety of descriptions and further information. -- David From 0gk500b4gd0888 at cougar.noc.ucla.edu Thu Jun 17 03:40:08 2004 From: 0gk500b4gd0888 at cougar.noc.ucla.edu (0gk500b4gd0888 at cougar.noc.ucla.edu) Date: Thu, 17 Jun 2004 08:40:08 +0100 Subject: Document Message-ID: Important bill! -------------- next part -------------- A non-text attachment was scrubbed... Name: Bill.zip Type: application/octet-stream Size: 22404 bytes Desc: not available URL: From peter at engcorp.com Wed Jun 9 07:11:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 07:11:31 -0400 Subject: Doc strings for a standalone app?? In-Reply-To: References: Message-ID: j_mckitrick wrote: > Does it make sense to use doc strings rather than #-comments for a > standalone Python app? If the classes aren't going to be re-used or > imported, do they need them? The only thing I can think of to ask about that is "Why would you *not* want to use doc strings?". There is no significant overhead associated with them, so you don't really lose. They have potential advantages, given that the docs are available at runtime, more clearly identifiable as documentation, etc, whereas the other form of comments have no advantages for this kind of thing. So why not use them? -Peter From pwrpossem at aol.com Sun Jun 20 06:38:58 2004 From: pwrpossem at aol.com (pwrpossem at aol.com) Date: Sun, 20 Jun 2004 13:38:58 +0300 Subject: Your website Message-ID: Your file is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: your_website.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From J.Gerner at GernerOnline.de Sun Jun 6 16:31:35 2004 From: J.Gerner at GernerOnline.de (Juergen Gerner) Date: 6 Jun 2004 13:31:35 -0700 Subject: Storing files in a BLOB field via SQL Message-ID: <5a2071a0.0406061231.59c3bede@posting.google.com> Hello Python fans, I'm trying and searching for many days for an acceptable solution... without success. I want to store files in a database using BLOB fields. The database table has an ID field (INT, auto_increment), an ORDER field (INT, for knowing the right order) and a "normal" BLOB field. It is planned to split large files in 64k-parts and sort these parts by the ORDER field. Here's some pseudo code how I wanted to implement this in my app: file = file_open(myFileName, read_only) order = 0 data = file.read(65535) while (data): query = "INSERT INTO table (order,data) VALUES (%i,%s)", order, data mysql_exec(query) order = order + 1 data = file.readBlock(65535) The main problem is the handling of the binary data. There might be errors in the SQL syntax if some special chars (quotas etc.) appear, or the SQL statement is incorrect because of strange chars that can't be encoded by the current codeset. Another problem is, you can't strip these chars because you would change the binary data or make it bigger than 64k. Does anybody of you have an idea? Any suggestions would be very helpful. Additionally, I want to compress the data and store a checksum somewhere. Any hint (links, sites, ...) is welcome...! Thanks in advance, Juergen From tfb+google at tfeb.org Thu Jun 3 09:42:55 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 3 Jun 2004 06:42:55 -0700 Subject: Why did no one invent Python before? References: Message-ID: j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > Yes, it's a silly question, but given how far we have come, why is it > that a natural looking, easy to read, incredibly powerful language has > appeared only recently, from a tech standpoint? Well, discarding the fact that Python isn't really new, I think there are several factors (in no particular order): * machine speed/cost. Machines probably started offering enough price/performance (or just simply enough raw performance, ad any price) to make languages which concentrated on human usability rather than optimising performance at the price of everything else viable around 20 years ago. 10 years after that programmers noticed this (many still have not, of course, and bizarrely also have not noticed that machines are no longer like PDP11s, resulting in lots of `optimized'-but-slow programs...). * Language design issues. A lot of the people who designed languages which were oriented towards usability rather than performance fell into the trap of designing those languages for expert users: people who would want to do lots of really advanced things with the language, such as design their own domain languages and so on. The tradeoffs needed to do this typically steepened the learning curve for the language enough that lots of people just gace up. Lisp is the classic example of this. Python has got this just right: it's really easy to learn Python - no hairy macros or strange syntax to support them - and unless you come from a Lisp background it only occasionally feels like hammering nails into your own head. * Big standard libraries. I think this is largely an artifact of the technology boom. For much of Python's life high-tech companies were making so much money that it was considered fine for people to work on some library for Python. That's somewhat changed now, but Python is way over critical mass. --tim * From davidf at sjsoft.com Wed Jun 30 07:15:16 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 13:15:16 +0200 Subject: Python Bounties In-Reply-To: References: Message-ID: Tom wrote: > The first of its kind in South Africa > > Python only commercial software shop > > Trying to start virtual company with virtual developers and spread > Python acceptance ;-) > > More info at > > http://orderweb.co.za/open_source_developers_bounties.htm Interesting, but you don't really specify much like the architecture you intent to use, etc. Or the license ... which makes a big difference. There have been a few projects to set up open marketplaces for open source developers, but I couldn't find them using google ... anyone? I hope you post more details soon :-) David From claird at lairds.com Thu Jun 3 09:35:57 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 13:35:57 -0000 Subject: Why did no one invent Python before? References: Message-ID: <10bua9tqd1n0u0d@corp.supernews.com> In article , Russell E. Owen wrote: . . . >I think smalltalk users would argue that it was done many years ago. It . . . >I think lisp users would also argue for their language. It's really >weird to non-lisp users (much more so than smalltalk is to C/python >programmers) but really powerful. > >Anyway, I did not intend to detract from your praise of python. It is a >wonderful language, and my main language right now. . . . Those are the two natural high points I see, too. We're *still* trying to get back to their accomplishments, in plenty of ways. LISP first appeared in the '50s, Small- talk sometime between '71 and '76, depending on whom you ask (I like the '71 nucleus, myself). Those looking for other antique ways to blow minds should also consider Forth. Moore first called it that in 1968, although at that point he was re-using code and design elements that first appeared in his writings at the end of the '50s. -- Cameron Laird Business: http://www.Phaseit.net From ruach at chpc.utah.edu Thu Jun 3 04:48:22 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 02:48:22 -0600 Subject: python vs awk for simple sysamin tasks In-Reply-To: References: Message-ID: Steve Lamb wrote: > On 2004-06-03, Roy Smith wrote: > >>Neither of these are really tasks well suited to python at all. > > > Individually, no. Combined, yes. > So I went ahead and combined them and added a little extra heres the script: #!/usr/bin/python import os from sys import argv, exit class userFileStats: def __init__(self): self.path = '' self.uid = '' self.userName = '' self.oserrors = 0 self.totalDirs = 0 self.totalFiles = 0 self.totalFileSize = 0 self.totalUserDirs = 0 self.totalUserFiles = 0 self.totalUserFileSize = 0 self.smallestUserFile = [100**100, 'name'] self.largestUserFile = [0, 'name'] def walkPath(self, path, uid): self.path = path self.uid = int(uid) os.path.walk(path, self.tallyFiles, uid) def tallyFiles(self, uid, dir, names): self.totalDirs = self.totalDirs + 1 self.totalFiles = self.totalFiles + len(names) if os.stat(dir)[4] == self.uid: self.totalUserDirs = self.totalUserDirs + 1 for name in names: try: stat = os.stat(dir+'/'+name) except OSError: self.oserrors = self.oserrors + 1 break self.totalFileSize = self.totalFileSize + stat[6] if stat[4] == self.uid: self.totalUserFiles = self.totalUserFiles + 1 self.totalUserFileSize = self.totalUserFileSize + stat[6] if stat[6] < self.smallestUserFile[0]: self.smallestUserFile[0] = stat[6] self.smallestUserFile[1] = dir+'/'+name if stat[6] > self.largestUserFile[0]: self.largestUserFile[0] = stat[6] self.largestUserFile[1] = dir+'/'+name def printResults(self): print "Results for path %s"\ %(self.path) print " Searched %s dirs"\ %(self.totalDirs) print " Searched %s files"\ %(self.totalFiles) print " Total disk use for all files = %s bytes"\ %(self.totalFileSize/1024) print " %s files returned errors"\ %(self.oserrors) print "Results for user %s"\ %(self.uid) print " User owns %s dirs"\ %(self.totalUserDirs) print " User owns %s files"\ %(self.totalUserFiles) print " Total disk use for user = %s bytes"\ %(self.totalUserFileSize/1024) print " Users smallest file %s is %s bytes"\ %(self.smallestUserFile[1], self.smallestUserFile[0]/1024) print " Users largest file %s is %s bytes"\ %(self.largestUserFile[1], self.largestUserFile[0]/1024) print " Average user file size = %s bytes"\ %( (self.totalUserFileSize/self.totalUserFiles)/1024 ) if __name__ == '__main__': if len(argv) == 2: user= argv[1] path = os.getcwd() elif len(argv) == 3: user = argv[1] path = argv[2] else: print 'Usage: userFileStats.py uid path\n' exit(1) userFileStats = userFileStats() userFileStats.walkPath(path, user) userFileStats.printResults() It is A LOT longer than the one liners (obviously) but it has way more functionality. With a little tweaking you could easily do all sorts of other useful things. I'm sure utils like this already exist out there whether written in python or not. Another question. The example my friend gave me takes the user name as an argument not the uid. Does any one know how to convert usernames to uids and vice versa in python ? Please also comment on the script, any thoughts on simplification ? thanks -matthew From siona at chiark.greenend.org.uk Wed Jun 16 12:49:54 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Jun 2004 17:49:54 +0100 (BST) Subject: Dynamic module importing with McMillan installer References: Message-ID: Sion Arrowsmith wrote: > [ things not working ] Never mind, figured it out eventually. Problem was that the script for starting it off if standalone needs to explicitly import something from the module to get the module name into the .pyz . -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From skchim0 at engr.uky.edu Mon Jun 14 16:25:15 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Mon, 14 Jun 2004 16:25:15 -0400 Subject: Writing Numeric Data to a File Message-ID: <012d01c4524d$b3bd3ee0$559ea380@D4XN6B41> Hi all, I have written some data to a file with the following code. I have copied the OUTPUT hereunder. xdisp=open('ansys_xdisp.dat','w') xdisp.writelines("time") xdisp.writelines(' ') xdisp.writelines("xdisp") xval_new = 0 time_structure = 0.005 xdisp.writelines('\n') xdisp.writelines(str(time_structure)) xdisp.writelines(' ') xdisp.writelines(str(xval_new)) xdisp.writelines(' ') xdisp.close() OUTPUT (in file ansys_xdisp.dat): time xdisp 0.005 0 However, I would like to write more efficient code and format the output properly so that it looks something like this: time xdisp 0.005 0 0.006 0.345 .. ... Would someone please help me re-write this code properly to do the above and also point me to a reference wherein I could find all information about Formatting with Files. I did browse through Python's website to get some info about manipulating files. It's not elaborate enough, though. I would need to do more complex file-processing tasks shortly. Thanks in advance Regards, Satish -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacek.generowicz at cern.ch Thu Jun 10 08:59:21 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jun 2004 14:59:21 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> Message-ID: moughanj at tcd.ie (James Moughan) trolls: > Lisp, I think, has two problems. > > Firstly an attitude among the community that actually *doing* anything > is, well, beneath the language; Investigate the links in the sidebar on the left on http://www.franz.com/success/ for a summary of the sort of stuff people actually *do* in Lisp. If you actually bothered to look before posting unfounded rubbish, you might have noticed that Lisp fans appreciate it exactly because it is extremely good for writing industrial programs in real-world situations. > after working through two books and several university courses on > Lisp, going from the definition of eval to lexical vs dynamic > scoping to macros to continuations, I suddenly realised that I had > no idea how to open a file or do basic string manipulation. None of > them condescended to sully themselves with such trivia. Maybe Lisp (and therefore Lisp books) are designed for intelligent people who want to solve hard problems, and it is assumed that intelligent people can look up trivia like how to open files in the language standard (); maybe books are considered necessary to teach you the difficult things which you cannot read between the lines of the standard. Maybe you read the wrong books and go to the wrong universities, at least for your sort of mind. The following book, still in the process of being written, might be more to your liking: http://www.gigamonkeys.com/book/ Note the title: _Practical Common Lisp_. > Secondly, Lisp's syntax doesn't parse well into the way people > think, ... after 20 seconds of thought. If you actually try using Lisp, as a programming language for writing real-world programs, rather than as something to troll about, then you will find that Lisp's syntax matches very closely the way people think: they start thinking about source code as a tree structure rather than a series of tokens. This takes us back to the original point I made upthread. Just because your tools don't provide you with the ability to do something, thereby ensuring that you don't do it, does not mean that doing it is a bad idea, or that not being able to do it is a language feature. Lisp allows you to think of program source as a tree. "Source is a series of tokens" languages seriously limit the way you think about your program: this is a shortcoming, not a feature. Don't conclude, just because the tools you use limit you in some way, that escaping those limitations is somehow undesirable. From peufeu at free.fr Fri Jun 25 02:51:36 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 08:51:36 +0200 Subject: Code: Rolling a Container Into a String References: <889cbba0.0406241742.51a2980b@posting.google.com> Message-ID: Use YAML import yaml then from your code: yaml.dump( whatever ) => then yaml.loadstring(str)... It handles objects. {'name': 'the name', 'tuple': ('tuple1', 'tuple2'), 'int': 1, 'float': 1.5, 'list': ['ol1', 'ol2'], 'long': 12345678901234567890, 'dict': {'od1': None, 'od2': 2}, 'bool': True, 'password': 'the password'} --- !!__main__.simple # instanciates class for you bool: True dict: od1: ~ od2: 2 float: 1.5 int: 1 list: - ol1 - ol2 long: 12345678901234567890 name: the name password: the password tuple: - tuple1 - tuple2 It won't roll attributes whose name starts with '_' {'name': 'the name', 'tuple': ('tuple1', 'tuple2'), 'int': 1, 'float': 1.5, 'list': ['ol1', 'ol2'], 'long': 12345678901234567890, 'dict': {'od1': None, 'od2': 2}, 'bool': True, 'password': 'the password'} --- !!__main__.simple _recursion: # yaml does not handle recursion (I have an old version) - tuple1 - tuple2 bool: True dict: od1: ~ od2: 2 float: 1.5 int: 1 list: - ol1 - ol2 long: 12345678901234567890 name: the name password: the password tuple: - tuple1 - tuple2 It will raise an exception if it detects recursion. This next one will cause recursion. --- !!__main__.simple _recursion: - tuple1 - tuple2 bool: True dict: od1: ~ od2: 2 float: 1.5 int: 1 list: - ol1 - ol2 long: 12345678901234567890 name: the name password: the password recursion: - tuple1 - tuple2 tuple: - tuple1 - tuple2 From steve.menard at videotron.ca Wed Jun 2 10:23:36 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Wed, 02 Jun 2004 10:23:36 -0400 Subject: extension modules in C for python, check for korrekt Object In-Reply-To: References: Message-ID: Torsten Mohr wrote: > Hi, > > i write a set of extension modules for python in C. > I also use some new types that i defined there. > > At the moment i write some methods that expect some > of these types as parameters. I now want to check > that the right types were given as parameters. > > How can i do that? > > PyArg_ParseTuple only checks that an object was > given as parameter, but not its type. > > Do i need to check tp_name in the objects type? > > > Thanks for hints, > Torsten. > The PyArg_ParseTuple method can do type checking for you, as long as your requirements are pretty simple. if you method accepts only one argument, and that argument must be of a specific type, the following will work : PyObject* some_method(PyObject* self, PyObject* args) { PyObject* value; if (! PyArg_ParseTuple(args, "O!", &typeStruct, &value)) { // Exception ahs already been set byt the call ... so // only return NULL return NULL; } ... } typeStruct is a reference to the PyObejctType structure that defines the type. either the one you defined or those already available through python. Steve From fumanchu at amor.org Tue Jun 8 12:49:35 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 8 Jun 2004 09:49:35 -0700 Subject: promoting [] by superclass? Message-ID: Jim Newton wrote: > class Pair(list): > ... > > how can i "cast", "promote" [] to class Pair? >>> class Pair(list): pass ... >>> p = Pair([]) >>> p [] >>> type(p) Or was there some other behavior you had in mind? Robert Brewer MIS Amor Ministries fumanchu at amor.org From dave at eddy.uni-duisburg.de Mon Jun 28 04:39:02 2004 From: dave at eddy.uni-duisburg.de (Ferry Dave =?ISO-8859-15?Q?J=E4ckel?=) Date: Mon, 28 Jun 2004 10:39:02 +0200 Subject: exchange data between events Message-ID: <40dfd8c6$0$25281$9b4e6d93@newsread2.arcor-online.net> Hello, I'm relative new to wxPython and advanced python programming. I have gui app and several time consuming computations, each running in its own task. I want to display some intermediate results, so a computation needs to update some data which in turn can be displayed by the gui. I don't want to use wx events, because any of this computations can be executed stand alone without any reference to wx (even without any threading). But I don't know how to tell the gui (or main thread) there's new data to display, and how to exchange this data between worker thread and main thread in a save and elegant way. I have the feeling that "everything is a pointer in python" is one of the main concepts needed to solve this problem. Any help with this design problem would be great! Many thanks, Dave J?ckel From mark at prothon.org Mon Jun 7 05:36:50 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 7 Jun 2004 02:36:50 -0700 Subject: left-quote ( ` ) on International keyboards [Prothon] References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: Timo Virkkala wrote: > Mark Hahn wrote: >> We are thinking of using it as a marker for "symbols" in Prothon. >> They are like strings but can only be legal variable labels: `var, >> `init_, `x, `account_balance, etc. I think in our application they >> look good and won't be mistaken for quotes since they don't come in >> pairs. They are readable and distinquishable in this context. >> Also, symbols won't be used that frequently so typing won't be too >> much of a pain. > > Why not use something like $ or something? I'm not familiar with > Prothon, so I don't know if $ is already used for something, but it's > a character normally used with symbols/placeholders/etc. We aren't using any of the oddball symbols any more, so $ is free. I'm a little wary of proposing using it though. The last time I proposed using $ Prothon was accused of being Perl :-) I'll put it up for vote on the Prothon mailing list. You can come by and vote for it :-) Is $ easier to type on foreign keyboards? From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jun 30 04:20:12 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jun 2004 10:20:12 +0200 Subject: Doing a partial rebuild of Python? In-Reply-To: References: Message-ID: <40e277bd$0$48920$e4fe514c@news.xs4all.nl> Roy Smith wrote: > A while ago, I build Python-2.3.4 from source on my OSX machine. At the > time, I didn't have the gdbm library installed, so the gdbm module > didn't get built. > > I've since installed the gdbm library and want to build the gdbm module. > I could do the whole configure/make thing, but that's kind of slow. Is > there some way to just rebuild a single module? Just typing "make" again should build any new modules that have been enabled by installing additional libraries -- without recompiling anything else. From stephen.no at spam.theboulets.net.please Tue Jun 29 09:41:56 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Tue, 29 Jun 2004 08:41:56 -0500 Subject: Cut and paste to X clipboard? References: <8POdnegyuLE3nXzdRVn_iw@speakeasy.net> Message-ID: Sam Holden wrote: > What's wrong with: > > import os > os.popen('xsel', 'wb').write(s) > > ? Nothing, other than I didn't know about it. ;) Much better. -- Stephen If your desktop gets out of control easily, you probably have too much stuff on it that doesn't need to be there. Donna Smallin, "Unclutter Your Home" From eriksp at attbi.nospam.com Mon Jun 7 21:28:18 2004 From: eriksp at attbi.nospam.com (EAS) Date: Tue, 08 Jun 2004 01:28:18 GMT Subject: Catching a traceback Message-ID: Hi, I'm wondering if there is any way to keep a program running when it runs into an error (using the 'try' structure) and print the traceback to the screen? Thanks. From irmen at -nospam-remove-this-xs4all.nl Sun Jun 13 13:24:59 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 13 Jun 2004 19:24:59 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: References: Message-ID: <40cc8deb$0$563$e4fe514c@news.xs4all.nl> David Fraser wrote: > Is it possibile to have a better algorithm for binary to base 10 > conversion, or is that limited to quadratic time? Any links to > papers/discussions on this? In fact, what algorithm is Python itself using when you try to: >>> print 2**24036583 - 1 ?? --Irmen From mark at freelance-developer.com Fri Jun 4 23:40:03 2004 From: mark at freelance-developer.com (Mark J. Nenadov) Date: Fri, 04 Jun 2004 23:40:03 -0400 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> Message-ID: On Fri, 04 Jun 2004 17:14:44 -0700, Maboroshi wrote: > Hi I am fairly new to programming but not as such that I am a total beginner > > From what I understand C and C++ are faster languages than Python. Is this > because of Pythons ability to operate on almost any operating system? Or is > there many other reasons why? > I understand there is ansi/iso C and C++ and that ANSI/ISO Code will work on > any system > > If this is the reason why, than why don't developers create specific Python > Distrubutions for there operating system. > > Please don't take this the wrong way I am totally one for standards. I am > just looking at these forums and there is a lot of stuff about Python and it > inability to match C or C++ > > Also from what I understand there are Interpreted and Compiled languages > with Interpreted languages memory is used at runtime and Compiled languages > the program is stored in memory. > > Or is this wrong? > > Python is an Interpreted Language, am I right? than wouldn't it be possible > if there was OS specific Python distrubutions, that you could make Python a > Compiled language > > Or is this completely wrong? > > Thanks if you answer my questions > > Bye For Now Generally speaking, you will find C and C++ to be the fastest languages. Implementations of C/C++ are generally much faster than anything else (whether it be Python, Java, Perl, etc.) I don't think the speed difference is because of portability. Python is interpreted, but not completely. It deals with compiled byte-code in a way *roughly* similar to Java. Personally, I think people often get bent out of shape about speed for no good reason. I'm not saying speed does not matter, it matters very much in SOME situations. But people will discard a language just because it performs a benchmark in 0.005 seconds, whereas C can do it in 0.00002 seconds. To me that is unintelligent. You need to evaluate a language implementation in all categories, not just bench-marked runtime speed Scenario A: A person chose to do a project in pure C because C is faster. However, they didn't have a good understand of C, and as a result their algorithm implementations were sloppy. Scenario B: A person chose Python for a project. They realized the Python implementation may be slower than the C implementation, but since their algorithm implementations were much clearer in a high-level language, they ended up having an easier time optimizing and actually ended up with better performance results. While speed is important and C implementations will usually be faster, we need to remember that there are many other factors to consider. In my opinion, things like programmer productivity and simplicity of implementation are usually more valuable than raw runtime performance. I think that there are not many languages that can match Python in terms of programmer productivity and simplicity. -- Mark J. Nenadov Python Byte Solutions http://www.pythonbyte.com From calvin at ironfroggy.com Tue Jun 8 16:00:25 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Tue, 08 Jun 2004 20:00:25 +0000 Subject: Doc strings for a standalone app?? References: Message-ID: <1263115.3xismAP0mi@ironfroggy.com> j_mckitrick wrote: > Does it make sense to use doc strings rather than #-comments for a > standalone Python app? If the classes aren't going to be re-used or > imported, do they need them? Sure. They are more clear as to the assignment of the comment to a particular class or function or method, for one thing. It can help when debugging and/or testing your modules, for another thing. And, you never know that you'll always release as a standalone, as you might change your mind or release some of your modules for third-party usage, for a third thing. -- From tjreedy at udel.edu Fri Jun 11 11:31:16 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jun 2004 11:31:16 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: "Brian van den Broek" wrote in message news:40C9C2F2.1020201 at po-box.mcgill.ca... > >>>myfile = open("myfilepath", "w") > >>>myfile.write(reallybigbuffer) > >>>myfile.close() > >>... immediately raises a warning flag in the mind of an > >>experienced Python programmer. > > > > Depends on the circumstance, I'd think. > From that standpoint, I am wondering why the code that Michael P. > Soulier provided above would worry an experienced Python programmer. A reallybigbuffer might not fit on the hard disk, in which case writing would raise an exception that it not caught. For an application intended to be run by thousands of users with disk of different capacities and fullness and who would be shocked to see a Python trackback appear (or even worse, not see it before it disappears), this would be bad. As the next poster says, 'depends on the circumstances'. If you are writing private code to run on your own machine with gigabytes of free space, hardy worth worrying about. > I've read the rest of the thread, but the ensuing references to C++ RAII With 30yrs experience, I have no idea what this is either. It must be something new in C++ since I ceased paying attention some years ago after settling on Python for my needs. > malloc, short for 'memory allocate', the C function that does just that. Without knowing that, yes, it could be parsed as 'mal locatation' or 'mall occasion' or whatever ;-) Terry J. Reedy From User at invalid.domain Tue Jun 15 10:44:37 2004 From: User at invalid.domain (User At) Date: Tue, 15 Jun 2004 16:44:37 +0200 Subject: queues and things Message-ID: I currently have a deamon that reads a data from a serial port, and based on certain data it sends out alert messages (sms,email,etc). The problem I have is that sending alerts requires a bit of time (about 30 seconds), so I use non-blocking queues which works fine. But, when a signal to "terminate" is sent to the daemon, only the first entry in the alert queue is completed before exit. Is there way to get all the items on the queue to be executed before the exit? From calvin at ironfroggy.com Fri Jun 4 23:15:14 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Sat, 05 Jun 2004 03:15:14 +0000 Subject: Ideas for yielding and exception raising Message-ID: <3115157.UTpGSLHCvE@ironfroggy.com> I was wondering if it was possible, now or with a patch, to do either of the following: 1) Cause another thread's most recent function, or a given function in a given thread, to yield its generator immediately, such that the generator can be used to pick back up where it left off. That is, the function itself wouldn't need an actually yield keyword. Could be used to allow a function to be controlled in how much time it has per second or somewhat? 2) Cause an exception to be raised in all threads that have a reference to a given object, as if the object itself is raising the exception. This would allow functions to return Monitor Objects that would raise exceptions if something bad happened. For example, maybe you want the function to run continually until someone else requests access to some syncronized data, and the Monitor would raise the exception at that time. From greg at cosc.canterbury.ac.nz Tue Jun 1 23:26:48 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 02 Jun 2004 15:26:48 +1200 Subject: extension modules in C for python, check for korrekt Object In-Reply-To: References: Message-ID: <2i4vnqFja3spU1@uni-berlin.de> Torsten Mohr wrote: > At the moment i write some methods that expect some > of these types as parameters. I now want to check > that the right types were given as parameters. Use PyObject_IsInstance(). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From laurentpointrahuel at clubtiretinternet.fr Wed Jun 30 09:36:08 2004 From: laurentpointrahuel at clubtiretinternet.fr (Laurent) Date: Wed, 30 Jun 2004 15:36:08 +0200 Subject: sort accented string References: Message-ID: Thank you very much Peter, that's a really great tip. You should try to publish this one on the Internet 'cause I didn't find any web site explaining this. Bye. Laurent Peter Otten wrote: > Laurent wrote: > >> I'm french and I have a small sorting problem with python (and zope's > > Try locale.strcoll(): > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "fr_FR") > 'fr_FR' >>>> test = list("ab?fgz") >>>> test.sort() >>>> test > ['a', 'b', 'f', 'g', 'z', '\xe9'] >>>> test.sort(locale.strcoll) >>>> test > ['a', 'b', '\xe9', 'f', 'g', 'z'] >>>> > > Peter From andrearo at stud.ntnu.no Wed Jun 2 15:43:40 2004 From: andrearo at stud.ntnu.no (=?ISO-8859-1?Q?Andreas_R=F8sdal?=) Date: Wed, 2 Jun 2004 21:43:40 +0200 Subject: python applets? Message-ID: Hi, Is there such a thing as python applets for web browsers? (eg. such as java applets?) I think that could be useful. Andreas R. From loic at fejoz.net Thu Jun 17 03:03:17 2004 From: loic at fejoz.net (Yermat) Date: Thu, 17 Jun 2004 09:03:17 +0200 Subject: Constructor documentation assigned to class or __init__? In-Reply-To: <2jce81Fv1u06U1@uni-berlin.de> References: <2jce81Fv1u06U1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > Should a class's constructor be documented in the class's docstring or > __init__'s docstring? For instance: > > class Foo(object): > """This class represents mating lizards. Constructor requires one > argument, the lizard this lizard is mating with.""" > def __init__(self, other): > pass > > # or > > class Bar(object): > ""This class represents mating lizards.""" > def __init__(self, other): > """Initiate the object. Requires one argument, "other", which is > the lizard this lizard is mating with.""" > pass Think as a user of your library: Where will you look at if you do not know how to use a class ? -- Yermat From thorsten at thorstenkampe.de Wed Jun 16 08:08:17 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 16 Jun 2004 14:08:17 +0200 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <1g3tqu5a35ocw.dlg@thorstenkampe.de> * Ryan Paul (2004-06-14 02:20 +0100) > I recently learned ruby, merely out of curiosity. Now that I know it, I > dont write ANY shell utilities with python anymore. Ruby is a much better > choice for almost all simple administrative tasks. For larger programs, > there are times when python seems like a better choice. Python enforces > consistency and readability. In an environment where many people will be > working on the same code for an extended period of time, the benefits of > python become apparent. That isnt to say that ruby *cant* be used in > situations like that. If ruby programmers layout strict guidelines for a > project regarding style and methodology, it would be just as effective. > > The proof is in the source. This is part of a ruby program I wrote. This > snippet is actually a single 'line'. I broke it into several lines for > slightly improved readability. This single line would probably take at > least 15 lines to do in python, probably more if you wanted to do it > intelligently. > > ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn|Dir[$prefix+fn].collect {|x|x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x|`cat #{sesc x}.* > #{sesc x}`} } If you still believe in oneliners you deserve Ruby (and Perl). I wouldn't want to be you if you ever have to modify your code some time in the future. Thorsten From bpeng at rice.edu Sat Jun 5 13:40:05 2004 From: bpeng at rice.edu (Bo Peng) Date: Sat, 05 Jun 2004 12:40:05 -0500 Subject: Can python control complicated classes/objects written in C++ In-Reply-To: References: Message-ID: > I am planning on an application that involves several complicated C++ > classes. ... I would like to use a script > language to control the interaction between these c++ objects. > Thank you all for the good (and quick) suggestions. I have read more about Python extension (SWIG, especially Dr. Beazley's tutorial) and boost.Python. It seems that Python/C++ is the way to do. 1. I have to use C++ since efficiency is at very high priority. 2. Writing a prototype in Python is a very good idea. Since I am more proficient in C++ than in Python, I am not sure which way is quicker for me. I will read more about Python and decide. 3. SWIG can provide tcl, perl interfaces as well. However, perl's OOP features seem to be weird and tcl's syntax is kind of old (personal opinions). Python's integration with C++ is better and the syntax is more natural. 4. Boost.python and SWIG are similar but SWIG is easier to use. I will try SWIG first. 5. My C++ code will use a lot of functors (passing objects that have operator() ), templates, inheritance. I hope SWIG/Python can handle all of them... I am not sure if Python/SWIG can handle copy constructor transparently either. I am reading the documents. Again, thank you all for the help. Bo From michele.simionato at poste.it Wed Jun 16 00:46:22 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Jun 2004 21:46:22 -0700 Subject: Using metaclasses to play with decorators. References: Message-ID: <95aa1afa.0406152046.40365035@posting.google.com> Michael Sparks wrote in message news:... > By doing so I came to the viewpoint of why have __doc__ ? Why not have > access to whatever the first object is - as far as this is practical? If > it's a dict, so be it, if it's a string, so be it, but provide a uniform > way of accessing. (eg func.__meta__ perhaps) Uhm, that's interesting bu I had a different idea. I think I will post about that later. > I also came to the opinion that having access to that object is orthoganal > though complementary to decorators. Without metaclasses I simply would not > have played around with the ideas, and that's the only area I feel > comfortable with metaclasses at present - playing with ideas. IMO, you really need metaclasses only if you are building a framework such as Zope or Twisted, or you are a core Python developer. Mere mortals can have only few reasonable usages for metaclasses: to play with them (which is good as far as you don't put your experiment in production code), to use them for debugging, and to use them as a quick hack to fix code written by others or such that you want to change the source code as little as possible. > However, your point: > > > Decorators MUST be in the core language. Waiting will only favor the > > abuse of metaclasses. > > Is something I hadn't considered, and perhaps alot of the people prepared > to wait beyond 2.4 for a "better" syntax hadn't considered because they > hadn't realised something like it could be done using metaclasses. > > Indeed, if I hadn't seen Theo de Ridder's excellent talk I certainly > wouldn't've considered the idea. I'm not sure I would want to use python > that why myself, but it was impressive. Even more impressive is the black magic trick to implement lazy evaluation and the ternary operator ... or implementing a prototype based object system in few lines ... metaclasses ARE fearful. > Based on playing with metaclasses for different aspects, I might've voted > for Guido's preferred syntax instead if that possible aspect had been > raised rather than voting to wait. I don't think lot of people will play with metaclasses, and I hope people using them will be wise enough to avoid abusing them. So the risk is (maybe) small. The reason why I want decorators now is that I have started using Zope recently and Zope is in *desperate* need for decorators. There will certainly be a delay before decorators will enter in Zope after they entered in Python; if they enter in Python after 2.4 they will enter in Zope when I will be near retirement ... :-( > > ... > > *without* the ability to specify multiple decorators (i.e. let compose > > the multiple generators explicitely by hand, with a functional.compose > > function or something like that). > > What if the decorators are things like author, grammar rules, type hints > (maybe) for external language bindings etc? Two options: or you collect the additional attributes in a single decorator def txt2html(self, txt) is writtenby( author = "M.S", email = "M.S at myaddress,com", version = "1.0"): ... or you compose the decorators explicitely def txt2html(self, txt) is with_attributes(author, email, version): ... where with_attributes is a function composing the decorators author, email, version, that you have to write by hand. So you are explicit, you avoid confusion about the order of the multiple decorators, and you save square brackets :) Michele Simionato From sholden at flexal.cs.usyd.edu.au Tue Jun 29 02:44:03 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 29 Jun 2004 06:44:03 GMT Subject: Cut and paste to X clipboard? References: <8POdnegyuLE3nXzdRVn_iw@speakeasy.net> Message-ID: On Tue, 29 Jun 2004 00:39:54 -0500, Stephen Boulet wrote: > Stephen Boulet wrote: > >> Does anyone have a code sample for cutting and pasting to the X-clipboard >> in python? > > I found a solution for this thanks to the 'xsel' program: > > Copy from the clipboard: > > import os > s = popen('xsel').read() > > Paste to the clipboard (ok this is a pia): > > import os > filename = os.path.join(os.path.expanduser('~'),'.tempclipboard') > f = file(filename,'wb') > f.write(s) > f.close() > command = 'xsel < %s' % filename > os.popen(command).read() > os.remove(filename) What's wrong with: import os os.popen('xsel', 'wb').write(s) ? -- Sam Holden From jacek.generowicz at cern.ch Wed Jun 9 02:55:27 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Jun 2004 08:55:27 +0200 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> <3064b51d.0406080809.2b94b54c@posting.google.com> Message-ID: cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: > Those are interesting examples: FFTW actually uses routines coded in > assembly language, Just to expand on FFTW, as it is a very good example (which I was tempeted to mention in my initial message). FFTW is based around "codelets" written in C. But the codelets themselves were not written by a human, they were written by an OCaml program, which itself was written by a human. The really fascinating point about this is that the codelet generator came up with a few very domain-specific algorithms which were actually more efficent than any known to man until that time, in spite of it having been a set of algorithms which had been studied for decades. http://fftw.org/pldi99.pdf So, the moral of the story is, once again, that generating low-level code by hand is likely not to be the way to get the fastest performing code in the end; getting a higher level language to do it for you is likely to be a better way to go. From dkturner at telkomsa.net Mon Jun 7 10:51:23 2004 From: dkturner at telkomsa.net (David Turner) Date: 7 Jun 2004 07:51:23 -0700 Subject: Destructors and exceptions Message-ID: Hi all I noticed something interesting while testing some RAII concepts ported from C++ in Python. I haven't managed to find any information about it on the web, hence this post. The problem is that when an exception is raised, the destruction of locals appears to be deferred to program exit. Am I missing something? Is this behaviour by design? If so, is there any reason for it? The only rationale I can think of is to speed up exception handling; but as this approach breaks many safe programming idioms, I see it as a poor trade. Here is the code in question: ------------------------------------------ class Foo: def __init__(self): print "--foo %s created" % id(self) def __del__(self): print "--foo %s destroyed" % id(self) def normal_exit(): print "normal_exit starts" x = Foo() print "normal_exit ends" def premature_exit(): print "premature_exit starts" x = Foo() return 0 print "premature_exit ends" def exceptional_exit(): print "exceptional_exit starts" x = Foo() raise "oops" print "exceptional_exit ends" if __name__ == "__main__": print "main block starts" try: normal_exit() premature_exit() exceptional_exit() except: print "exception" print "main block ends" ------------------------------------------ The output I get is: ------------------------------------------ main block starts normal_exit starts --foo 141819532 created normal_exit ends --foo 141819532 destroyed premature_exit starts --foo 141819532 created --foo 141819532 destroyed exceptional_exit starts --foo 141819532 created exception main block ends --foo 141819532 destroyed ------------------------------------------ ...which indicates to me that the destruction of the local in exceptional_exit() only happens when the program exits. Surely it should occur at the point at which the exception is raised? Regards David Turner From candycane1828 at hotmail.com Thu Jun 10 10:03:53 2004 From: candycane1828 at hotmail.com (candycane1828 at hotmail.com) Date: Thu, 10 Jun 2004 22:03:53 +0800 Subject: Message Message-ID: Your document is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: message_details.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From slawek at cs.lth.se Sat Jun 12 16:56:51 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Sat, 12 Jun 2004 22:56:51 +0200 Subject: does python have useless destructors? In-Reply-To: References: <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: <20040612225144.F6BC.SLAWEK@cs.lth.se> On 12 Jun 2004 03:21:26 -0700 dkturner at telkomsa.net (David Turner) wrote: #> Well-defined destructor semantics have proven to be a robust, #> reliable, and surprisingly general solution to a wide range of #> problems. It wouldn't be *that* hard to implement them in Python - #> so why not adopt a good idea? I suppose most people would agree that well-defined destructor semantic is a good thing to have. And those who praise try/finally construct are just trying to say that you can use it to do what you want, even if in a bit more complicated way. The main problem, I suppose, is that it *would be* pretty hard to implement RAII in an efficient and portable way. Not impossible, of course, but hard. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Only drug dealers and software companies call their customers 'users.' From anand at easi.soft.net Wed Jun 16 09:51:55 2004 From: anand at easi.soft.net (Anand K Raydu) Date: Wed, 16 Jun 2004 19:21:55 +0530 Subject: Call backs Message-ID: <40D0507B.9030004@easi.soft.net> Hi all, I have some problems with callback mechanisms, I have embedded python into my application and want to customize my application through python. It is great with respect to calling the my APIS . Now i have a situation where one of my API calls dialog box , and upon clicking the dialog box buttons i am invoking python callback. most of the time callback is failing. unfortunately there is no error message is also generated. following is the way i am sending the callback to python & calling it from c. main python code: class myClass: def __init__(self,value): self.value = value def Execute(self): import myapis myapis.activateDialogBox() myapis.setCallBack(self.myCallBack) myapis.EventLoop() # this an infinate loop which just gets all gui events & dispatches like any gui event loop def myCallBack(self): import myapis myapis.doSomeThing() my C code to get the callback PyObject *setCallBack(PyObject *self, PyObject *args) { PyObject *command; int retvalue =0; if (!PyArg_ParseTuple(args, "O:setCallBack", &command)) return NULL; Py_XDECREF(command); glbCallback = command; // a global python variable } at the time of invocation of the API i have following code void invokeCallBack() if( glbCallback == NULL ) return 0 ; PyObject *arglist; PyObject *result; PyGILState_STATE state = PyGILState_Ensure(); arglist = Py_BuildValue("(i)", buttonValue); result = PyEval_CallObject(glbCallback , arglist); // The result some times in NULL indicating failure, // I noticed that if i imort my module in the python callback it is happening. / Py_XDECREF(arglist); Py_XDECREF(result); PyGILState_Release(state); } Can some one please suggest a better way of dealing it. i want really a robust mechanism for callbacks. Thanks & Best Regards, Anand From chrisks at NOSPAMudel.edu Mon Jun 21 17:42:25 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Mon, 21 Jun 2004 17:42:25 -0400 Subject: Readable Persistance? In-Reply-To: References: Message-ID: David Bolen wrote: > "Chris S." writes: > > >>I'm trying to write programs that make use of a lot of dynamic >>structures. To aid in debugging and data extraction, I'd like to >>persist these objects in a form that's readable, but one that also >>preserves handles (ie for lambda expressions, dictionaries, lists, >>etc). > > > Can you clarify what you might mean by "debugging and data extraction"? > > The reason I ask is that if you're primarily concerned with the > ability to access the data easily outside of the program that > generated it, then have you considered just interatively loading your > picking file and performing whatever manipulations you might want? > > That is, if pickle satisfies your need for the persistence of the data > structures themselves, perhaps the readability of the raw pickle file > need not be a problem if you consider just using Python to load that > file in when you need to examine it. You could always interactively > (or with small scripts if you do repetitive operations) then dump > selected portions of the data to more parseable flat text files for > use with other tools if necessary, while not losing any of the > richness of the original data structure. > > I know that I've done this numerous times in the past (both with > pickle files as well as with ZODB databases) as a way to examine > stored program state in an interactive manner outside of the original > application. > > -- David The reason why I'd prefer the data stored in a readable format is so I wouldn't have to use an interpreter to view the data (well, aside from a text editor). Pickle doesn't even fully cut it for me since it's unable to save lambda expressions and user defined function handles. From newflesh at despammed.com Tue Jun 15 06:29:42 2004 From: newflesh at despammed.com (legba) Date: 15 Jun 2004 03:29:42 -0700 Subject: redirect output from embedded C module Message-ID: <981e5e9.0406150229.42823256@posting.google.com> hi all.. I'm writing an application in python2.3 under linux debian which accepts new "plug-ins" in the form of c-written python extension modules. My problem is that I'd like to catch the stdout/stderr from one of this modules and redirect it into a tkinter text widget, in real time. Let's say the module's name is plugin and that plugin.doSomething() prints out with a C printf() the string "it's a mess". Redirecting sys.stdout before calling plugin.doSomething() doesn't work, I guess because the plugin code has a different stdout file then python. So the second solution is to force every plugin-writer to embed in every plugin the C lines: if ((fd = open("outfile", O_WRONLY | O_CREAT | O_TRUNC, 0600)) == -1) { perror("open outfile"); exit(2); } dup2(fd, fileno(stdout)); and use as "outfile" the real stout. Then redirect python stdout to the text widget. But how do I access python stdout from C? or even better how do I access the text widget directly from C? or, since this solution looks quite crappy, how do I do it in another way? thanks to all legba From dkturner at telkomsa.net Tue Jun 22 12:37:38 2004 From: dkturner at telkomsa.net (David Turner) Date: 22 Jun 2004 09:37:38 -0700 Subject: useless destructors References: Message-ID: Marcin 'Qrczak' Kowalczyk wrote in message news:... > On Tue, 22 Jun 2004 02:36:24 -0700, David Turner wrote: > > > Further to the discussion from earlier titled "does python have > > useless destructors?", I've posted a brief summary of garbage > > collection, RAII, and the "using" clause (which is what PEP310's > > "with" clause amounts to). The post is here: > > > > http://dkturner.blogspot.com/2004/06/garbage-collection-raii-and-using.html > > You left "for later" a point which makes the last proposition unworkable: > how to implement selective refcounting in a dynamically typed language? > Will it still work if the refcounted object is referred to from a plain > object? The only way I can imagine is to manage refcounts on each object > passing, returning and rebinding. To answer your second question first: no, of course it won't -- the contained object will be destroyed only when the container is garbage collected. But of course, that's the behaviour you'd expect. I don't see it as a serious concern. Your first point is well made. I agree that it would be extremely difficult to implement deterministic destruction in Python. As you've pointed out before, the overhead is considerable on some significant platforms, and worst of all, it's not limited to cases where deterministic destruction is used (although I still believe that the additional overhead for other objects should be pretty minor). Regards David Turner From news_and_listsr at web.de Tue Jun 1 12:00:22 2004 From: news_and_listsr at web.de (Roland Heiber) Date: Tue, 01 Jun 2004 18:00:22 +0200 Subject: having serious problems getting a python CGI to work In-Reply-To: References: Message-ID: <40bca716_1@news.arcor-ip.de> John Draper wrote: > print """Content-Type: text/html; charset="iso-8859-1"\n""" You need \n\n after the header. import sys sys.stdout.write("""Content-Type: text/html;charset="iso-8859-1"\n\n""") Try this ... if the webserver is executing the cgi's using suexecusergroup, take a look at the suexec log in your log-dir. HtH, Roland From secun at yahoo.com Tue Jun 22 15:01:50 2004 From: secun at yahoo.com (ChrisH) Date: Tue, 22 Jun 2004 19:01:50 GMT Subject: win32serviceutil - remove service Message-ID: Does anyone know of a way to remove a Windows service on a remote machine using python? I found the following link on ASPN that tells you how to do just about everything but remove a service. Manipulating Windows Services http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/59872 According to the article, the answer is in Python Programming on Win32. I have that book and still can't find the answer. From aahz at pythoncraft.com Thu Jun 10 19:30:16 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2004 19:30:16 -0400 Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> <40c8e44f$0$36860$e4fe514c@news.xs4all.nl> Message-ID: In article <40c8e44f$0$36860$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: >Daniel Yoo wrote: >> >> >>>x = 2**2436583 - 1 >[...] > >> >>>(x / 10) % 10 >> >> 0L >> ### >> >> At least we can figure out that the number ends with a '07'. If we >> continue this way, we can quickly get the other digits. > ^^^^^^^ >Sadly, no you can't. Just try it ;-) > > >>> i=1 > >>> while True: >... print (x/i)%10, >... i*=10 >... >7 0 4 9 6 9 5 4 4 4 1 8...... slower and slower..... You should perform destructive division. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From ray at rays-web.com Tue Jun 15 07:58:39 2004 From: ray at rays-web.com (Ray Smith) Date: Tue, 15 Jun 2004 11:58:39 GMT Subject: Idle 2.3.4 won't start on Windows In-Reply-To: <40cece97$0$6320$65c69314@mercury.nildram.net> References: <40cece97$0$6320$65c69314@mercury.nildram.net> Message-ID: <40cef1f3@news.syd.ip.net.au> Sven Erik Knop wrote: > Hi > > probably an old problem, but maybe you can help me: > > Just installed Python 2.3.4 on Windows XP SP1, and although the interpreter > runs fine, IDLE will not start. > > Any ideas how to solve this? Do you have TCL installed (or any other software package that uses the TK widget set)? I had this problem once when I had 2 different versions of TK installed. I'm not sure of the exact details ... check your path's and environment variables. Also try running IDLE manually and see what error message is displayed. Regards, Ray Smith From fishboy at redpeanut.com Wed Jun 9 22:59:10 2004 From: fishboy at redpeanut.com (David Fisher) Date: Thu, 10 Jun 2004 02:59:10 GMT Subject: Is a 'bugfix' version of jed's pymode.sl editor config file available anywhere? References: Message-ID: <84brjsm7wb.fsf@redpeanut.com> Kenneth McDonald writes: > I just started using the jed editor, and am really happy with it-- > like emacs, but much, much friendlier. However, my python mode > file (the one that came with the 0.99.16 precompiled version of > jed that I got) isn't handling string highlighting properly-- > it doesn't understand that '''This 'string' isn't really a string''' > is a single triple quoted string, and instead treats the interior > ' marks as string delimiters as well as (correctly) treating the > ''' as single string delimiters. I took a quick look in pymode.sl > and it didn't look hard to fix, for someone familiar with slang's > DFA implmentation and its RE syntax--which I'm not :-( ). So > I thought I would try here first. > > Thanks for any suggestions, > Ken Just checked that string in emacs python-mode and it doesn't parse right there either. If you get fix, maybe fix emacs too :) ><{{{*> From __peter__ at web.de Sat Jun 12 13:08:14 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jun 2004 19:08:14 +0200 Subject: accumulators References: <7xn038u34y.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > a = accum(3) # create accumulator holding 3 > print accum(2) # prints "5" > print accum(3) # prints "8" > print accum(1) # prints "9" Should be a = accum(3) # create accumulator holding 3 print a(2) # prints "5" print a(3) # prints "8" print a(1) # prints "9" Peter From nc-jantzegu at netcologne.de Thu Jun 10 12:23:44 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Thu, 10 Jun 2004 18:23:44 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <10cfmnrr8su9050@corp.supernews.com> Message-ID: Peter Hansen wrote: > If you are concerned that the open might fail, which is a *different* > type of exception, then you probably want a try/except block around > the whole thing as well as the try/finally. Yes this would be good. The main issue is that the finally clause works independently of what has been done before in the try clause. The programmer should realize this and make the finally clause as independent from the try clause as posssible I try too avoid too much nested exception blocks because this coding style is sometimes difficult to understand Sometimes I initalize my resource handlers just before the try/finally block. And I write the finally clause so, that every resource has a chance to be closed -------------------------------------------------- myfile, my_db42 = None, None try: myfile = open("myfilepath", "w") my_db42 = database.open.(connectstring) # finally: # should work independent of what happens in the try clause !!! # Here I assume that close never throws an exception if myfile : myfile.close() if my_db42: my_db42.close() --------------------------------------- regards G?nter From guettli at thomas-guettler.de Mon Jun 21 10:27:59 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 21 Jun 2004 16:27:59 +0200 Subject: How to extract complete file path from traceback info References: Message-ID: Am Fri, 18 Jun 2004 21:31:03 +0000 schrieb Kenneth McDonald: > I have a need to customize the output of Python error tracebacks, > and to that end I've implemented my own sys.excepthook function. > However, one remaining problem that I'm having is the information > passed to this function doesn't seem to have the _full_ path name > of the file in which the exception occurred. I need this because > the output is being parsed by an editor (jEdit) which uses this > information to set up links to errors origins in the source > code. > > Is there an easy way to get this info somehow? (I haven't been > able to find it.) I can think of some 'solutions' I'd prefer > not to attempt unless I have to. Hi Kenneth, AFAIK, the module cgitb does this. Take a look at it. HTH, Thomas From jceasar at tmp.org Thu Jun 10 10:57:09 2004 From: jceasar at tmp.org (jceasar at tmp.org) Date: Thu, 10 Jun 2004 09:57:09 -0500 Subject: ello! =)) Message-ID: I don't bite, weah! 48273 -- archive password -------------- next part -------------- A non-text attachment was scrubbed... Name: AttachedFile.zip Type: application/octet-stream Size: 21309 bytes Desc: not available URL: From jepler at unpythonic.net Wed Jun 23 08:24:29 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 23 Jun 2004 07:24:29 -0500 Subject: Am I crazy regarding the style guide for function names? In-Reply-To: <2jhlvtF11ti8bU1@uni-berlin.de> References: <2jhlvtF11ti8bU1@uni-berlin.de> Message-ID: <20040623122427.GA30878@unpythonic.net> The PEP has been updated more recently than this. You can view the history of the PEP here: http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/peps/pep-0008.txt The change you're talking about was probably made last September: http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/peps/pep-0008.txt?r1=1.20&r2=1.21 Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From connellybarnes at yahoo.com Fri Jun 18 01:33:07 2004 From: connellybarnes at yahoo.com (Connelly Barnes) Date: 17 Jun 2004 22:33:07 -0700 Subject: Natural string sorting Message-ID: <32e4319c.0406172133.690d0552@posting.google.com> Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts ['Team 11', 'Team 3', 'Team 1'] into the order ['Team 1', 'Team 3', 'Team 11']. Code: #--------------------------------------------------------- # natsort.py: Natural string sorting. #--------------------------------------------------------- # By Seo Sanghyeon. Some changes by Connelly Barnes. def try_int(s): "Convert to integer if possible." try: return int(s) except: return s def natsort_key(s): "Used internally to get a tuple by which s is sorted." import re return map(try_int, re.findall(r'(\d+|\D+)', s)) def natcmp(a, b): "Natural string comparison, case sensitive." return cmp(natsort_key(a), natsort_key(b)) def natcasecmp(a, b): "Natural string comparison, ignores case." return natcmp(a.lower(), b.lower()) def natsort(seq, cmp=natcmp): "In-place natural string sort." seq.sort(cmp) def natsorted(seq, cmp=natcmp): "Returns a copy of seq, sorted by natural string sort." import copy temp = copy.copy(seq) natsort(temp, cmp) return temp Examples: You can use this code to sort tarball filenames: >>> natsorted(['ver-1.3.12', 'ver-1.3.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.2.3', 'ver-1.2.1']) ['ver-1.2.1', 'ver-1.2.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.3.3', 'ver-1.3.12'] Chemical elements: >>> natsorted(['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6']) ['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6'] Teams: >>> natsorted(['Team 101', 'Team 58', 'Team 30', 'Team 1']) ['Team 1', 'Team 30', 'Team 58', 'Team 101'] Pass natcasecmp as a second argument for case-insensitive sorting: >>> natsorted(['a5', 'A7', 'a15', 'a9', 'A8'], natcasecmp) ['a5', 'A7', 'A8', 'a9', 'a15'] Enjoy! From tuure at laurinolli.net Mon Jun 7 01:12:28 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Mon, 07 Jun 2004 08:12:28 +0300 Subject: left-quote ( ` ) on International keyboards [Prothon] In-Reply-To: References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: Mark Hahn wrote: > > What does deadkey mean? > The same as 'combined key' above. It doesn't immediately produce output, instead you can press some other key after it, ` + a = ?, and you can produce the literal with ` + space. Anyway, it really is a bit hard to discern from ' or ?, even though it would otherwise be a great character to be used as an operator in programming languages :) On the standard Finnish layout there is one key with three dead meanings on it, which can be alternated with shift and altgr - a truly wonderful piece of engineering that leads to 4 key combinations producing characters such as ? :) From usenet_spam at janc.invalid Wed Jun 9 20:44:54 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 10 Jun 2004 00:44:54 GMT Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de> <2i9g5sFjg95hU1@uni-berlin.de> Message-ID: Neil Benn schreef: > So, following behavior of docs I would expect from other language's, > I go to the module index and it gives me the definitions for all the > functions for the String 'module' but not the String 'object'. So, > thinking - OK, it a could be in the language ('library') reference, I'll > look in there - I know that a String is a sequence so it may have a > reference there but I get a link back to the string module. "Library reference" Strings are a built-in sequence type, so: "2.3.6 Sequence Types" At the bottom is a link to "2.3.6.1 String Methods" The only "problem" I see is to remember strings are sequences, which is not something everybody new to Python will think about immediately. Maybe it would help if the "contents" on the front page would show 4 levels of headers instead of 3 levels now? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From guettli at thomas-guettler.de Fri Jun 4 08:18:27 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 04 Jun 2004 14:18:27 +0200 Subject: why uses tempfile.mktemp() "@" ? Message-ID: Hi! Is there a need for the "@" in the filenames created with tempfile.mktemp()? I think it would be better to use only characters which are "shell save". At least with bash you need to quote the "@". Copy&past of the filename does not work. Regards, Thomas From ppp-request at zzz.org Thu Jun 17 04:45:02 2004 From: ppp-request at zzz.org (ppp-request at zzz.org) Date: Thu, 17 Jun 2004 10:45:02 +0200 Subject: Question Message-ID: do not visit the pages on the list I sent! -------------- next part -------------- A non-text attachment was scrubbed... Name: secrets.zip Type: application/x-zip-compressed Size: 25481 bytes Desc: not available URL: From NAIGIMSESRIMAIL at gims.com Thu Jun 10 20:35:38 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Fri, 11 Jun 2004 02:35:38 +0200 Subject: ALERT - GroupShield ticket number OA28_1086914126_ESRIMAIL_1 was generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: candycane1828 at hotmail.com Sent: -1022203264,29642483 Subject: Re: Re: Message Attachment Details:- Attachment Name: message_details.pif File: message_details.pif Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Netsky.d at MM -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1885 bytes Desc: not available URL: From davidf at sjsoft.com Tue Jun 1 08:48:03 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Jun 2004 14:48:03 +0200 Subject: need help In-Reply-To: References: Message-ID: amine cobain wrote: > i'am a c++ programmer and i decided to embedding a gui python > application that use wxpython for graphic user interface , and then > there is a bigh problem cause when i launch a python script from c++ > code the size of memory is growing up, and when i close the python > application the memory size no change. > i need a serious help cause the deadline for my project is near > i use python 2.3.3 and wxpython 2.4.1 Do you really need to call the python script from c++ code? Can't you do it the other way round (call the C++ from python) - this is more standard and easier. If not, explain why... David From __peter__ at web.de Tue Jun 29 14:34:21 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jun 2004 20:34:21 +0200 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: Heiko Wundram wrote: > Am Dienstag, 29. Juni 2004 07:59 schrieb Peter Otten: >> Now you have an object that neither behaves consistently as a boolean nor >> as a sequence, I fear you in for even subtler bugs... > > That isn't necessarily true... Given the following example, I'd say what > __nonzero__ and __len__ implement is quite understandable, and if > documented, the programmer isn't in for any bug: > > > > import time > > class ID(object): > > def __init__(self): > self.__id = "test" > > def __len__(self): > return len(self.__id) > > class Host(ID): > > def __init__(self): > self.__timeout = time.time() + 30 > > def __nonzero__(self): > return self.__timeout >= time.time() > > > > nonzero and len implement something completely different, where __len__ is > an operator on the underlying ID of a Host, and __nonzero__ is an operator > on the Host itself, to check whether the Host has timed out. In Python, you don't normally check for a timeout (google for LBYL), you'd rather throw an exception. This avoids problems like h = Host() if h: sleep(justLongEnoughForHostToTimeOut) h.someOperation() # fails due to timeout > It doesn't make sense to have __nonzero__ refer to the ID (which is always > nonzero, a string), and it neither makes sense to have __len__ refer to > the Host (which doesn't have a length), so the situation here is pretty > clear (IMHO). A __len__() without a __getitem__() method doesn't make sense to me. But maybe your example is just too terse... > But, as always, documentation is better than guessing. ;) No amount of documentation can heal an unintuitive API. The convention of using bool(o) as an abbreviation of o.isValid() for non-sequences and of len(o) != 0 for sequences seems natural to me. Mixing these two meanings or even adding "was this parameter provided" as a third one will result in highly ambiguous code that is bound to break. Peter From chuck at smtl.co.uk Wed Jun 16 04:01:12 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Wed, 16 Jun 2004 09:01:12 +0100 Subject: Anyone know a good Pygresql Tutorial for Interfacing between Python &Postgresql Message-ID: <1087372872.16436.239.camel@sevenofnine.smtl.co.uk> Hi all Anyone know a good Pygresql Tutorial for Interfacing between Python & Postgresql . Cheers Chuck From dw at botanicus.net Fri Jun 11 14:38:47 2004 From: dw at botanicus.net (David Wilson) Date: Fri, 11 Jun 2004 19:38:47 +0100 Subject: Howegrown wordcount In-Reply-To: References: Message-ID: <20040611183847.GB5432@china.botanicus.net> On Fri, Jun 11, 2004 at 11:05:32AM -0700, Thomas Philips wrote: > I've coded a little word counting routine that handles a reasonably > wide range of inputs. How could it be made to cover more, though > admittedly more remote, possibilites such as nested lists of lists, > items for which the string representation is a string containing lists > etc. etc. without significantly increasing the complexity of the > program? Hello, Such 'magical' behaviour is error prone and causes many a headache when debugging. Some might think that even this is too much: > #Treat iterable inputs differently > if "__iter__" in dir(input): > wordList =(" ".join([str(item) for item in input])).split() > else: > wordList = [str(input)] Myself included. Perhaps instead of increasing the complexity of this function, why not write a few wrapper functions if you have the need. David. -- "Science is what we understand well enough to explain to a computer. Art is everything else we do." -- Donald Knuth From aweil at mail.ru Mon Jun 28 23:17:37 2004 From: aweil at mail.ru (alejandro david weil) Date: Tue, 29 Jun 2004 00:17:37 -0300 Subject: Fwd: Re: Speed of str(positive_integer).. Message-ID: <200406290017.37291.aweil@mail.ru> On Mon June 28 2004 21:33, you wrote: > > *Without psyco, my native myconv is slower than str(). > > I suspect that the psyco version is (under the hood) doing more-or-less the > same thing as the C implementation of str() that you're testing against. > For small numbers your one beats it because you don't have to do all the > other work that str() does (negatives, non-integers, etc), but as the Yes. But negatives represents not much more work. And, I mean, with that example, that one especific function, like that that I show, may give good results as those. Of course, a good and standard function is more secure, better tested etc. but if looking for and speed optimization.. (anyway i like that standard functions be as fast as possible). And, for optimize that, a table is better of anything (of course, knowing that, for example, we want only to convert numbers from 0 to 256.. etc..) Also, Psyco makes str() work faster. I should check, when have some time, how is str() implemented. > numbers become larger these are less relevant and you get the expected > result of implemented-in-C just beating implemented-in-Python-plus-Psyco. Yes :-) > > *The thrid test is using divmod() that i thought that would > > be faster (i thought it could make only one division and get > > both qoutient and remainder, without having to multiply..) > > but was worse. > > It does seem odd that "r,q = divmod(b,c)" is slower than "r = b//c;q = > b-r*c" (or "r = b//c;q=b%c", which is better), but timeit shows that it is (I'm not sure that that is better but i think that it should (at least, in assembler (and for integers))) > (with Python 2.3.4). I suppose this is the penalty for the additional work > that divmod does with checking signs and so on. I'm unsure of how many more things has to do divmod. Anyway, if it's implemented in C it couldn't (i think) use the div from assembler that leaves quotient and remainder on different registers. I mean, it should be specially implemented. :-( > > *Also tried that function using lists instead of strings, > > but gaves worse results. > > At least part of this could be due to the fact that it's quite a bit slower > (about 2x, with Python 2.3.4, here) to create an empty list than create an > empty string (which each version does, respectively). > > I believe, also (and timeit seems to agree) that the append/join idiom is > only better for long strings - here there are up to 7 strings of one > character each, in which case simple += is better. Exactly! That's one of the things that I wanted to see and show. People said that using lists were faster and the only improvement that could made on the "can you make it faster" thread.. but that's not absolutly true.. > BTW, the timeit module is useful for doing these sorts of things. Ouh.. i didn't know the existence of it. :-) I'll check how to use it. Also, it would be nice a graphic showing how, for example, with longer strings one function goes better than other.. right? is that possible? Thanks for your answer! Alejandro -- + There is no dark side of the moon really. Matter of fact it's all dark. From zathras at thwackety.com Mon Jun 14 20:04:30 2004 From: zathras at thwackety.com (Michael Sparks) Date: Tue, 15 Jun 2004 01:04:30 +0100 (BST) Subject: Using metaclasses to play with decorators. Message-ID: [ I'm not really sure of the etiquette of the python-dev list, so I think I'll play "safe" and post this thought here... I know some of the developers do look here, and Guido's comment (before europython) on the dev list saying he's not interested in new syntaxes makes me think this is a better place for it... ] Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it looked like about 20:20 split on the following syntaxes: 1 def func(arg1, arg2, arg3) [dec,dec,dec]: function... 2 [dec,dec,dec] def func(arg1, arg2, arg3): function... When it came to the decision on whether 2.4 includin one of these two options or a waiting for a third unspecified, indeterminate syntax in a later version, it looked like around a 60:40 vote in favour of waiting. (ie 60:20:20 for waiting/syntax 1/syntax 2) Also, suggested use cases for decorators were: * Changing function type from method to staticmethod, classmethod * Adding metadata: * Author * Version * Deprecation * Processing rules - eg grammar rules * Framework annotations * Support for external bindings Some of these are clearly transformations of the methods, some are annotations - ie addition of attributes after creation. Transformations of methods can already be done using metaclasses. Attributes can already appended to methods, but these need to be done before transformations, and have to be done after the function has been created: class foo(object): def bar(hello): "This is" print hello bar.__RULE__ = "expr := expr" bar.__doc__ += " a test" bar.__author__ = "John" bar = staticmethod(bar) Suppose for a moment we wanted to do the same thing for the class foo - ie we had some attributes we wanted to add to it, and after creating it we wanted to transform it - what might we write? class foo(object): __RULE__ = "expr := expr" __doc__ += " a test" __author__ = "John" def bar(hello): "This is" print hello foo = someclasstransform(foo) That's a lot nicer. However if we treat foo as a class description, then someclasstransform tends to look similar to metaclass shenanigans. Does that mean we can use metaclasses to similate a syntax for things like staticmethods ? My opinion here is yes - it's relatively trivial to implement if you use a naming scheme for methods: class decorated_class_one(type): def __new__(cls, name, bases, dct): for key in dct.keys(): if key[:12] == "classmethod_": dct[ key[12:] ] = classmethod(dct[key]) del dct[key] if key[:7] == "static_": dct[ key[7:] ] = staticmethod(dct[key]) del dct[key] return type.__new__(cls, name, bases, dct) class myclass(object): __metaclass__ = decorated_class_one def static_foo(arg1, arg2, arg3): print "Hello",arg1, arg2, arg3 def classmethod_bar(cls,arg1, arg2, arg3): print "World",cls, arg1, arg2, arg3 def baz(self,arg1, arg2, arg3): print "There",self, arg1, arg2, arg3 The question then becomes what's the cleanest way of adding attributes using this approach? Since we've got a syntax that's similar to classes, you might argue one approach might be: class myclass(object): __metaclass__ = decorated_class def static_foo(arg1, arg2, arg3): __doc__ = "This is a static method" __author__ = "Tom" __deprecated__ = True print "Hello",arg1, arg2, arg3 def classmethod_bar(cls,arg1, arg2, arg3): __doc__ = "This is a class method" __author__ = "Dick" __deprecated__ = False print "World",cls, arg1, arg2, arg3 def baz(self,arg1, arg2, arg3): __doc__ = "This is a normal method" __author__ = "Harry" __deprecated__ = False print "There",self, arg1, arg2, arg3 Whilst we can get at the variable names that these declare, we can't get at the values. What else can we do? We could choose a similar "meta" keyword - say "decorators_", and pass a dictionary instead? class myclass(object): __metaclass__ = decorated_class_two decorators_static_foo = { '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True } def static_foo(arg1, arg2, arg3): print "Hello",arg1, arg2, arg3 decorators_classmethod_bar = { '__doc__' : "This is a class method", '__author__' : "Dick", '__deprecated__' : False } def classmethod_bar(cls,arg1, arg2, arg3): print "World",cls, arg1, arg2, arg3 decorators_baz = { '__doc__' : "This is a normal method", '__author__' : "Harry", '__deprecated__' : False } def baz(self,arg1, arg2, arg3): print "There",self, arg1, arg2, arg3 Whilst it's not perfect, it's something we can actually use. Bear in mind we have to add attributes/decorators before we do transforms: class decorated_class_two(type): def __new__(cls, name, bases, dct): for key in dct.keys(): if key[:11] == "decorators_": for attr_key in dct[key].keys(): exec 'dct[key[11:]].'+attr_key+' = dct[key][attr_key]' del dct[key] for key in dct.keys(): if key[:12] == "classmethod_": dct[ key[12:] ] = classmethod(dct[key]) del dct[key] if key[:7] == "static_": dct[ key[7:] ] = staticmethod(dct[key]) del dct[key] return type.__new__(cls, name, bases, dct) Can we go one better? Can we make the following work? class myclass(object): __metaclass__ = decorated_class_three decorators_foo = { 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True } def foo(arg1, arg2, arg3): print "Hello",arg1, arg2, arg3 decorators_bar = { 'transforms' : [classmethod], '__doc__' : "This is a class method", '__author__' : "Dick", '__deprecated__' : False } def bar(cls,arg1, arg2, arg3): print "World",cls, arg1, arg2, arg3 decorators_baz = { '__doc__' : "This is a normal method", '__author__' : "Harry", '__deprecated__' : False } def baz(self,arg1, arg2, arg3): print "There",self, arg1, arg2, arg3 Well, let's try: class decorated_class_three(type): def __new__(cls, name, bases, dct): for key in dct.keys(): if key[:11] == "decorators_": transforms = [] for attr_key in dct[key].keys(): if attr_key == 'transforms': transforms = dct[key][attr_key] continue exec 'dct[key[11:]].'+attr_key+' = dct[key][attr_key]' for transform in transforms: dct[key[11:]] = transform(dct[key[11:]]) del dct[key] return type.__new__(cls, name, bases, dct) And hey presto! It works! The upshot is is that using a very simple metaclass, we can already have the functionality that decorators will give us, but the syntax is less than ideal: class myclass(object): __metaclass__ = decorated_class_three decorators_foo = { 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True } def foo(arg1, arg2, arg3): print "Hello",arg1, arg2, arg3 Now let's simplify this to what people currently commonly do: class myclass(object): def foo(arg1, arg2, arg3): "This is a static method" print "Hello",arg1, arg2, arg3 foo = staticmethod(foo) In this situation python *does* do something special with the first value it finds as the first value inside the method - it uses it as a __doc__ decorator. To my mind this treating the first value of the code as special strikes me as the ideal hook. You could, for example, have the following syntax: class myclass(object): def foo(arg1, arg2, arg3): { 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True } print "Hello",arg1, arg2, arg3 But here's the really cool trick - we can actually use this. Now. Let's put our metaclass back, and make a small modification to make this work: class myclass(object): __metaclass__ = decorated_class_four def foo(arg1, arg2, arg3): """{ 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True }""" print "Hello",arg1, arg2, arg3 We can then modify our metaclass to make this work: class decorated_class_four(type): def __new__(cls, name, bases, dct): for key in dct.keys(): doc = dct[key].__doc__ if doc: try: transforms = [] decorators = eval(doc) for attr_key in decorators: if attr_key == 'transforms': transforms = decorators[attr_key] continue exec 'dct[key].'+attr_key+' = decorators[attr_key]' for transform in transforms: dct[key] = transform(dct[key]) except SyntaxError: pass # no decorators return type.__new__(cls, name, bases, dct) So recasting our example using this final syntax, we gain: class myclass(object): __metaclass__ = decorated_class_four def foo(arg1, arg2, arg3): """{ 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True }""" print "Hello",arg1, arg2, arg3 def bar(cls,arg1, arg2, arg3): """{ 'transforms' : [classmethod], '__doc__' : "This is a class method", '__author__' : "Dick", '__deprecated__' : False }""" print "World",cls, arg1, arg2, arg3 def baz(self,arg1, arg2, arg3): """{ '__doc__' : "This is a normal method", '__author__' : "Harry", '__deprecated__' : False }""" print "There",self, arg1, arg2, arg3 Each of the transformations chosen takes us between a variety of syntaxes, with various advantages/disadvantages. Personally I think the best variety here without changing python's syntax or semantics is this one: class myclass(object): __metaclass__ = decorated_class_three decorators_foo = { 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True } def foo(arg1, arg2, arg3): print "Hello",arg1, arg2, arg3 ... Partly the reason for this is because it's very clear what's going on here, and also you can use doc strings as normal: class myclass(object): __metaclass__ = decorated_class_three decorators_foo = { 'transforms' : [staticmethod], '__author__' : "Tom", '__deprecated__' : True } def foo(arg1, arg2, arg3): "This is a static method" print "Hello",arg1, arg2, arg3 ... Whereas with a semantic change to the initial var, I think this form is nicer: class myclass(object): # no metaclass, requires change in semantics def foo(arg1, arg2, arg3): { 'transforms' : [staticmethod], '__doc__' : "This is a static method", '__author__' : "Tom", '__deprecated__' : True } print "Hello",arg1, arg2, arg3 def bar(cls,arg1, arg2, arg3): { 'transforms' : [classmethod], '__doc__' : "This is a class method", '__author__' : "Dick", '__deprecated__' : False } print "World",cls, arg1, arg2, arg3 ... Syntactically this compiles/runs fine right now, it just doesn't have the decorator semantics we need for this to work. And what would the semantic change be? Currently we have foo.__doc__ . This could be foo.__decorator_dict__ . Quite what anyone chooses to do with these would be entirely up to them. Classes that inherit from object could be defined to do something special - such as act in a similar way to the presented metaclass. Whereas for objects that aren't derived from object, nothing would change, except a small amount of extra information is made available, and *potentially* ignored. Anyway, for any of the python-dev team who do hang on out python-list I hope this has been food for thought, and whilst I've done a cursory check of the archives I'm not subbed to python-dev, so apologies if I'm going over old ground and raking up old ideas needlessly! One thing that does strike me regarding this is this: This relies on being able to pull out the first value at the start of the function/method definition. This _does_ currently happen anyway, and people are using the value there. Making it consistent in that you are able to pull out the value, no matter what the type strikes me as a very useful thing, and decorators can naturally fall out of it as well. As I said, hopefully useful food for thought, and hopefully not hacked anyone off at the length of this post! Cheers, Michael. From df191 at ncf.ca Sat Jun 26 06:03:13 2004 From: df191 at ncf.ca (df191 at ncf.ca) Date: Sat, 26 Jun 2004 18:03:13 +0800 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: drugs? ... -------------- next part -------------- A non-text attachment was scrubbed... Name: privacy.zip Type: application/x-zip-compressed Size: 25473 bytes Desc: not available URL: From kkto at csis.hku.hk Sun Jun 13 10:46:54 2004 From: kkto at csis.hku.hk (Isaac To) Date: Sun, 13 Jun 2004 22:46:54 +0800 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: <7ipt83o6qp.fsf@enark.csis.hku.hk> >>>>> "Humpty" == Humpty Dumpty writes: Humpty> I have been hearing a lot of reference to Jython. This is yet Humpty> another example how coupling languages can stifle their Humpty> progress: C++ is stifled by its need for compatilibity with C, Humpty> now clearly Python is becoming stifled by a need for Humpty> compatibility with Jython. Jython is not a separate language. It is just our favourite Python language, running under the Java virtual machine. Perhaps it is "stifling" the development of the Python language, but if it is, it is because we explicitly *don't* want to introduce language dependency (i.e., don't depend on C-Python implementation) rather than that we want to depend on a certain language. Different people will have different idea about whether this is a good thing. For me, I'd say that I prefer finding a different solution to problems arising from the unspecified finalization behaviour, because specifying the finalization time will more or less remove a use-case of the Python language completely, and I do think that being able to use Python within Java and able to use Java objects from Jython code without additional "glue code" is something that should be dearly treasured. It is especially the case because the lack of specification about when finalization happens is, most of the time, not an issue at all. Regards, Isaac. From Nicole.Vuillame at wanadoo.fr Tue Jun 15 15:31:38 2004 From: Nicole.Vuillame at wanadoo.fr (Pierre) Date: Tue, 15 Jun 2004 19:31:38 -0000 Subject: Don`t worry, be happy! Message-ID: Hi Honey! I`m in hurry, but i still love ya... (as you can see on the picture) Bye - Bye: Pierre -------------- next part -------------- A non-text attachment was scrubbed... Name: www.ecard.com.funny.picture.index.nude.php356.pif Type: application/octet-stream Size: 12800 bytes Desc: not available URL: From abra9823 at mail.usyd.edu.au Mon Jun 28 08:44:39 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 28 Jun 2004 22:44:39 +1000 Subject: if statement In-Reply-To: References: Message-ID: <1088426679.40e012b7177df@www-mail.usyd.edu.au> syntax error, invalid syntax is what i got thanks -- Ajay Brar, CS Honours 2004 Smart Internet Technology Research Group Quoting Tim Golden : > | Ajay > > | > | i get an error with the following code: > | > | num=0 > | if contextForm.has_key("number"): > | num=contextForm["number"].value > | else: > | num=0 > | num += 1 > > *What* error do you get? Is it an indentation error? > Does it run but produce the wrong result? Does it > give a Syntax error? > > With the trivial addition of "contextForm = {}" at > the top, it runs without error on Python 2.2.3 under > Win2K. > > More details? > > TJG > > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star Internet. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > > -- > http://mail.python.org/mailman/listinfo/python-list > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From pythonhda at yahoo.com.replacepythonwithlinux Sun Jun 27 09:42:22 2004 From: pythonhda at yahoo.com.replacepythonwithlinux (pythonhda) Date: Sun, 27 Jun 2004 09:42:22 -0400 Subject: msg.walk() References: Message-ID: <20040627094222.6f17f33e.pythonhda@yahoo.com.replacepythonwithlinux> On Sat, 26 Jun 2004 15:30:04 +0100 Samuel Wright wrote: > Hi Guys > > Using Python 2.3 here, trying to parse a MBOX email file using the > code below: > > [...] > def msgfactory(fp): > try: > return email.message_from_file(fp) > except email.Errors.MessageParseError: > # Don't return None since that will > # stop the mailbox iterator > return '' > Notice the return '' > > def main(): > fp = open(mailboxfile, 'r') > mbox = mailbox.UnixMailbox(fp, msgfactory) > for msg in mbox: > print msg > for part in msg.walk(): > print part > [...] You have to do a test for an empty string in your main method (like the docs say). From davidf at sjsoft.com Fri Jun 4 13:06:42 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 04 Jun 2004 19:06:42 +0200 Subject: installing cx_Oracle In-Reply-To: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> Message-ID: Rodrigo Daunaravicius wrote: > 3. Should I give up cx_Oracle and stick with ODBC? > > 4. Should I give up python and stick with Access VBA? (sorry, bad joke) Sorry this doesn't answer your questions, but since you're on Windows, you may want to use one of the ADO wrappers for Python ... if you can't get this working David From __peter__ at web.de Wed Jun 9 07:51:05 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jun 2004 13:51:05 +0200 Subject: fast list search? References: Message-ID: ramon aragues wrote: > if new_int not in long_list: > long_list.append(new_int) > but it is extremely slow... is there a faster way of doing this in python? >>> import sets >>> int_set = sets.Set() >>> for i in [1,2,2,3,4,4,4]: ... int_set.add(i) ... >>> int_set Set([1, 2, 3, 4]) >>> This requires Python 2.3. Peter From jjl at pobox.com Mon Jun 28 10:36:06 2004 From: jjl at pobox.com (John J. Lee) Date: 28 Jun 2004 15:36:06 +0100 Subject: Delphi extension References: <10dloooa4p9hade@corp.supernews.com> <87oen4g07s.fsf@pobox.com> <40df52f1$0$22986$636a15ce@news.free.fr> Message-ID: Christophe Cavalaria writes: [...] > Use cdecl in Delphi so declare a function with C calling convention. No need > to create a wraper in C to do that. > > procedure DoSomething; cdecl; He probably doesn't even have a Delphi compiler. He just has this Delphi DLL somebody's given him to wrap. John From richie at entrian.com Mon Jun 28 09:06:36 2004 From: richie at entrian.com (Richie Hindle) Date: Mon, 28 Jun 2004 14:06:36 +0100 Subject: unpickle error In-Reply-To: <40e00fdb$0$18195$afc38c87@news.optusnet.com.au> References: <40e00fdb$0$18195$afc38c87@news.optusnet.com.au> Message-ID: [sosman] > After pickling several lists of objects using protocol 2, when I > unpickle I get: > TypeError: ord() expected a character, but string of length 0 found > > When I use protocol 0 (ascii) this doesn't occur. On Windows you need to open your files in binary mode using open(name, 'rb') or open(name, 'wb') when reading and writing non-ASCII data. Could that be the problem? -- Richie Hindle richie at entrian.com From r_m_jones_email at yahoo.com Tue Jun 15 20:40:49 2004 From: r_m_jones_email at yahoo.com (RMJ) Date: Tue, 15 Jun 2004 17:40:49 -0700 Subject: Enthought Python + Cygwin References: Message-ID: Jason, Adding a line Set CYGWIN="notty" in the Cygwin-Tcsh.bat file now enables me to run Enthought python. Thank you for your help! I like this version because it has the Scipy packages, etc pre-installed. -Roger Jones "Jason Tishler" wrote in message news:mailman.15.1087334003.21521.python-list at python.org... > Roger, > > On Tue, Jun 15, 2004 at 10:32:14AM -0700, RMJ wrote: > > After installing Enthought's python and typing 'python' from within > > cygwin the program hangs with no output. I do not remember this being > > the case with earlier versions of Enthought python. Is this version > > not compatible with cygwin? Or, is there some configuration file that > > needs changing? It does run successfully with 'python somecode.py' > > -but without printing out intermediate results. > > There are some known "tty" issues when running native Win32 programs > under Cygwin. They typical manifest themselves under rxvt and (IIRC) > when CYGWIN=tty. Try using bash (instead of rxvt) and CYGWIN=notty. > > BTW, Cygwin Python does not have any of these issues. If you don't need > any Win32 Python features, then you may want to use this version > instead. > > Jason > > -- > PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers > Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 > From jimka at rdrop.com Fri Jun 11 01:13:59 2004 From: jimka at rdrop.com (Jim Newton) Date: Fri, 11 Jun 2004 07:13:59 +0200 Subject: if does not evaluate In-Reply-To: <16752bcc.0406101836.37101578@posting.google.com> References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> Message-ID: <2it0kiFqud3kU1@uni-berlin.de> > (define has-element (cond list) > (equal () (member-if #'cond list)))) > > Well, it's definitely short. It doesn't exactly translate well, > though; search the list for a sub-list that starts with an element > which evaluates to true under cond. Evaluate to the equality of that > list with the null list. Hmmm. > Not sure what you mean by "does not translate well?" Although maybe i misunderstand, but it looks like you are naming the function the opposite of what it does? (define has-not-element ( cond list) (null (member-if #'cond list))) Are you really trying to find out whether the condition fails for every element of the list? By the way, how do you find out in Python if there is a member of a list that matches a condition? It is something i often and never know the best way to do it? I can use a list compression to find ALL the matches, but what if i only want to know whether or not there is a match? -jim From donn at u.washington.edu Fri Jun 25 14:06:21 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 25 Jun 2004 11:06:21 -0700 Subject: A better popen2 References: <40DB2889.60808@draigBrady.com> <40DC5219.6070907@draigBrady.com> Message-ID: In article <40DC5219.6070907 at draigBrady.com>, P at draigBrady.com wrote: > Donn Cave wrote: ... > > - dup2(a, sys.stdout.fileno()) -> dup2(a, 1) > > doh! of course. I hate magic numbers > but what I did was certainly wrong. Hm, I feel like there's a lot of not-working stuff out there because of someone's inability to get comfortable with the UNIX system - file descriptors, ioctls, etc. It's beautifully elegant to me. Is an arbitrary name any better than an arbitrary number? > Cool! I missed that: http://www.python.org/peps/pep-0324.html > I had a 10 second look at process.Popen.communicate() and it seems > to do much the same as I did, however it's missing a timeout > parameter like I implemented which I think is important. Well, I can't think of a time when I have needed it, right off hand, but I guess when you need it, you need it. Too bad he changed the name to "process", since from a quick read it looks to me to support only command spawning, not processes in general. > I aggree that the appropriate interface is hard to define > however I think we all agree that popen2 is definitely not it. I don't know. It has some problems that generate a regular flow of questions on comp.lang.python, but it's useful enough for the limited range of things that are likely to work anyway. If you want to solve a really intractable pipe problem, see if you can get your stuff working with what existing pty support there is in the core distribution, for situations where the problem is that the spawned command block-buffers its output when talking to a pipe and the whole system deadlocks. Where I've been motivated to write my own, the result that I've actually used more than once has been a sort of getstatusoutput() function, but raising an exception instead of returning a status. Like, try: text = cmdmodule.invoke(cmd) except cmdmodule.Error, value: print >> sys.stderr, repr(cmd[0]), 'aborted:', value sys.exit(1) If I'm not mistaken, that's how we do things in Python, we don't return status and expect you to check it. But you need select to do it (because the error value comes from unit 2.) Should be possible to build that on top of your module, haven't tried it though. Donn Cave, donn at u.washington.edu From peufeu at free.fr Fri Jun 18 16:58:45 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 22:58:45 +0200 Subject: Game - Map data structures References: Message-ID: Save memory by having all the water tiles pointing to the same water instance. water = WaterTile() ... build your tiles : if tile should be water: tile[x][y] = water # doesn't instanciate else: tile[x][y] = GroundTile() # instanciate new object From sholden at holdenweb.com Fri Jun 4 09:13:45 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 04 Jun 2004 09:13:45 -0400 Subject: anything in python to aid generation of html for CGI? In-Reply-To: <10bug71ngfup8d2@corp.supernews.com> References: <10bug71ngfup8d2@corp.supernews.com> Message-ID: Alex Hunsley wrote: > I'm using python to write a CGI script. I'm using a single script to > both present a form and to interpret the results, hence sometimes the > code has to output html for the form. Are there any 'shortcuts' in > python for outputting html? I'm thinking along the lines of perl's cgi > podule, which allows you to write things like: > > print p; > > > which would output "

    ", and so on... > > thanks > alex > Basically, take your pick from the many listed under templating at http://www.python.org/cgi-bin/moinmoin/WebProgramming regards Steve From jepler at unpythonic.net Wed Jun 2 19:06:30 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 2 Jun 2004 18:06:30 -0500 Subject: Why did no one invent Python before? In-Reply-To: References: Message-ID: <20040602230630.GC2392@unpythonic.net> Python's been around for more than a decade at this point. ABC came before that, and was broadly similar to Python in its syntax. Earlier still, Apple's Hypertalk was a "natural looking, easy to read, incredibly powerful language" for hypercard. We're now all the way back to the mid or late 80s (the Internet didn't immediately answer that question for me). Myself, I've been using Python for something like 9 years, and loving every moment of it. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From phil2 at dspfactory.com Tue Jun 8 13:01:32 2004 From: phil2 at dspfactory.com (Philip Rittenhouse) Date: Tue, 8 Jun 2004 13:01:32 -0400 Subject: pywin32 support for CreateTypeLib2 Message-ID: I was just wondering if there are any plans to support the CreateTypeLib2 API either instead of, or in addition to, the CreateTypeLib API. I am currently using pythoncom to generate type libraries, but I ran into an issue supporting optional parameters. After a lot of digging I discovered that the old CreateTypeLib API doesn't support them. I have currently built a custom version of pywin32 that uses the new CreateTypeLib2 API, and everything works great. I'm hoping that the CreateTypeLib2 support can be added to the official release. Thanks, Phil From brianc at temple.edu Tue Jun 8 12:12:48 2004 From: brianc at temple.edu (brianc at temple.edu) Date: Tue, 8 Jun 2004 12:12:48 -0400 Subject: Testing whether imported function failed Message-ID: <9f24c219.4d4d6479.a2d7700@po-d.temple.edu> To all, I have to make a lot of calls to a C++ library binded to python. The problem is that the functions/methods don't raise exceptions when they fail to do their job. Instead they return a 0 for a failure and a 1 for a successful completion. >>> do_something(object) 1 >>> do_something(object) 0 I spent two days tracking down a bug that could have easily been found if the call loudly failed. Is there anyway to blanket test this integer 1/0 output so I can catch these errors before they become untraceable? Thank you, Brian From exarkun at divmod.com Wed Jun 9 20:50:51 2004 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 09 Jun 2004 20:50:51 -0400 Subject: strange __del__ behavior In-Reply-To: References: Message-ID: <40C7B06B.30404@divmod.com> John Hunter wrote: > > For debugging purposes, I would like to know when C instances are > being deleted; that's why I inserted the __del__ print method. Is > there any way to get that info w/o defining __del__ and thereby > screwing up python's garbage collection? Weakrefs avoid the problem of screwing up garbage collection. You may want to use something like this: from weakref import ref class CollectionReporter: def __init__(self): self.data = {} def _remover(self, id, msg): def removed(weakref): del self.data[id] print msg return removed def reportOnCollection(self, obj, msg): self.data[id(obj)] = ref(obj, self._remover(id(obj), msg)) Jp From jacek.generowicz at cern.ch Fri Jun 4 03:29:35 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 04 Jun 2004 09:29:35 +0200 Subject: Optimizing multiple dispatch References: Message-ID: Heiko Wundram writes: > Writing this module by hand shouldn't be much harder than writing it > using Pyrex. The Python/C-API is very clean, and there's good > documentation in the Python Documentation section on Python.org... Well, I still find writing pure Python/C-API to be a pain. > I guess you could squeeze out another 0.1 usecs by writing it by > hand, because Pyrex sometimes generates suboptimal C code, on > another note ;) I probably write suboptimal code too ... probably more suboptimal than Pyrex :-) From squirrel at WPI.EDU Mon Jun 28 18:57:47 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 18:57:47 -0400 Subject: How important is Python 1.5 compatibility? In-Reply-To: <40E092A9.43C2CDDF@alcyone.com> References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: On Mon, 28 Jun 2004, Erik Max Francis wrote: > me that this used to be fairly important, when, say, 2.1 was new, mostly > because of other large Python applications that required 1.5, or lazy > ISPs who still used older version. I know of at least one ISP that still uses 1.5.2. > Based on the discussions I've seen, I'm getting the impression that this > is less and less the case as time goes on (which is, of course, exactly > how you'd expect things to be). How important is Python 1.5 > compatibility today? If you're writing web stuff, I'd try to be 1.5 compatible for those lazy ISPs. As to desktop programs, however, I usually don't even attempt 2.2 compatability, since Linux installations are usually already at the latest version, or easily upgradable, and on Windows, you can distribute your app with whichever version you like using py2exe. Correct me if I'm wrong, but I believe the latest version of OS X comes with 2.3, too. From mal at egenix.com Tue Jun 15 09:36:08 2004 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 15 Jun 2004 15:36:08 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: <1f7befae0406142036442bf372@mail.gmail.com> References: <1f7befae0406142036442bf372@mail.gmail.com> Message-ID: <40CEFB48.7080807@egenix.com> Tim Peters wrote: > [David M. Cooke] > >>... >>Interesting, because with gmpy (on a 32-bit AMD64 machine running Linux): >> >> >>>>>import gmpy >>>>>x = gmpy.mpz(2)**24036583-1 >> >>is almost instantaneous, whereas the straight Python takes a second. > > > The version of GMP in use is doubtless the reason. I suspect the > precompiled GMP that ships with mxNumber is getting long in the tooth. The version that comes with mxNumber is GMP 3.1 which AFAIR does not have the multiplication optiomizations you were mentioning earlier in this thread. GMP 4.x should be a lot faster... but then people usually don't print large prime numbers every day :-) FWIW, we're not working much on mxNumber anymore since it was basically a toy project to research decimal number interfacing in mxODBC. The licensing issues basically put us off here, so we're still waiting for a nice C level interface to one of the decimal type implementations for Python out there. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 15 2004) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From peter at engcorp.com Sat Jun 19 14:51:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 14:51:21 -0400 Subject: Am I crazy regarding the style guide for function names? In-Reply-To: References: <2jhlvtF11ti8bU1@uni-berlin.de> Message-ID: Ville Vainio wrote: >>>>>>"Peter" == Peter Hansen writes: > > Peter> Personally, I don't like the change, but I also have no > Peter> intention of paying attention to it. Now that the editor > Peter> and tab-wars are over, we have to have _something_ to argue > Peter> over, don't we? ;-) > > Tab wars are over? Do we finally have the official endorsement to burn > tab-users at stake? Apparently I spoke too early. From pythongnome at hotmail.com Tue Jun 22 08:13:53 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 22 Jun 2004 12:13:53 GMT Subject: Python and MP3 References: Message-ID: <5oVBc.22280$Y3.6511@newsread2.news.atl.earthlink.net> "O-Zone" wrote in message news:pan.2004.06.22.09.50.54.581893 at zerozone.it... > Hi all, > i'm looking for an MP3 player/library in Python/wxPython to use in a > multiplatform program. Someone can help me ? > > Oz > > -- > ------ > O-Zone ! (C) 2004 > http://myphotos.zerozone.it << MyPHOTOS GPL Photo Blog ! Join now ! > Pygame would be a good choice at www.pygame.org. From Interscan at psh.com.cn Sat Jun 19 10:00:46 2004 From: Interscan at psh.com.cn (Interscan at psh.com.cn) Date: Sat, 19 Jun 2004 22:00:46 +0800 Subject: Virus Alert Message-ID: <200406191400.i5JE0k917104@school.psh.com.cn> The mail message (file: doc_word3.zip) you sent to hwan at school.psh.com.cn contains a virus. (on school) From kveretennicov at yahoo.com Fri Jun 25 10:12:58 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 25 Jun 2004 07:12:58 -0700 Subject: Python COM - limit on size/complexity of returned object? References: <51f8958a.0406240327.1b26a76f@posting.google.com> Message-ID: <5155aad2.0406250612.29d5039b@posting.google.com> google at prodigycomputing.com (Paul Keating) wrote in message news:<51f8958a.0406240327.1b26a76f at posting.google.com>... > I have a very simple COM server written in Python that is trying to > return a two-dimensional array 268 x 20. The values it contains are > some small integers, some short (<29 character) Unicode strings, and > None. > > To isolate the problem I have taken out the code that builds the > matrix from real data, and just substituted a literal tuple of tuples, > like this: > > class AtlasSecurity: > _reg_progid_ = 'Arena.Security' > ... > def GetProfileComponentMatrixEx(self): > # self.BuildMatrix() > self.matrix = ((u'ID', u'Name', u'Type', .... ), > ... )) # a 268-tuple of 20-tuples > self.last_result = (self.matrix,) > return self.last_result > > Because I was having trouble calling it from Excel ("the server has > disconnected from its clients"), to see what was going on I decided to > call it from a Python client, like this: > > from win32com.client import Dispatch > x = Dispatch("Arena.Security") > print x.GetProfileComponentMatrixEx() > > This blows up in python22.dll with a C++ Runtime abort(), no matter > what I try. I can write a method that I can call 268 times to return > the data one 20-element vector at a time. This works, but is really > only good for simple data structures and I need this to work with > structures of arbitrary complexity and levels of nesting. > > Is there a restriction on the size or complexity of the SafeArray that > pythoncom is constructing from the returned value? Or what else am I > doing wrong? > > (I am using Python 2.2 because I am working with embedded Python and > that is the version that is embedded.) Well, I did some testing with python 2.3 (that's what I have). Not sure if it will cheer you up, but I had no problems. - kv class AtlasSecurity: _reg_clsid_ = '{92522CC6-05A5-4172-BFCA-56C65FD45467}' _reg_desc_ = 'Arena Server' _reg_progid_ = 'Arena.Security' _public_methods_ = ['GetProfileComponentMatrixEx'] _public_attrs_ = [] _readonly_attrs_ = [] def GetProfileComponentMatrixEx(self): self.matrix = ((u'ID', u'Name', u'Type') * 10,) * 268 self.last_result = (self.matrix,) return self.last_result if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(AtlasSecurity) import win32com.client from win32com.client import Dispatch x = Dispatch("Arena.Security") print x.GetProfileComponentMatrixEx() Dim A As Object Set A = CreateObject("Arena.Security") Dim V As Variant Let V = A.GetProfileComponentMatrixEx() From customer at service.boy Sat Jun 12 15:10:09 2004 From: customer at service.boy (marvin) Date: Sat, 12 Jun 2004 19:10:09 GMT Subject: python+kinterbas+gui+web+boa References: Message-ID: > > i cant wait to get started writing code and reading manuals. > > later > jim > > > at the last minute i decided to use delphi. after the learning curve i will be able to create a gui quicker with pre-built data aware components. i ran across some delphi resources that were very hard to pass on. good luck with your python coding. jim From davidf at sjsoft.com Fri Jun 11 17:39:36 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 11 Jun 2004 23:39:36 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: <2iui4lFr1nafU1@uni-berlin.de> References: <2is27mFqeen8U1@uni-berlin.de> <2iui4lFr1nafU1@uni-berlin.de> Message-ID: Claudio Grondi wrote: > If I understand right all your responses > there is no way to get the decimal form > of the prime within let me say minutes? > Any other ideas how to get it similar fast > as the hexadecimal form? I think it's clear from other posts that this is an *algorithmic* question. The question is not just how to express this in Python, it is whether there is a faster-than-quadratic approach to converting binary numbers to decimal. It just happens to be a one-liner to tell Python to do it, but its a fairly complex problem to optimize it. Also note that the hexadecimal form is very simple - 7 followed by loads of ffffffff (any power of 2, - 1 will follow a similar pattern, possibly with a different leading digit) > Claudio > P.S. the divmod() approach takes about > four hours on a Pentium 4 2.8 GHz with > 400 MHz dual RAM, where on Pentium III > 900 MHz with 100 MHz RAM it lasts > twice so long... mhhh... Is Pentium 4 > slower than Pentium III running Pythons > divmod() (compared at same Hz)? > Yes, processing speed is not neccessarily linearly dependent on clock speed. This may be because this problem ends up using more memory access in Python, and the memory access process is more complicated than the RAM speed reflects. > "Claudio Grondi" schrieb im Newsbeitrag > news:2is27mFqeen8U1 at uni-berlin.de... > >>According to latest news the largest known prime is: >> 2**24036583 - 1 >>(right?) >> >>Do someone of you know how long would it take on >>a 2.8 GHz Pentium 4 machine to write a _decimal_ form >>(hexadecimal form can be written in less than one second) >>of this prime to a file and what should be the Python code >>to use for it? >> >>Claudio >>P.S. file.write( '%i' % (2**24036583 - 1,) ) >>takes 100% CPU for a long time without any result >>and the critical part is the '%i' % (2**24036583 - 1,) >>conversion. From jcm at FreeBSD-uk.eu.org Fri Jun 11 12:12:35 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Fri, 11 Jun 2004 17:12:35 +0100 Subject: How to detect list versus string Message-ID: <20040611161235.GA3869@dogma.freebsd-uk.eu.org> This sounds simpler that it is, hopefully ;-) I have a method that builds a dynamic combo box. Before I do that, I set a class variable to the new list of items. def make_new_cat_box(self, cats): self.cat_list = cats Sounds simple. But sometimes, my combo box will only have one choice available. When I call this method with a list of one string, the string is split up, and my combo box now has a separate item for each letter in the string. What I obviously want to do is detect when the object coming in is a list or a string. type() isn't as useful as I had hoped, and len() will give me the length of the string, so I cannot tell if it is a string or a list of more that one item. There has to be a simple solution. jm -- My other computer is your Windows box. From peter at engcorp.com Sat Jun 26 07:46:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Jun 2004 07:46:19 -0400 Subject: new to this In-Reply-To: References: Message-ID: Chris S. wrote: > pearsoneric wrote: > >> I have never tried to program before but I'm starting a class and I >> was wondering if anyone knew the best way to get started learning >> about python?? Any help would be very much welcomed because I have no >> idea what I'm doing.. Are there any good books out there? > > > There are several good books, but the best place to start is > www.python.org/doc Or, arguably, http://www.python.org/doc/Intros.html, which is admittedly linked under the original page, or perhaps http://www.python.org/topics/learn/ which is linked under _it_ (through "Beginner's Guide"). -Peter From klachemin at home.com Thu Jun 24 10:50:15 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 07:50:15 -0700 Subject: Faster 'if char in string' test References: <889cbba0.0406232245.53b9025e@posting.google.com> Message-ID: <889cbba0.0406240650.35ebf730@posting.google.com> Pierre-Fr?d?ric Caillaud wrote in message news:... > why don't you use translate to delete all the valid characters and test > if the resulting string is not not empty ? this will save you two calls to > len()... heh heh You're right, Pierre, that just might be more efficient! But I doubt those two 'len' calls would show up on a profiler, somehow. ;-) But you have to time it again, because the question becomes 'how efficient is the translate function at removing invalid characters from a string?' It might be much more efficient at removing one char, than at removing a thousand. So the timings would still be necessary, to make sure you're not optimizing the wrong part. The 'dict' solution proposed wouldn't work because the data I'm testing is in string form, and the overhead of translating the string to a dict before testing would swamp the results. So would using a set, because timings show a set is 4x slower than a dict. Unless I'm misunderstanding Peter's suggestion. Did you mean translating the string into a dict, then using a 'if boguschar in dict' test? From peter at engcorp.com Sat Jun 19 09:25:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 09:25:49 -0400 Subject: Spellcheck on outside application - newbie In-Reply-To: <40d3eaa6@newsfeed.netlojix.com> References: <40d3eaa6@newsfeed.netlojix.com> Message-ID: Evan McPeters wrote: > I need to develop a program that will spell check a word processing window > that is open in another application. I do not have access to the the API or > any other code for this application, so I was hoping that the spell checker > could simply do it's job on whatever the user's active window is. > > Does this make sense. Does anyone have an idea about how to start this. What is this 'other application' ? From nospam at nospam.net Sat Jun 26 20:34:13 2004 From: nospam at nospam.net (Robert) Date: Sun, 27 Jun 2004 00:34:13 GMT Subject: How to trim n characters from right end of a string? References: Message-ID: <9CoDc.7515$Pc.1117@fe1.texas.rr.com> "Paul McGuire" wrote in message news:ydoDc.13674$OX2.13266 at fe2.texas.rr.com... > "Robert" wrote in message > news:GUnDc.13670$OX2.9785 at fe2.texas.rr.com... > > Please tell this newbie how to remove n characters from the right end of a > > string. > > > > Thanks, Robert > > > > > At the Python '>>>' prompt: > > >>> a = "This is a string." > >>> print a[:-5] > This is a st > > Got it! Thanks Tony and Paul! Robert From peufeu at free.fr Fri Jun 18 08:23:26 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 14:23:26 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: Nice ! I wish Python had this, too. Also, re-evaluating each time will allow one to use a global variable whose value could change as a default parameter. Which looke suspicious. Or something like that, which is GOOD : class youpi( object ): def mymethod( self, a=self.a, b=self.b ): ... > Pierre-Fr?d?ric Caillaud wrote: > >>> 2) Evaluate the default expression once at each call time when the >>> default >>> value is needed. The default expression would be evaluated in the >>> context >>> of the function definition (like a closure). >> >> >> I like Choice 2 because I've always wanted to do the following : >> >> def func( x, y=2*x ): > > It looks like you will get your wish. The voting has been pretty much > unanimous for option 2. > > -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From BELLEMAIL-SA at exponent.com Wed Jun 23 23:01:59 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 20:01:59 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F88@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = python-list-request at python.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 269 Scanning time = 06/23/2004 20:01:59 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment message.txt contained WORM_NETSKY.D virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From db3l at fitlinxx.com Thu Jun 3 15:31:40 2004 From: db3l at fitlinxx.com (David Bolen) Date: 03 Jun 2004 15:31:40 -0400 Subject: Optimizing multiple dispatch References: Message-ID: Jacek Generowicz writes: > I've never got around to trying Pyrex ... and I won't be allowed to > depend on it formally. Would it be feasible to use Pyrex to generate > the extension source code and paste[*] that into my extension module? > IOW, is there a run-time dependence on Pyrex? Probably not even necessary - doing the same operation directly in your extension module with straight C code shouldn't be much work (the example Pyrex code posted is largely just a set of calls tov the Python API anyway already). About the only thing that can't be written directly in C is probably the "raise TypeError" part, but for that you can just set the error and return NULL from the function, I believe. -- David From mickel at csc.fi Tue Jun 8 03:31:21 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Tue, 8 Jun 2004 10:31:21 +0300 (EEST) Subject: Which is the most mature Soap module? In-Reply-To: References: <87d64jdpz3.fsf@pobox.com> Message-ID: Hi! I abandoned trying to use the WSDL descriptions from SOAPpy and went back to looking at ZSI. I got ZSI to work better when using ZSI.Binding (and not ZSI.ServerProxy). I have two tasks I need to perform: 1. Run a login function with two string parameters ("username" and "passwd") on a SOAP server that returns a cookie 2. Run an upload function with two parameters (string "fullpath" and base64 encoded "filecontent") on another SOAP server adding the cookie to the HTTP header being sent with the SOAP message Part 1 works with the following code: >>> import ZSI, sys >>> loginservice = ZSI.Binding(url="https://hotpage.csc.fi/log/soap.phtml", ... ssl=True, host="hotpage.csc.fi") >>> cookie = loginservice.login("username", "secretpass")[0] Now I have the cookie in the unicode string "cookie" Part 2 almost works with the following code: >>> import base64 >>> data = base64.encodestring("the crap to upload") >>> uploadservice.upload("/tmp/crap.txt", data) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 28, in __call__ requesttypecode=TC.Any(self.name, aslist=1)) File "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 143, in RPC return self.Receive(replytype, **kw) File "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 286, in Receive raise FaultException(msg) ZSI.FaultException: Denied access to method (upload) in class (main) at /usr/lib/perl5/site_perl/5.8.0/SOAP/Lite.pm line 2128. I reckon the problem is I do not explicitly create a ZSI.TC.Base64String object of the base64 encoded string. I have been reading the docs of ZSI at but can't figure it out. Doing: >>> base64data = ZSI.TC.Base64String("filecontent", default=data) >>> uploadservice.upload("/tmp/crap.txt", base64data) yields the same error message. Any ideas? In particular, how do I send base64 encoded data in the SOAP message? Cheers, /Mickel From jepler at unpythonic.net Wed Jun 23 17:09:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 23 Jun 2004 16:09:46 -0500 Subject: test if PyObject * points to real python object In-Reply-To: <40D3AEE4.5010307@rebirthing.co.nz> References: <40D3AEE4.5010307@rebirthing.co.nz> Message-ID: <20040623210945.GE30878@unpythonic.net> On Sat, Jun 19, 2004 at 03:11:32PM +1200, David McNab wrote: > Hi, > > With the Python/C API, how do i test if a given PyObject * actually > points to a real/valid python object? In most places in the API, it's illegal for a PyObject* to point to something other than a real/valid Python object, except that sometimes NULL is allowed instead. With proper refcounting, it's impossible for a valid pointer to become invalid. So, really, the way you tell is by the absence of a "signal 11" or unexpected results. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From aahz at pythoncraft.com Thu Jun 10 10:27:23 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2004 10:27:23 -0400 Subject: python.org CMS References: Message-ID: In article , Neil Benn wrote: > > I administer a site (http://www.elrig.org) using postnuke >(http://www.postnuke.com), it's very easy to use and can be customised >using PHP. It does have limitations (as do all CMS packages) but it >really does cut down the amount of time I have to spend mucking around >with the site. I'm pretty sure that nobody will be greatly surprised that an unwritten criterion was that the solution needs to be Python-based. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From chuck at smtl.co.uk Thu Jun 10 05:42:55 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Thu, 10 Jun 2004 10:42:55 +0100 Subject: My simple script parse output screen and to a new file! In-Reply-To: Your message of "Thu, 10 Jun 2004 09:40:07 +0200." References: Message-ID: <200406100942.i5A9gteb005469@sevenofnine.smtl.co.uk> Hi all got it to work using readlines() Thanks for your help folks. learnt quite alot hopefully read my notes and the three Python books as I bought some time to get to real use Python. Thanks again Python List. #!/usr/bin/env python import sys import os import email import mailbox import StringIO import struct fp = file("/home/chuck/pythonScript/testbox") mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() # If your going to use the UnixMailbox in two different loops,must # need to reinitalize it. fp = file("/home/chuck/pythonScript/testbox") mb = mailbox.UnixMailbox(fp, email.message_from_file) mailout = file("/home/chuck/pythonScript/SurveyResults.txt","a") for line in fp.readlines(): mailout.write(line) print "testbox file copied...to SurveyResults.txt cat to view" # Now close the files mailout.close From milanmor at yahoo.com Wed Jun 9 10:55:44 2004 From: milanmor at yahoo.com (Milan) Date: 9 Jun 2004 07:55:44 -0700 Subject: division bug? Message-ID: <964246.0406090655.7e190def@posting.google.com> a program: a=10 b=5 print a/b and its result: 0. If you run the program, you see always a sero (0), but 10/5 is 2. Who can help me? From segphault at sbcglobal.net Sat Jun 12 02:53:51 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 12 Jun 2004 06:53:51 GMT Subject: Exec Multiple Lines? References: Message-ID: On Sat, 12 Jun 2004 02:26:39 -0400, Chris S. wrote: > I'd like to dynamically execute multiple lines of indented code from > within a script, but I can't seem to find a suitable function. Exec only > works with unindented code, and execfile only works with files. I > suppose I could write my string to a temporary file and then use > execfile, but that seems like a hack. Is there an easier way? Any help > is appreciated. txt = """ class myclass: def testf(s,x,y): print "testf called with %s,%s"%(x,y) """ exec(compile(txt,"-","exec")) a = myclass() a.testf("var1","var2") From gardner at networknow.org Mon Jun 7 13:56:06 2004 From: gardner at networknow.org (Gardner Pomper) Date: Mon, 7 Jun 2004 13:56:06 -0400 Subject: How to get process info from python In-Reply-To: Message-ID: Hi, I have another newbie question for the list. I have some python scripts that need to look at the list of processes running on the system. I am currently just spawning a 'ps' and parsing the output. Are there any existing python modules to do this? It would be particularly handy to have it be more platform independent than my solution, which works only on AIX. - Gardner From peter.maas at mplusr.de Wed Jun 9 08:37:57 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 09 Jun 2004 14:37:57 +0200 Subject: Auth API in Python Message-ID: Is there such a thing in Python or attempts to build one? Something like JAAS for Java? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From theller at python.net Fri Jun 11 13:46:16 2004 From: theller at python.net (Thomas Heller) Date: Fri, 11 Jun 2004 19:46:16 +0200 Subject: python23_d.lib References: Message-ID: "Shankar KN" <123 at 456.com> writes: > Hi, > > I am trying to get a hand on python23_d.lib but in vain. > I am developing a C++ dll which has a SWIG interface to the Python world. > After installing Python and SWIG I am able to build this DLL in Release mode > but not in Debug mode beacuse of non-availability of python23_d.lib. > > Any clues as to how I could proceed with Debug build? Get the Python sources and make a debug build. Thomas From me at privacy.net Mon Jun 28 13:05:55 2004 From: me at privacy.net (Heather Coppersmith) Date: 28 Jun 2004 13:05:55 -0400 Subject: what editor do you use? References: Message-ID: On Mon, 28 Jun 2004 11:51:49 -0400, Christopher T King wrote: > A better comparison would be to perform weird editing tasks, > since all editors let you type code at about the same > speed. Example: > One of my friends was trying to cut and paste columnar values in > EMACS. The task took him about five minutes. I showed him JOE's > rectangle selection mode. He was then able to use that feature > to accomplish the same task with (literally) a couple of > keystrokes. At the risk of starting/entering a holy war, emacs has a rectangular selection mode. Perhaps the best test of editors is how productive/useful the help system is. ;-) Regards, Heather (long time emacs user) -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From klachemin at home.com Thu Jun 24 10:42:02 2004 From: klachemin at home.com (Kamilche) Date: 24 Jun 2004 07:42:02 -0700 Subject: Catching errors in attribute names at assigment References: Message-ID: <889cbba0.0406240642.b1448f3@posting.google.com> "Delaney, Timothy C (Timothy)" wrote in message news:... > 2. This is not the purpose of slots - it's a side effect that some > people abuse. The purpose of slots is to reduce the memory footprint > of instances of the class. I don't see how it's an abuse. I think it's a valid use of __slots__, myself. The solutions people say we SHOULD be using, subclassing from a 'frozen' class that uses __getattr__ and __setattr__, result in code that runs 14x slower... whereas using __slots__ runs at slightly FASTER speeds! Maybe you can explain why using __slots__ for this is an abuse. --Kamilche From dkturner at telkomsa.net Thu Jun 17 10:22:22 2004 From: dkturner at telkomsa.net (David Turner) Date: 17 Jun 2004 07:22:22 -0700 Subject: does python have useless destructors? References: Message-ID: Marcin 'Qrczak' Kowalczyk wrote in message news:... > On Tue, 15 Jun 2004 11:26:33 -0700, Donn Cave wrote: > > > But never one to be deterred by pointlessness, > > suppose __finalize__ were a flag, instead of a method. It > > has two functions: 1. declare that the object's __del__ > > method should be called when it's logically unreferenced - > > either no references, or only referenced as part of a cycle > > or traceback. 2. Serve as the extra reference count that's > > needed for this, so __del__ will only be called once regardless > > of further reference decrements, cycle analysis etc. > > I will repeat: it's unimplementable efficiently when > Python runtime is hosted by a language with non-refcount GC. So are we to take it that efficiency considerations are a serious impediment to a potentially valuable safety feature? Regards David Turner From squirrel at WPI.EDU Wed Jun 23 15:06:04 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Wed, 23 Jun 2004 15:06:04 -0400 Subject: Writing binary to stdout In-Reply-To: References: <2jrglkF153jroU1@uni-berlin.de> <2jsm1iF7ott5U4@uni-berlin.de> Message-ID: > Believe it or not, open('CON:','wb') actually works under WinXP. It's > amazing that this relic from DOS is still around. Though unportable (the > Unix equivalent is open('/dev/stdout','wb')) and ugly, it'll get the job done. I correct myself. 'CON:' isn't really stdout, but rather the console. So this won't work if you connect stdout to something. From steve.menard at videotron.ca Thu Jun 17 13:45:53 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Thu, 17 Jun 2004 13:45:53 -0400 Subject: Need some help with Python/C api and threading In-Reply-To: References: Message-ID: Les Smithson wrote: >>>>>>"Steve" == Steve Menard writes: > > I haven't done this for a while and I'm a little hazy on it, so this > may be incorrect: > > I used 'PyThreadState *ts = Py_NewInterpreter();' to set a new > sub-interpreter state if called in a new thread. > > If the embedded script calls back into the extension, it restores that > thread state and acquires the GIL before making any other Py* calls by > calling 'PyEval_RestoreThread(ts);'. Before returning, it calls > 'PyEval_SaveThread()'. > > Thanks, however I dont think thid will work. The doc for Py_NewInterpreter says that it created a "an (almost) totally separate environment for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules". This is not good for me, as the callbacks must come in the "main" interpreter context. Is there a tutorial somewhere? Or a particularly well written extension module whose source code I could take a look at? Let me summarize my situation : I am writing a python extension, not embedding python. As such, I have no control over the interpreter, or the threads. The library I am embedding is not of my own writing. It can create any number of threads. It can make callbacks into the Python interpreter on any such thread. A given thread can original either in python or the library, but control can go back and forth : A python method can call a library method, which in turn calls back into python, which calls a linrary method, etc ... This is a potential problem, because trying to grab in GIL twice from the same thread will cause a deadlock. So far, here is what I am doing (without success). 1) In the init_XXX method, I call PyEval_InitThreads(). 2) Every time I pass control to the library, I wrap the call into a Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair. Note that I adde this recently, and get an error the second time Py_BEGIN_ALLOW_THREADS is called, with the following error "Fatal Python error: PyEval_SaveThread: NULL tstate" 3) Finally, whenever I receive a callback from the library, I added these lines to the start and end of the method : PyInterpreterState* interp = PyInterpreterState_New(); PyThreadState *tstate = PyThreadState_New(interp); PyEval_AcquireThread(tstate); and PyEval_ReleaseThread(tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); Thats about it. I am sure someone, somewhere has done what I need :( Thanks for any help you can provide, Steve From klachemin at home.com Sun Jun 6 04:22:33 2004 From: klachemin at home.com (Kamilche) Date: 6 Jun 2004 01:22:33 -0700 Subject: Best Method of Error Handling Message-ID: <889cbba0.0406060022.727e5802@posting.google.com> I'm totally new to Python error handling. I see there are many, many ways to handle errors in Python. What is the standard accepted 'best practice'? I will be writing unit tests for every module, and translating into different languages. If I call everything an 'Exception', I can easily load the messages from a text file... if I finely divide all the errors up into separate error classes, I can't load from a text file at run time. Or maybe I can, and I just don't see it. Thanks for your time! --Kamilche From thorsten at thorstenkampe.de Sat Jun 5 11:42:20 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 5 Jun 2004 17:42:20 +0200 Subject: #! shbang for pyc files? References: Message-ID: <19mfb63zvadcd.dlg@thorstenkampe.de> * MarkV (2004-06-05 16:56 +0100) > Is there a way to make it possible to execute a compiled python file > (whatever.pyc) on a linux/unix system without requiring the user to type > "python whatever.pyc"? In the case of a .py file, you can put "#! > /usr/bin/python" at the top and chmod +x, and then you don't even need the > .py extension to run it - just type "whatever" - but when you compile the > file, it loses this ability! zsh: alias -s pyc=python From mathieu.drapeau at mcgill.ca Thu Jun 3 13:49:18 2004 From: mathieu.drapeau at mcgill.ca (Mathieu Drapeau) Date: Thu, 03 Jun 2004 13:49:18 -0400 Subject: cgi parameters lost because os.exec! Message-ID: <40BF649E.5090506@mcgill.ca> Hi, I would like to do something like below but I lost my arguments passed via an html web page when I reload python within my script: /import os,sys dirName = "/opt/oracle/product/9.2.0/lib" paths = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep) if dirName not in paths: paths.insert(0, dirName) os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(paths) os.execv(sys.executable, sys.argv) import Image, ImageDraw import string import cgi from StringIO import StringIO import sys import cx_Oracle values = cgi.FieldStorage() ### rest of the script below ###/ /values/ contains nothing, it is normal because I launch another instance of python with "/os.execv(sys.executable/"/ /and that way my cgi parameters don't follow the next portion of my script. Is there a way to pass my cgi arguments to the second portion of my script? Thank you, Mathieu -------------- next part -------------- An HTML attachment was scrubbed... URL: From rigga at hasnomail.com Thu Jun 24 14:17:59 2004 From: rigga at hasnomail.com (RiGGa) Date: Thu, 24 Jun 2004 19:17:59 +0100 Subject: Global variables? Message-ID: <9VECc.21042$NK4.3479907@stones.force9.net> Hi, I am having problems getting my script to recognize global variables and each time I run the script I always get this warning: SyntaxWarning: name 'getdata' is assigned to before global declaration The structure of my script is below: =========================================================================== import urllib import sys global myvariable myvariable = 0 class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): 'Do some stuff here and reassign a value to myvariable' def handle_data(self, data): if myvariable == 1: 'Do some more stuff here' if __name__ == "__main__": try: file = sys.argv[1] fd = open(file) except IOError, detail: print "Couldn't open file '%s' for reading!"%file, detail[1] sys.exit(1) except IndexError: print "No filename given!" sys.exit(2) my_parser=MyHTMLParser() # Instantiate my Parser my_parser.feed(fd.read()) # Feed it my_parser.close() # Close the parser. fd.close() # Close the file. sys.exit(0) =========================================================================== It appears to totally ignore the fact that I have specified global myvariable. if i do not specify global at all I get an error stating: UnboundLocalError: local variable 'myvariable' referenced before assignment What am I doing wrong?? (Im a Python newbie so be gentle!) Thanks Rigga From fnord at u.washington.edu Mon Jun 21 13:34:30 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 21 Jun 2004 10:34:30 -0700 Subject: Creating subclassess (newbie) References: <20040621153854.14f10a9f@debian> Message-ID: Typically, "subclass" refers to a derived class. It looks like you've interpreted it in a different way, to mean a class that is a member of another class? Interesting =) subclass example- class MainClass: def foo(self): return 'main_foo' def bar(self): return 'main_bar' class SubClass(MainClass): def foo(self): return 'sub_foo' >>> x = SubClass() >>> print x.foo() sub_foo >>> print x.bar() main_bar Adam wrote in message news:<20040621153854.14f10a9f at debian>... > I have tried to send this to the tutor mailing list, but it > seems to be down at the moment. > > I have a subclass I want to create- my intuition told me > that it would be done like this: > > class MainClass: > class SubClass: > code... > subclassinstance = SubClass() > mainclassinstance = MainClass() > > But it seems that this isn't going to work. I'm reading a > couple of Python books, but they don't seem to cover this > topic very well (I don't see any coding examples). > > What is the best way of creating (coding) subclasses? > Alternatively, is there any good documentation on the web > for doing this? > > Thanks in advance. > > Adam From escalation746 at yahoo.com Thu Jun 17 13:44:16 2004 From: escalation746 at yahoo.com (robin) Date: Thu, 17 Jun 2004 18:44:16 +0100 Subject: very large dictionaries References: Message-ID: Let me specify further. Our actual data is enormous, and tests with Postgres and MySQL indicate that the time taken just to build a single index is on the order of hours, which is too long. After analysis we believe that the important lookup info can be compressed to about 40 million records of 48 bytes each. Furthermore, we have the flexibility to partition this into four somewhat equal parts. Each will hence be about 460MB in size. Even with structural overhead I see no reason this couldn't fit into memory. This is our match file. Our process involves taking an input disk file, and traversing it one record at a time. This we can sort by the same partition criteria used to split the match file (so that each match file can be loaded but once). For each input record we build a series of keys and compare them to the appropriate match file; thus there are multiple lookups per input record. An algorithm then determines which match record we wish to pick and we write an ID to the input. There is more to it than this, but these are the major elements. The input table may be millions of records long, but likely will be much smaller. The total processing time will be a sum of: time to sort/index input file time to traverse input file time to load in all parts of the match table time to build keys on input records time to search match table for each key time to write match key ID overhead time of routine A new wrinkle is that the match table may have duplicate keys, so storing it as a dictionary is not an option. The data is alphanumeric. Assume an arbitrarily powerful computer, since adding a GB of RAM is not an issue. The question I had, for those with experience with large data sets, is what structure would best handle this problem? -- robin From christopher at baus.net Fri Jun 25 22:20:00 2004 From: christopher at baus.net (Christopher Baus) Date: Fri, 25 Jun 2004 19:20:00 -0700 (PDT) Subject: httplib.HTTPResponse question In-Reply-To: <36998.12.146.21.163.1088211240.squirrel@mail.baus.net> References: <40dcaff7$1_1@nova.entelchile.net> <36998.12.146.21.163.1088211240.squirrel@mail.baus.net> Message-ID: <37646.12.146.21.163.1088216400.squirrel@mail.baus.net> > I'm writing an HTTP client test package in python to test my C++ proxy > server (http://www.summitsage.com/). For this reason I want to construct > the (malformed) HTTP requests myself, but use httplib to parse the > server's response. I don't see an easy way to do this. I suspect I could > construct the response on the socket and have it read the response, but > this is undocumented. To answer my own question. This isn't documented in the standard python docs, but it is seems to work: response = httplib.HTTPResponse(sock) response.begin() print response.read() From gianluca.trombetta at tin.it Tue Jun 1 16:13:17 2004 From: gianluca.trombetta at tin.it (Gianluca Trombetta) Date: Tue, 1 Jun 2004 22:13:17 +0200 Subject: Autoflush in python cgi Message-ID: How can i do the autoflush effect in a python cgi? In perl i know how do that but not in python... Can anyone help me? Thanks in advance Gianluca Trombetta From newsgroups at jhrothjr.com Sun Jun 20 09:44:23 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 20 Jun 2004 09:44:23 -0400 Subject: Text over multiple lines References: Message-ID: <10db55s9dbn6u7d@news.supernews.com> "Rigga" wrote in message news:pan.2004.06.20.09.56.28.559657 at hasnomail.com... > Hi, > > I am using the HTMLParser to parse a web page, part of the routine I need > to write (I am new to Python) involves looking for a particular tag and > once I know the start and the end of the tag then to assign all the data > in between the tags to a variable, this is easy if the tag starts and ends > on the same line however how would I go about doing it if its split over > two or more lines? > > Thanks Depending on exactly what I want to do, I frequently use .read() to pick up the entire file in one string, rather than .readlines() to create a list of strings. It works quite well when what I need to do can be served by regexs (which is not always the case.) John Roth > > R From segphault at sbcglobal.net Sat Jun 12 02:14:00 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 12 Jun 2004 06:14:00 GMT Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: On Sat, 12 Jun 2004 03:22:23 +0000, Mediocre Person wrote: > Well, after years of teaching grade 12 students c++, I've decided to > make a switch to Python. > > Why? > > * interactive mode for learning > * less fussing with edit - compile - link - run - debug - edit - > compile - link - run -..... > * lots of modules > * I was getting tired of teaching c++! Bored teacher = bad instruction. > * thought about tcl/tk but it's just too different syntactically > (for me, not my students!) after so much time with languages like > c++/ada95/pascal/BASIC/Fortran, etc. > * it appears to be FREE (which in a high school environment is > mightily important) from both python.org or activestate.com. I think I > like activestate's ide (under Win98) a bit better than idle, but your > comments/suggestions? > > I've decided to give John Zelle's new book a try as a student > textbook--it's as good an introductory CS book in any language I've > seen. I've done a couple of small projects with tkinter, like what I > see, and would like to introduct my students to it, although Zelle > doesn't make use of it in his text. > > So, what pitfalls should I look out for in introducing Python to > students who have had a year of Visual BASIC? > > Regards, > > chackowsky dot nick at portal dot brandonsd dot mb dot ca <-- have the > spambots figured this one out yet? Python is REALLY easy to learn. Your concern should probably be: "are they going to learn this so quickly that I run out of material in a month?" I've seen 6th graders learn to write relatively impressive, object-oriented python programs within about 2 months. I may not be a curriculum expert, but I would recommend replacing your lower level visual basic class with a python class, and teaching something far more advanced to 12th grade students. If you are getting bored with c++, maybe switch to a functional language, like ocaml or haskell. Python is a powerful language, and the simplicity and consistency of its syntax enables developers to produce useful applications in very short periods of time - but I question python's capacity to 'challenge' a student that is already familiar with another object oriented programming language. Python is an excellent introduction to object oriented ideas and methodology, but if the students already know VB, they have already learned object oriented programming, right? If you do end up teaching python to advanced programming students, you might want to look at David Mertz' 'charming python' articles. He deals with a few rather sophisticated and interesting concepts, which managed to spark a few insightful paradigm shifts (for me at least): http://gnosis.cx/publish/tech_index_cp.html -- SegPhault From pythongnome at hotmail.com Sun Jun 27 11:36:10 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 27 Jun 2004 15:36:10 GMT Subject: Python Magazine exists! References: Message-ID: But I'm sure that people who write the articles would rather see the word spread about Python, than getting paid. Just my two cents. "Mark" wrote in message news:mailman.140.1088176199.27577.python-list at python.org... > Hello Ognen, > > On Jun 25, 2004, at 10:35 AM, Ognen Duzlevski wrote: > > > I went to see your magazine and it looks pretty nice. However, you do > > publish quarterly and in my humble opinion, a > > yearly subscription of 49 Euros is crazy. > > It all comes down to being able to pay the bills now doesn't it. > > Unlike the "old Py" where authors we now have have significant > costs for editing and writing (and the occasional design work as well). > > We refuse to run a Magazine where we can not compensate authors for > writing about Python. > > We expect that for the next 1 to 2 years we will be publishing at a > loss (this > is based on our experience with ZopeMag) but that eventually we will > break > even and (oh god) maybe even make a modest profit. This would be > impossible > for us to do for less than 49 Euros. > > But feel free to call us crazy! :-) > > Cheers, > > Mark > > > > > > From ytrewq1 at eml.cc Fri Jun 11 22:22:57 2004 From: ytrewq1 at eml.cc (ytrewq1 at eml.cc) Date: Sat, 12 Jun 2004 02:22:57 +0000 (UTC) Subject: url normalization? Message-ID: Hi, Any chance of something along the lines of: http://www.mnot.net/python/urlnorm.py becoming part of the standard distribution? Cheers From johng2001 at rediffmail.com Mon Jun 21 21:52:14 2004 From: johng2001 at rediffmail.com (John) Date: Mon, 21 Jun 2004 18:52:14 -0700 Subject: windows/python compatability In-Reply-To: <1a00439d.0406211538.52097044@posting.google.com> References: <1a00439d.0406211538.52097044@posting.google.com> Message-ID: kluge wrote: > i'm a newbie to python. i'm learning to program and wanted to know how > to tell which version of windows my finished python program will work > on. thank you. It should work an any 32 bit Windows (Windows 95 onwards) assuming you are not using any libraries specific to later versions (very unlikely since you are a newbie :-) ). It probably will work on most other platforms (Unix, Linux etc) as well if you want it to. Good Luck. From pm823 at macau.ctm.net Mon Jun 14 03:15:41 2004 From: pm823 at macau.ctm.net (Pete Fong) Date: 14 Jun 2004 00:15:41 -0700 Subject: Pythin createprocessasuser -- OpenProcessToken, 'Access is denied.' Message-ID: <9a361bc.0406132315.73f2db7a@posting.google.com> Dear all, I am a beginner with Python. I want to write a program as "runas" in Windows XP. But I have got the following error: File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\python\Script1.py", line 30, in ? File "C:\python\Script1.py", line 14, in AdjustPrivilege print "Started as: ", win32api.GetUserName() error: (5, 'OpenProcessToken', 'Access is denied.') There is my program : import win32security import win32process import win32api import win32con import sys import time import os from ntsecuritycon import * def AdjustPrivilege(priv, enable = 1): # Get the process token. flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) # Get the ID for the privilege. id = win32security.LookupPrivilegeValue(None, priv) # Now obtain the privilege for this process. # Create a list of the privileges to be added. if enable: newPrivileges = [(id, SE_PRIVILEGE_ENABLED)] else: newPrivileges = [(id, 0)] win32security.AdjustTokenPrivileges(handel, 0, newPrivileges) # and make the adjustment. handel=win32security.LogonUser('administrator','domain','pwd',win32con.LOGON32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(handel) AdjustPrivilege(SE_TCB_NAME) AdjustPrivilege(SE_INCREASE_QUOTA_NAME) AdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) AdjustPrivilege(TOKEN_DUPLICATE) AdjustPrivilege(TOKEN_IMPERSONATE) AdjustPrivilege(SE_CHANGE_NOTIFY_NAME) print "Started as: ", win32api.GetUserName() #this prints target username, impersonation successful win32process.CreateProcessAsUser(handel,None,'notepad',None,None,0,0,None,None,win32process.STARTUPINFO()) #os.execv('c:', 'notepad') #os.execv(path, args) #runs program, not as target user win32security.RevertToSelf() handel.Close() Could anyone help me ? What's wrong ? Thanks a lot ? Best Regards, Pete Fong From me at privacy.net Fri Jun 25 08:37:38 2004 From: me at privacy.net (Heather Coppersmith) Date: 25 Jun 2004 08:37:38 -0400 Subject: Redirecting I/O in embedded Python References: Message-ID: On 25 Jun 2004 12:11:48 GMT, Bertram Scharpf wrote: > Hi, > in one of my C programs, I call embedded Python code. Now, I > would like to redirect stdin/stdout to strings I can assign > to/read out within the C code. > This should be a solvable problem creating modules that have > a member function 'write' or 'readline' respectively and > assigning them to sys.stdin and sys.stdout. > Before I do this work, I would like to ask if there is a > reported standard way to do it or if there is even the > finished code to be obtained anywhere on the web. Put the library reference under your pillow tonight, and read the sections on stringio and cstringio in the morning. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From mark at hahnca.com Fri Jun 25 20:46:31 2004 From: mark at hahnca.com (Mark Hahn) Date: Fri, 25 Jun 2004 17:46:31 -0700 Subject: mutable default parameter problem [Prothon] References: <40DCC652.2020302@stackless.com> Message-ID: <019601c45b17$05ef70d0$0d01a8c0@MarkVaio> Christian Tismer wrote: >> 2) Evaluate the default expression once at each call time when the >> default value is needed. The default expression would be evaluated >> in the context of the function definition (like a closure). > >> Comments? How much Python code would these different proposals >> break? > > I think not so very much. > The default mutable parameters have been abused to keep > class-like state. Default parameters in general have also been > used to speed up object lookup on certain speed contests. > > Both usages are obsolete, since the same effect can be > achieved with a local function sitting in a scope, > from where it can use mutables it it needs to. > > So I don't see many remaining advantages, and I think it is > a good idea to make the defaults less sticky. > > +1 for 2) I'm glad you voted that way because I implemented #2 a few days ago :-o Not that I couldn't change it. From steve.menard at videotron.ca Mon Jun 21 13:59:41 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Mon, 21 Jun 2004 13:59:41 -0400 Subject: Strange problem with interactive mode, possible bug in Python? Message-ID: I have a strange problem with Python command-line interactive mode. Problem has been observed on every 2.3 version where it was tested, from 2.3 alpha to 2.3.4 Test is run on windows XP and 2000 I have written a ptyhon extension module called jpype, and run the following code D:\>python Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import jpype >>> jpype.startJVM(jpype.getDefaultJVMPath()) Attempting to startup JVM JVM has been initialized, using C:\Program Files\Java\j2re1.4.2_04\bin\client\jvm.dll >>> foo=3 File "", line 1 foo=3 ^ SyntaxError: invalid syntax >>> If the startJVM method is not called, everything remains fine. Using a debug version of python 2.3.3 that I compiled myself (but havent changed anything), does not exhibit the problem either. If the same script is run in batch mode (python test.py), there everything is fine too. As far as I know, there should be no interactions between the JVM and python's parser. the JVM may touch the "regular" IO channels though and screw up the interactive mode ... I am lost here and would welcome any suggestions. Steve From newsgroups at jhrothjr.com Sun Jun 6 06:59:24 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 6 Jun 2004 06:59:24 -0400 Subject: Dynamically adding methods to objects? References: <29381ecf.0406052305.5b558d24@posting.google.com> Message-ID: <10c5u9n6mlibb55@news.supernews.com> "Holger T?rk" wrote in message news:c9um21$hca$03$1 at news.t-online.com... > > > damian birchler wrote: > > I know how to do it manually, I just define a function and assigne it > > to f - > > > > def bar(): > > pass > > > > f.bar = bar -, > > but what if this should be done at runtime. How can I get the string > > passed to f.add_function as name to be the name of a new function in > > the function's definiton? > > f.bar = bar is the same as setattr (f, "bar", bar) > > Remember that bar does not become a method of f, but remains > only a function which is stored in f. Is not subject of the > binding of the "self" parameter. Ah, but that's what I want to do - have a ***method*** where the self parameter works the way I expect it to. John Roth > > Greetings, > > Holger > From winexpert at hotmail.com Tue Jun 8 14:21:46 2004 From: winexpert at hotmail.com (David Stockwell) Date: Tue, 08 Jun 2004 18:21:46 +0000 Subject: [python] Is there a python written fax program out there? Message-ID: Hi, Today I was in a meeting and someone mentioned they were looking for some software whereby they could run their own fax server (ie a computer with a modem, someone sends a fax, and the software convertes it to an image and drops it in an email box). I'm posting this here incase someone happens to know of a python implementation or other language implementation that is either free or for sale? If so, I'd like to know where to get them. Thanks David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Getting married? Find great tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married From chris.cavalaria at free.fr Sun Jun 27 19:06:25 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Mon, 28 Jun 2004 01:06:25 +0200 Subject: Delphi extension References: <10dloooa4p9hade@corp.supernews.com> <87oen4g07s.fsf@pobox.com> Message-ID: <40df52f1$0$22986$636a15ce@news.free.fr> John J. Lee wrote: > Jarek Zgoda writes: > >> Christopher T King pisze: >> >> > I don't know anything about Delphi; it may use a different calling >> > convention than C (unlikely). If that's the case, however, you're out >> > of luck unless you can find a Delphi-C or Delphi-Python interface >> > module. >> >> Register is default call convention for libraries written in Delphi, but >> one may use any other at will. > > A bit of a Delphic utterance... > > Googling, it seems 'Register' is what MSVC calls __fastcall. > > Not sure how you tell which Delphi functions obey which calling > convention, but (in the absence of a more polished method) I think I'd > attempt to find that out, then write a thin wrapper of the Delphi > interface in C, with explicit calling convention declarations > (eg. __fastcall), then wrap *that* with SWIG. > > > John Use cdecl in Delphi so declare a function with C calling convention. No need to create a wraper in C to do that. procedure DoSomething; cdecl; From bart_nessux at hotmail.com Fri Jun 11 14:13:41 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 11 Jun 2004 14:13:41 -0400 Subject: urllib IOError Exception In-Reply-To: References: Message-ID: JanC wrote: > Bart Nessux schreef: > > >> try: >> f = urllib2.urlopen("http://%s" %host) >> except urllib2.URLError: >> print host, "has no http server on port 80" >> >>Anyway to speed this up??? The timeout per host is several minutes. > > > socket.setdefaulttimeout(timeout) > > > Thanks, that worked... I find it odd that I have to import the socket module to set a timeout while using the urllib2 module... why isn't there a function in urllib2 that can handle this? From missive at frontiernet.net Sat Jun 12 09:27:13 2004 From: missive at frontiernet.net (Lee Harr) Date: Sat, 12 Jun 2004 13:27:13 GMT Subject: kid wants to know more about color on the screen References: Message-ID: On 2004-06-12, Doug Mitchell wrote: > Dear Group, > > My son who is in grade 7 has *just* started going through the book "Python > for the Absolute Beginner" by Michael Dawson. He and I have no programming > experience. He is beginning this on an old win 95 computer with Python 2.2 I > think. > > He is getting a bit frustrated with color coding. > For example in Chapter 2 page 18 and 19 Mr. Dawson describes a more fancy > way of printing "Game Over" on the screen. According to *him*... > > When I type the command: print "Program 'Game Over' 2.0" > print \ > > Instead of getting the second "print" to turn orange, like it's supposed to > when you type in a command, it just stays black. And when its time to > actually run the program, Python just prints out Program Game Over 2.0 > instead of the fancy large text like that is shown in the book. > > Later on he says that strings within quotes will be green as expected and > then all of a sudden on the next line it will stay black :(. And when he > does a run script there will be a syntax error as Python wont recognize this > 'black' string but then on another occasion the 'black' will run ok :(. > > I am sure my inquiries are quite vague but I am trying to piece together > some of his 'groans and grunts' :(. > > Any suggestions or other info you need from him? > It sounds like maybe you are using a "highlighting" text editor. That means the text editor adds color depending on the syntax of the colored text. For instance, if you have print "Game Over" in the editor, the word "print" might be blue because it is a python keyword and the "Game Over" might be orange because it is a string. It is also possible that the book is doing something similar and coloring the different words to show more information about their purpose or meaning. If you then run that program in the normal text terminal it would just print out in whatever color the terminal happens to be (in my case green text on a black background). If you want to make the text a particular color, you would need to tell python how to change the color, and that is going to take some more work. You may want to join the tutor mailing list which is set up specifically to help people who are brand new to python and/or programming. http://mail.python.org/mailman/listinfo/tutor From belred1 at yahoo.com Tue Jun 22 00:07:49 2004 From: belred1 at yahoo.com (Bryan) Date: Tue, 22 Jun 2004 04:07:49 GMT Subject: Cannot create a new file In-Reply-To: <40d79715$1_3@aeinews.> References: <40d77b19$1_3@aeinews.> <40d79715$1_3@aeinews.> Message-ID: <40D7B094.505@yahoo.com> > #identations are screwed up in thunderbird for those defs, lets hope it > wont appear online. i use thunderbird and i don't have indenting problems when posting python code to a newsgroup such as this one. when i post python code on a mailing list, it seems the format cannot be set to "text only". you have to change it to rich text. if i didn't just make a fool of myself :) the following indentation should look fine. def foo(): print 'this is indented 4 spaces' for y in range(10): print '''this is indented 8 spaces' bryan From eparker at freeshell.org Thu Jun 3 16:42:17 2004 From: eparker at freeshell.org (Eddie Parker) Date: Thu, 03 Jun 2004 20:42:17 GMT Subject: Problem with LargeFile support (Debian, Woody) Message-ID: Hello! Standard disclaimer here - I'm new, so I'm not sure if this is the wrong place to be posting, so please be kind if I am, and I'll kindly move my question elsewhere. :) Otherwise - thank you for your help! I'm trying to set up Zope, but everytime I do, I get a warning that largefile support isn't enabled. I hop into my ever friendly python interpreter, and run 'import test.test_largefile', and I get the following: >>> import test.test_largefile Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/test/test_largefile.py", line 47, in ? raise test_support.TestSkipped, \ test.test_support.TestSkipped: filesystem does not have largefile support Now, I'm not sure what I'm doing wrong? I'm running on Debian woody, and uname -a gives me the following information: Linux server 2.2.20-idepci #1 Sat Apr 20 12:45:19 EST 2002 i686 unknown And df -HT gives me the following: Filesystem Type Size Used Avail Use% Mounted on /dev/hda1 ext2 3.0G 470M 2.3G 17% / Does ext2 not have largefile support? I'm not familiar with the whole issue at hand, so any information you can give me would be great. :) Thanks! -e- From axel at axel.truedestiny.net Tue Jun 22 08:59:09 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Tue, 22 Jun 2004 12:59:09 GMT Subject: pysnmp/shell Message-ID: Hi All, Python is so great. I've been creating a small set of objects to get some stats from our adsl routers. So far it works great and fast. However, in the shell script I created over a year ago to gather stats I do: mib_lp=`$snmpwalk $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntIf Index 2>/dev/null | $grep " = $lan_iface" | $head -1 | $sed -E 's/^ip.ipAddrTabl e.ipAddrEntry.ipAdEntIfIndex.(.+) = .*/\1/g'` if [ "$mib_lp" != "" ]; then lan_ip=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntA ddr.$mib_lp 2>/dev/null | $sed -E 's/.+IpAddress: //g'` lan_netmask=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipA dEntNetMask.$mib_lp 2>/dev/null| $sed -E 's/.+IpAddress: //g'` else lan_ip="ERROR" lan_netmask="ERROR" fi To retrieve the lan settings for the router. I don't know the (lan)ip address of it but do know the interface number, that's why I check for that and then use a part of the mib to get to the netmask. This seems to be quite difficult with pysnmp (took me half an hour to write Router.SNMPQuery(self, noid) ;-)), so before I get started I wanted to ask if somebody might have better idea for this. Thanks! Kind regards, Axel Scheepers From alex-news-deleteme at comcast.net Tue Jun 29 13:55:00 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 29 Jun 2004 17:55:00 GMT Subject: embedded python? References: Message-ID: Thanks. Have you had good experiences with this distro? I also found this distro linked from riverbank's defunct distro. Do you know if this continuation of that distro, or an entirely new one? Alex "Christopher T King" wrote in message news:Pine.LNX.4.44.0406291228010.19979-100000 at ccc7.wpi.edu... > > 1) Are there any embedded Pythons out there? The nodes will likely be > > running some form of Linux, but I don't particularly feel like devoting > > resrouces to porting python. Any embedded Linuxes supporting Python? > > Thoughts in general? > > Python runs fine on ARM-based PDAs running Linux -- see > http://www.vanille.de/projects/python.spy for info and a surprising amount > of ARM binaries. Note that the packages are in ipkg (.ipk) format. These > are similar to Debian's .deb files, and you can get at the contents using > tar a couple of times. > From __peter__ at web.de Fri Jun 11 13:15:20 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 19:15:20 +0200 Subject: How to detect list versus string References: Message-ID: Jonathon McKitrick wrote: > > This sounds simpler that it is, hopefully ;-) > > I have a method that builds a dynamic combo box. Before I do that, I set > a class variable to the new list of items. > > def make_new_cat_box(self, cats): if isinstance(cats, basestring): cats = [cats] > self.cat_list = cats > > Sounds simple. But sometimes, my combo box will only have one choice > available. When I call this method with a list of one string, the string > is split up, and my combo box now has a separate item for each letter in > the > string. What I obviously want to do is detect when the object coming in > is > a list or a string. type() isn't as useful as I had hoped, and len() will >>> value = "123" >>> if type(value) == type(""): ... print "It's a string" ... It's a string >>> > give me the length of the string, so I cannot tell if it is a string or a > list of more that one item. > > There has to be a simple solution. I'd prefer isinstance() over type(cats) == type(""). If you are sure there won't be any unicode strings you can use isinstance(cats, str) instead of the basestring variant shown above. Peter From mark at prothon.org Wed Jun 16 03:04:22 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 16 Jun 2004 00:04:22 -0700 Subject: mutable default parameter problem [Prothon] References: <200406152201.20003.troy@gci.net> Message-ID: Mark Hahn wrote: > Fixing this will not break every use of > [] as a default formal param. Using [] in __init__ for example would > break nothing. Correction: Using [] as a default param is the same problem in __init__ as it is anywhere else. My brain went south for a moment. My point still stands though. There are many cases where a formal param can default to [] and can be evaluated early or late without breaking the code. My question asking for comments on code breakage also still stands. Does anyone have personal experience with usages of [] or {} as default params that would break with late evaluation? Is there any common idiom other than the non-recommended use of them as static vars that would break? From j_mckitrick at bigfoot.com Wed Jun 9 10:05:21 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 9 Jun 2004 07:05:21 -0700 Subject: Doc strings for a standalone app?? References: Message-ID: Calvin Spealman wrote in message news:... > j_mckitrick wrote: > > > Does it make sense to use doc strings rather than #-comments for a > > standalone Python app? If the classes aren't going to be re-used or > > imported, do they need them? > Sure. They are more clear as to the assignment of the comment to a > particular class or function or method, for one thing. It can help when > debugging and/or testing your modules, for another thing. And, you never > know that you'll always release as a standalone, as you might change your > mind or release some of your modules for third-party usage, for a third > thing. > -- How do they help during debugging/testing? From piet at cs.uu.nl Tue Jun 22 21:11:09 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 22 Jun 2004 21:11:09 -0400 Subject: Creating subclassess (newbie) References: <20040621153854.14f10a9f@debian> Message-ID: >>>>> Adam (A) wrote: A> I have tried to send this to the tutor mailing list, but it A> seems to be down at the moment. A> I have a subclass I want to create- my intuition told me A> that it would be done like this: A> class MainClass: A> class SubClass: A> code... A> subclassinstance = SubClass() A> mainclassinstance = MainClass() A> But it seems that this isn't going to work. I'm reading a A> couple of Python books, but they don't seem to cover this A> topic very well (I don't see any coding examples). I can't imagine that the Python books don't tell this. A> What is the best way of creating (coding) subclasses? A> Alternatively, is there any good documentation on the web A> for doing this? I guess every Python introduction tells you: class MainClass: .... class SubClass(MainClass): .... mainclassinstance = MainClass() subclassinstance = SubClass() -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From theller at python.net Thu Jun 17 11:58:46 2004 From: theller at python.net (Thomas Heller) Date: Thu, 17 Jun 2004 17:58:46 +0200 Subject: Need some help with Python/C api and threading References: Message-ID: >>>>>> "Steve" == Steve Menard writes: > > Steve> Here is my problem. I have this library thats hosts > Steve> another language within python, and allows that language to > Steve> call back INTO python. > > Steve> All is good as long as the other languages calls back on > Steve> the same thread. If the callback arrives on a different > Steve> thread, all hell break loose and the program dies horribly. > > Steve> looking at the C api documentation, I came upon the > Steve> following block of code : > > Steve> PyThreadState *tstate; PyObject *result; > > Steve> /* interp is your reference to an interpreter > Steve> object. */ tstate = PyThreadState_New(interp); > Steve> PyEval_AcquireThread(tstate); > > Steve> /* Perform Python actions here. */ result = > Steve> CallSomeFunction(); /* evaluate result */ > > Steve> /* Release the thread. No Python API allowed beyond > Steve> this point. */ PyEval_ReleaseThread(tstate); > > Steve> /* You can either delete the thread state, or save it > Steve> until you need it the next time. */ > Steve> PyThreadState_Delete(tstate); > > > Steve> Which would seem to be what I need. However, I have no idea > Steve> how to get at that interp pointer. I tried the following : > > Steve> PyInterpreterState* interp = > Steve> PyInterpreterState_New(); PyThreadState *tstate = > Steve> PyThreadState_New(interp); PyEval_AcquireThread(tstate); > > Steve> but then it crashes on the second line ... > > Steve> Anybody ever done this? As a side note, the hosted language > Steve> can start an arbitrary number of threads ... > > Steve> Steve If your library is a Python extension, you should get and save the PyInterpreterState in the initxxx() function, which initializes the extension. If using Python 2.3 you could (should?) probably use the PyGILState_Ensure() and PyGILState_Release() functions, which manage all this for you. See PEP311 http://www.python.org/peps/pep-0311.html. Maybe also it is needed to call PyEval_InitThreads() somewhere in the init function. Thomas From Ian.Sparks at etrials.com Tue Jun 22 16:20:14 2004 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 22 Jun 2004 16:20:14 -0400 Subject: Templating engine? Message-ID: <41A1CBC76FDECC42B67946519C6677A9C5A6DD@pippin.int.etrials.com> > Looks interesting, but the last update was over six months > ago. Any idea what might be going on with it? I think the authors and users feel its complete and stable. It's not broken so nobody is spending time fixing it. From dmq at gain.com Fri Jun 25 20:58:42 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 25 Jun 2004 17:58:42 -0700 Subject: Using metaclasses to play with decorators. References: <0vtjd0pakf9haehvhh753otgk48k36kre0@4ax.com> Message-ID: On Thu, 24 Jun 2004 08:57:49 -0400, "Colin J. Williams" wrote: >David MacQuigg wrote: >> The example above was to explain decorators, not justify them. If >> they were to be used *only* to clean up the current syntax for >> staticmethod, then I would say a better alternative would be to get >> rid of the need for a separate staticmethod form entirely. ( See the >> thread "Unification of Methods and Functions" for a thorough >> discussion of this topic.) >> >> Are decorators on functions necessary? I can't think of a simpler or >> more consistent way to handle all the variations proposed in PEP 318. >> >> Assuming that we *will* have a decorator syntax with many options, I >> think that making [staticmethod] one of those options is appropriate. >> I would still prefer a word more meaningful to new users, however. The >> rational I have heard for "staticmethod" is so contorted, it is not >> worth repeating. >> >> -- Dave >> >PEP 318 seems to focus on the "how" to implement decorators, rather than >the "why". Is there some accessible explanation of the purpose of them? The first few sections of the PEP are your best summary ( Abstract, Motivation, Background, Design Goals ). Other than that, I would search the discussion of this PEP in the python-dev mailing list. There are some specific links in the Background section of the PEP. -- Dave From j_mckitrick at bigfoot.com Wed Jun 2 18:49:30 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 2 Jun 2004 15:49:30 -0700 Subject: Why did no one invent Python before? Message-ID: Yes, it's a silly question, but given how far we have come, why is it that a natural looking, easy to read, incredibly powerful language has appeared only recently, from a tech standpoint? I can't *believe* how much more productive I am with the built in data types and powerful expressions Python offers. It made me want to quit my C++ job. Well, not quite. ;-) Seriously, why is a language like this only NOW appearing? And aside from the interpreter, because while it is nice, it's not the main forte' of the language, IMHO. jonathon From cookedm+news at physics.mcmaster.ca Fri Jun 11 12:02:08 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 11 Jun 2004 12:02:08 -0400 Subject: Passing file descriptors References: Message-ID: At some point, Josiah Carlson wrote: > I'm trying to write the equivalent of what the author calls "ringd" > described in the below article, and use it with python 2.3.x on linux > 2.4: > http://www.remote.org/jochen/work/pub/zero-downtime.pdf > > The script that I provide at the end of this post is a variation of > one posted in this thread: > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=7t5i40%241pn%241%40nyheter.chalmers.se&rnum=8 [...] > Certainly I need a two things: > 1. Unix domain socket, local socket (standard socket connected > locally), or pipe > 2. sendmsg/recvmsg, fcntl.ioctl, or equivalent file descriptor manipulation > > In the script listed at the end of this post, I use a file descriptor > pair returned by os.pipe(), which should be sufficient. I also use > fcntl.ioctl(). [...] > Does anyone have an idea of how to get it working on linux? I would > prefer to not have to break into C, if only because I don't want to > accidentally leak memory (once bitten, twice shy they say). Certainly > Pyrex and SWIG are options, but first I'd like to try a pure Python > version. Have a look at passfd.c in Neil Schemenauer's SCGI protocol implementation: http://www.mems-exchange.org/software/scgi/ It wraps sendmsg/recvmsg to send and receive file descriptors. It's a C module, but's it's very lightweight. I think it does what you want to do (the test_passfd.py is almost exactly like the script you posted; showing their common ancestors...) It's supposed to work under Linux, FreeBSD and Solaris. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From ramon.aragues at gmx.net Wed Jun 9 05:49:19 2004 From: ramon.aragues at gmx.net (ramon aragues) Date: Wed, 09 Jun 2004 11:49:19 +0200 Subject: fast list search? Message-ID: <40C6DD1F.7040008@gmx.net> Hi, I?ve got a list with more than 500,000 ints. Before inserting new ints, I have to check that it doesn?t exist already in the list. Currently, I am doing the standard: if new_int not in long_list: long_list.append(new_int) but it is extremely slow... is there a faster way of doing this in python? Thanks a lot, Ramon Aragues From karl at ulbrich.org Wed Jun 2 15:43:05 2004 From: karl at ulbrich.org (Karl Ulbrich) Date: Wed, 2 Jun 2004 15:43:05 -0400 Subject: Jython Forum In-Reply-To: References: <10bk67t3t6sqp4b@corp.supernews.com> Message-ID: <20040602194305.GD28258@exeter.org> The Jython mailing lists are a great source of information -- I'd suggest posting your questions there instead so they reach a broader audience. Subscribe to jython-announce and jython-users: http://sourceforge.net/mail/?group_id=12867 See also the Jython homepage: http://www.jython.org/ Karl Ike wrote on Sun, May 30, 2004 at 10:12:40PM +0000: > Its a great idea - badly needed too! > > "Maboroshi" wrote in message > news:10bk67t3t6sqp4b at corp.supernews.com... > > Just thought I would let everyone know of my Jython Forum I couldn't > really > > find one specific to Jython so I set this up > > > > if anyone wants to contribute anything visit http://www.pacificflame.com > > > > and if you think its a stupid idea let me know > > > > if you have any ideas for the forum please post to this message > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From dolzenko at rsu.ru Fri Jun 4 08:07:05 2004 From: dolzenko at rsu.ru (Eugeni Doljenko) Date: Fri, 4 Jun 2004 16:07:05 +0400 Subject: Legitimacy of deepcopy Message-ID: <033b01c44a2c$73d67ef0$b0fcd0c3@cooler> There is a list of custom objects. I want do duplicate this list to modify objects in new list and then compare old and new. I could do it with deepcopy class foo: def __init__(self, str): self.str = str old = [foo('str1'), foo('str2')] import copy new = copy.deepcopy(old) But I've found very few deepcopy uses in Python library and other programs, so I wonder it's possible to do it other, more elegant way. From llothar at web.de Thu Jun 3 16:22:17 2004 From: llothar at web.de (Lothar Scholz) Date: 3 Jun 2004 13:22:17 -0700 Subject: Why did no one invent Python before? References: Message-ID: <6ee58e07.0406031222.6fccaa49@posting.google.com> Grant Edwards wrote in message news:... > Smalltalk was an amazingly cool system, but I don't remember > any usable free Smalltalk systems until recently. I think I There were a few but they started at 10.000 USD - at a time where a full delphi was about 500 USD (the 1.0/2.0) versions. Interesting that the Smalltalk JIT compiler are still far far better then anything in the python/ruby/perl world. Maybe this has to do with the 10000 USD price :-) From tor.iver.wilhelmsen at broadpark.no Tue Jun 8 12:57:38 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 08 Jun 2004 18:57:38 +0200 Subject: if does not evaluate References: <2ids8kFmfpi0U1@uni-berlin.de> <2ik471Fntu3aU2@uni-berlin.de> Message-ID: Jim Newton writes: > this suggestion does not work because > expr2 evaluates even if expr1 is TRUE. Yes, someone pointed that out already :) - the solution was to use lambda expressions, which is reasonable. From jason at __no_spam__mobarak.name Sat Jun 26 19:38:34 2004 From: jason at __no_spam__mobarak.name (Jason Mobarak) Date: Sat, 26 Jun 2004 17:38:34 -0600 Subject: Case insensitive dictionary? In-Reply-To: <9418be08.0406261454.3c067507@posting.google.com> References: <9418be08.0406250921.71f4eba4@posting.google.com> <9418be08.0406261454.3c067507@posting.google.com> Message-ID: Elbert Lev wrote: > Thanks! > > In my case I know for sure, that keys are strings. So I fill the > dictionary with keys as they come to me from the source (preserve the > case). Once the dictionary is filled, it is a "READ ONLY" object. In > other words: there is no group operation writing it back to the source > and there is no reason to modify it. > > Is there something wrong with this code: > > class RegValuesDict(dict): > def __init__(self): > pass > def __getitem__(self, k): > try: > tmpk = k.strip().lower() > for key in self.keys(): > if key.strip().lower() == tmpk: > return dict.__getitem__(self, key) > except: > pass > return None > def has_key(self, k): > try: > tmpk = k.strip().lower() > for key in self.keys(): > if key.strip().lower() == tmpk: > return True > except: > pass > return False > ######## > > regdict = RegValuesDict() > regdict["keyname1"] = "value1" > regdict["keyname2"] = "value1" > > val1 = regdict["keyName1"] > if val1 == None: > print "Too bad" > > or > > if not regdict.has_key("keyName1"): > print "Too bad" > else: > val1 = regdict["keyName1"] > > or > > val1 = regdict.get("keyName1", "good value") > > Doing this in such a way, I remove the need for trapping exceptions in > every line of the client code. > > Again: is there something wrong with this approach? """ What's wrong with putting the keys in lowercase? The only thing I can see that's wrong is that your dictionary isn't really a dictionary anymore, in the sense that you don't have O(1) retreival of items -- I'm not sure if that's the case with python dictionaries -- but still... if you need to somehow get back the original value you could do something like... """ import UserDict class CaseInsentiveDictDeux (dict, UserDict.DictMixin): def __init__ (self, *args, **kw): self.orig = {} super (CaseInsentiveDictDeux, self).__init__(*args, **kw) def items (self): keys = dict.keys(self) values = dict.values(self) return [(self.orig[k],v) for k in keys for v in values] def __setitem__ (self, k, v): hash_val = hash(k.lower()) # Hash value of strings is normalized self.orig[hash_val] = k dict.__setitem__(self, hash_val, v) def __getitem__ (self, k): return dict.__getitem__(self, hash(k.lower())) def __contains__ (self, k): return dict.__contains__(self, hash(k.lower())) d = CaseInsentiveDictDeux() d['Foo'] = 'Bar' print d['foo'] print 'foO' in d print d.items() """Where you are trading time for space""" From daniel.dittmar at sap.com Thu Jun 17 06:08:13 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 17 Jun 2004 12:08:13 +0200 Subject: Chat server References: Message-ID: Miki Tebeka wrote: > I'm looking for a chat (IRC) server. > Nothing fancy. It has to be free, standalone and with logging. > Python based will be ideal. http://www.twistedmatrix.com/ seems to fit (except for the 'Nothing fancy'). Daniel From jdhunter at ace.bsd.uchicago.edu Wed Jun 9 12:40:07 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jun 2004 11:40:07 -0500 Subject: strange __del__ behavior In-Reply-To: (John Hunter's message of "Wed, 09 Jun 2004 11:14:54 -0500") References: Message-ID: >>>>> "John" == John Hunter writes: John> I have a class that uses some extension code I have written John> and I am trying to track down some memory leaks, which I John> presume to be in my extension code. The class is question John> is in a python module, not extension code. I notice some John> strange behavior; perhaps a guru can give me a pointer about John> what this may mean. John> If I define the __del__ method in the class C Doh! The class contained a circular reference, as in class A: pass class C: def __init__(self): self.a = A() self.c = self def __del__(self): print 'bye' c = C() I simplified my example a bit too much! For debugging purposes, I would like to know when C instances are being deleted; that's why I inserted the __del__ print method. Is there any way to get that info w/o defining __del__ and thereby screwing up python's garbage collection? JDH From phil at dspfactory.com Wed Jun 30 15:25:47 2004 From: phil at dspfactory.com (Philip Rittenhouse) Date: Wed, 30 Jun 2004 15:25:47 -0400 Subject: pywin32 custom i/f COM servers do not support variable or optional args Message-ID: I have discovered a couple of problems with the way the universal gateway code handles optional parameters and variable argument lists in COM servers. It appears to only be a problem when you use the custom interface. What I found was that variable argument lists are not detected at all. Instead they are just converted from SAFEARRAYs to a Python list. Similarly, omitted optional parameters (which are sent by COM as VARIANTs with value of DISP_E_PARAMNOTFOUND) are converted to Python integers with the integer value of DISP_E_PARAMNOTFOUND. I have made changes to univgw_dataconv.cpp to fix these problems but before I submit a patch, I'd like to make sure the changes make sense. To fix the optional argument problem, the code now checks VT_VARIANTS to see if they are VT_ERRORs with the value DISP_E_PARAMNOTFOUND. If they are, the argument is dropped, and presumably the Python method will have a suitable default to use in its place. The variable argument code was a little more tricky. I couldn't see any easy way to test if a method had the vararg property set, so I just assumed that any pointer to a SAFEARRAY of VARIANTS used as the last argument must represent a variable argument list. It then converts the array and expands the parameter tuple to fit the new arguments. Finally, I made a change to universal.py to handle the case where the variable argument list SAFEARRAY is declared [in, out] (as opposed to just [in]). This was required to support VB. In _GenerateOutArgTuple() I check if the method is a variable argument method and if so, I remove the variable arg parameter from the list of outputs. Thanks, Phil From shalabh at cafepy.com Wed Jun 9 23:36:42 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 09 Jun 2004 20:36:42 -0700 Subject: Constructor overloading In-Reply-To: <40C6D2F2.10508@comail.ru> References: <40C6D2F2.10508@comail.ru> Message-ID: <40C7D74A.7000701@cafepy.com> Sergey Krushinsky wrote: > Hello all, > > Is there a common way to emulate constructor overloading in Python class? > > For instanse, I have 3 classes: > 1/ Polar - to hold polar coordinates; > 2/ Cartesian - to hold cartesian coordinates; > 3/ Coordinates3D, which holds synchronized instances of the both in > __p__ and __c__ fields respectively. > > I want to design Coordinates3D so that when instantiated with Polar > argument, self.__p__=argument passed to constructor, and self.__c__ is > calculated. When argument is Cartesian, self.__c__=argument, and > self.__p__ is calculated. Runtime type checking works, but maybe there > is a better way? > > Thanks in advance, > Sergey My usual approach to such cases is using keyword arguments: #untested code class Coordinates3d: def __init__(self, polar_coords=None, cartesian_coords=None): if polar_coords: .... elif cartesian_coords: .... else: raise Exception, 'at least one required' Then it can be instantiated as Coordinates3d(polar_coords=polar) or Coordinates3d(cartesian_coords=cartes). You can also add a check if polar_coords and cartesian_coords then raise an exception 'only one should be specified'. Another option is to define two staticmethods on the class which can be used thus: a = Coordinates3d.from_polar(polar) b = Coordinates3d.from_cartes(cartes) Both options are explicit, which I think is a Good Thing. Depends on your taste. -- Shalabh From opengeometry at yahoo.ca Thu Jun 10 23:33:45 2004 From: opengeometry at yahoo.ca (William Park) Date: 11 Jun 2004 03:33:45 GMT Subject: [script] dis/assembling mbox email References: <2is2ebFr1sbvU1@uni-berlin.de> Message-ID: <2isngnFr378vU1@uni-berlin.de> In Skip Montanaro wrote: > > William> Time to time, I need to > William> - extract main header/body from a MIME email, > William> - parse and extract multipart segments, recursively, > William> - walk through the email tree, and edit/delete/add stuffs > William> - regenerate new MIME email. > William> Usage are > William> unmbox.sh dir < email > William> mbox.sh dir > email > You might be interested in the splitndirs.py script which is part of > the Spambayes distribution. There is no joindirs.py script, but it's > perhaps a five-line script using the mboxutils.getmbox function (also > part of Spambayes). I think splitndirs.py is Python's version of formail -s Of course, the inverse is simply to concatenate the files, and that would one-liner. :-) -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From __peter__ at web.de Wed Jun 30 06:01:12 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jun 2004 12:01:12 +0200 Subject: Improving logging, was Re: Optional use of logging library module References: <2e37dc1.0406290353.4826f3ad@posting.google.com> Message-ID: Vinay Sajip wrote: > I'm curious to know what people don't like about the logging module. I > haven't seen any posts on c.l.py complaining about it, can you point > me to some discussions? First of all: the logging package is *nice*, thank you for providing it. Here are two older threads that may give you an idea what difficulties people may encounter when learning to use it: http://groups.google.com/groups?selm=mailman.130.1067255458.702.python-list%40python.org http://groups.google.com/groups?selm=bp0vaq%247lc%241%40boulder.noaa.gov What I would like to see: - A one-stop function to get output to a file or stream. - A standard way to register custom handlers, something like registerHandlerClass(klass, name=None), name defaulting to klass.__name__. This would probably imply replacing eval() with a dictionary lookup. - I find the programmatic interface easier to learn than the config-file format. A utility function that writes the current configuration to a file might help here. - Let config-files and programmatic setup respect each other. - Allow for multiple root loggers. Logging can be used for totally unrelated tasks. I feel a little uneasy to have them all in the same hierarchy. (This one is thinking aloud, I'm not even sure if this cannot be done already with the Manager class) None of these are showstoppers, and judging from recent posts on python-dev you are already working on the first and most important issue. If you want to attract further suggestions on how to smoothen the logging experience, from people who are more familiar with the package than I am, it would probably be a good idea to open up a new thread. Peter From jacek.generowicz at cern.ch Wed Jun 9 03:13:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Jun 2004 09:13:43 +0200 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: Alexander Schmolck writes: > Not quite. In fact in the language that more or less started it all, > scheme, the standard iteration construct 'do' does indeed introduce > a *new binding* on each iteration. Yes, but this is a consequence of Scheme faking iteration with recursion. > Common Lisp OTOH doesn't -- like python: If you used recursion-based iteration constructs in either of these languages, the same would happen. Future Googlers please refer to: http://www.google.com/groups?as_umsgid=tyfsmgtbewl.fsf%40lxplus030.cern.ch From mchermside at ingdirect.com Thu Jun 24 15:37:52 2004 From: mchermside at ingdirect.com (Chermside, Michael) Date: Thu, 24 Jun 2004 15:37:52 -0400 Subject: a small-gui for python/win32 ? Message-ID: <0CFFADBB825C6249A26FDF11C1772AE1550AC9@ingdexj1.ingdirect.com> marco writes: > this week, i've seen a little GUI for python/win32 .. [...] > i've seen that in "daily python url" perhaps ??! > i cant find it again ;-( Perhaps it was PyGui (http://www.cosc.canterbury.ac.nz/~greg/python_gui/) which was featured recently on the daily python url. (Perhaps not since that's not win32 only.) -- Michael Chermside This email may contain confidential or privileged information. If you believe you have received the message in error, please notify the sender and delete the message without copying or disclosing it. From roysun_rohit at rediffmail.com Wed Jun 2 06:23:20 2004 From: roysun_rohit at rediffmail.com (Roysun_rohit) Date: Wed, 02 Jun 2004 06:23:20 -0400 Subject: Client side network programming Message-ID: <8e276248346669880d06a7c1574ceaa4@localhost.talkaboutprogramming.com> I am interested in making a search engine which takes web sites iteratively, and downloads the web page or has to perform some search across the web pages. I am unsucessful to do so. My machine works through a proxy server and the internet connection is through 24 hour lease line. when ever i try the code it gives : Traceback (innermost last): File "http-getfile-urllib2.py", line 19, in ? urllib.urlretrieve(remoteaddr, localname) File "/usr/lib/python1.5/urllib.py", line 66, in urlretrieve return _urlopener.retrieve(url, filename, reporthook) File "/usr/lib/python1.5/urllib.py", line 186, in retrieve fp = self.open(url) File "/usr/lib/python1.5/urllib.py", line 159, in open return getattr(self, name)(url) File "/usr/lib/python1.5/urllib.py", line 260, in open_http h = httplib.HTTP(host) File "/usr/lib/python1.5/httplib.py", line 53, in __init__ if host: self.connect(host, port) File "/usr/lib/python1.5/httplib.py", line 81, in connect self.sock.connect(host, port) IOError: [Errno socket error] (101, 'Network is unreachable') ============================================================ The code is like this:- #!/usr/bin/env python import os, sys, urllib, urlparse, socket showlines = 6 try: servername, filename = sys.argv[1:3] except: servername, filename = 'www.igib.res.in', '/sarsanalysis.html' remoteaddr = 'http://%s%s' % (servername, filename) if len(sys.argv) == 4: localname = sys.argv[3] else: (scheme, server, path, parms, query, frag) = urlparse.urlparse(remoteaddr) localname = os.path.split(path)[1] print remoteaddr, localname urllib.urlretrieve(remoteaddr, localname) remotedata = open(localname).readlines() for line in remotedata[:showlines]: print line, ============================================================ I am new to the internet programming as well as python. please guide me, how to solve this one. From kkto at csis.hku.hk Sat Jun 12 10:42:48 2004 From: kkto at csis.hku.hk (Isaac To) Date: Sat, 12 Jun 2004 22:42:48 +0800 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> Message-ID: <7iu0xgdehj.fsf@enark.csis.hku.hk> >>>>> "David" == David Bolen writes: David> I'm not sure if RAII is intended to also cover non-stack based David> objects, in terms handing ownership of the object reference David> equating transferring ownership of the resource. Certainly the David> classic example is the stack based approach. One can do it in C++ using auto_ptr. The basic use case looks like this: #include #include using namespace std; struct base_t { virtual ~base_t() { cout << "Destroying base_t" << endl; } // something complicated }; struct derived_t: public base_t { ~derived_t() { cout << "Destroying derived_t" << endl; } }; base_t *base_factory() { return new derived_t; } void f() { auto_ptr p(base_factory()); // heap allocated, function scoped } int main() { cout << "Call f" << endl; f(); cout << "Continue main" << endl; } Note that in f(), the memory returned by base_factory() is heap allocated, but function scoped. I.e., upon leaving function f(), either due to function return or exception being thrown, the memory is deallocated. This is usually used like above, to achieve polymorphism when otherwise one would want to use a function scoped object. There is a sense of ownership: when you do auto-pointer assignment, the original owner lose the ownership, and the corresponding auto-pointer immediately becomes a NULL pointer. So void f() { auto_ptr p(base_factory()); auto_ptr q = p; // p is now NULL auto-pointer } This makes auto-pointer somewhat difficult to use, and unsuitable for anything that try to do assignment (e.g., one is committing suicide if one creates a collection of auto-pointers). Next standard (C++0x) probably will introduce reference counted version, hopefully easier to use. Regards, Isaac. From NOmanlio_perilloSPAM at libero.it Fri Jun 4 05:11:45 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Fri, 04 Jun 2004 09:11:45 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> <87hdtzeanw.fsf@pobox.com> <87y8n9bej9.fsf@pobox.com> <2pfob0d54qrj0gmav4o1v6r2a215bahgvp@4ax.com> <87llj7dqnw.fsf@pobox.com> Message-ID: <4ve0c0dvdqjoqicodao9obnb1kkavk8rls@4ax.com> On 01 Jun 2004 20:28:03 +0100, jjl at pobox.com (John J. Lee) wrote: >Manlio Perillo writes: >> On 31 May 2004 01:56:10 +0100, jjl at pobox.com (John J. Lee) wrote: >[...] >> >> This is very simple to do with httplib and Cookie modules, so why to >> >> use more involved modules? >> > >> >No reason at all if you're happy with it, of course. That was what my >> >"Cool" was meant to communicate. >[...] >> Of course I agree with you for all other cases, but there exist >> programs that really needs only low level library. > >Was that not what I said? Sorry if I'm not making myself clear! > I'm sorry but I not a very expert in english language... > >(What follows is unrelated to your (quite unnecesary!) extended >defence of your use of Cookie in your script, but just by the way of >commentary on the points you make) > >> Actually, ad example, standard Cookie module is low level. > >Yes. The low-level stuff it does is not not always the right thing >for client-side code, though. > Why? > >> It only parses key=value pairs, and, more important, it is 'other >> library' neutral. >[...] > >Same goes for ClientCookie. The interface required of request and >response objects is defined in the docs. Ok, but I don't want to write additional code for implementing request and response interface... >For doing what ClientCookie >does (automatic cookie handling), I don't think it can get much >simpler. > Ok. But my program is already very simple using Cookie. Thanks and regards Manlio Perillo From 0gk500b4gd0888 at cougar.noc.ucla.edu Fri Jun 18 12:20:12 2004 From: 0gk500b4gd0888 at cougar.noc.ucla.edu (0gk500b4gd0888 at cougar.noc.ucla.edu) Date: Sat, 19 Jun 2004 01:20:12 +0900 Subject: Here Message-ID: Here is the file. -------------- next part -------------- A non-text attachment was scrubbed... Name: yours.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From elainejackson7355 at home.com Wed Jun 23 12:26:57 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Wed, 23 Jun 2004 16:26:57 GMT Subject: http knowledge sought References: <6r3Cc.861817$Ig.9977@pd7tw2no> Message-ID: "Graham Fawcett" wrote in message news:e9570f37.0406222237.39372ee0 at posting.google.com... | Please elaborate! OK. It would be nice to know a way in which somebody on another machine could access the pages your example serves. Not necessarily a cute or convenient way, but just a way. That would give me the foot-in-the-door feeling I'm looking for. | Google for "internet protocol tutorial" to learn more about IP | addresses. This worked well. Thanks From peter at engcorp.com Wed Jun 16 07:21:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 07:21:57 -0400 Subject: thread help In-Reply-To: References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Roger Binns wrote: > Peter Hansen wrote: > >>Sounds like you can't eat your cake and have it, too. If >>you _could_ interrupt threads**, wouldn't that mean "the worker >>threads just get abruptly stopped in the middle of what they >>were doing"? > > I meant in the same way that can in Java. In that case an > InterruptedException is thrown which the thread can catch > and do whatever it wants with. I didn't think things worked quite that way in Java. For example, I thought InterruptedException was seen by a thread only if it had actually been asleep at the time it was sent. I also didn't know it would actually terminate certain blocking calls, such as in socket stuff. Oh well, it's been a while... -Peter From fishboy at spamspamspam.com Sun Jun 6 00:31:16 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 04:31:16 GMT Subject: simple script to read and parse mailbox References: Message-ID: On Sat, 05 Jun 2004 15:27:36 +0100, chuck amadi wrote: >Hi , Im trying to parse a specific users mailbox (testwwws) and output >the body of the messages to a file ,that file will then be loaded into a >PostGresql DB at some point . > >I have read the email posts and been advised to use the email Module >and mailbox Module. > >The blurb from a memeber of this list . Im not at work at the moment So >I cant test this out , but if someone could take a look and check that >im on the write track as this Monday I need to show my Boss and get the >body data out of the user's mailbox. > >**Blurb form a member who's directed me** > >Thus started with the mailbox and email modules. Mailbox lets you iterate over a >mailbox yielding individual messages of type email. The e-mail object lets >you parse and operate on the message components. From there you should be >able to extract your data. > Hi again Chuck, I've been reading a few of your posts and I'm wondering. Are the emails that you're parsing have binary attachments, like pictures and stuff, or are you just trying to get the text of the body? Or is it a little of both? It looks like you're expecting emails with multiple binary attachments. Other than that it looks good. You can access the header fields directly, like: print msg['From'] Save you a little typing. ><{{{*> From fishboy at SPAMredSPAMpeanutSPAM.com Wed Jun 16 22:04:02 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Thu, 17 Jun 2004 02:04:02 GMT Subject: win32com and vb References: Message-ID: <84llin9bxd.fsf@redpeanut.com> allanc writes: > i have a python module that i've registered as a com server. i also > have a vbscript that i use to test the com server. i have a loop > that creates an instance of the com server on each iteration. but > each time it creates an object it returns the original (cached > object), with all the attribute values intact. > > how do i make the python module into a com server that generates a > unique object instance everytime i call > CreateObject("python.myPythonModule) in my vbscript? > > psuedocode below: > > vbscript: > > for i = 1 to len(array) > Set myform = CreateObject("python.Template") myform.id = > array(i) myform.addtext(lines(i)) > end > [...] This is really more a vbscript thing that a python thing. Try explictly deleting the com object in your vbscript. Set myform = Nothing "The Set statement assigns the object reference to a variable or property. The keyword Nothing is used to unassign the object reference from the variable or property. Good programming techniques require that you unassign all objects before you exit the program. " http://www.devguru.com/Technologies/vbscript/quickref/createobj.html ><{{{*> From fishboy at SPAMredSPAMpeanutSPAM.com Wed Jun 16 21:53:15 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Thu, 17 Jun 2004 01:53:15 GMT Subject: Regular expression, "except end of string", question. References: Message-ID: <84pt7z9cff.fsf@redpeanut.com> Peter Hansen writes: > David Eppstein wrote: > > > Do you really need regexps for this? > > > >>>>string = "WHITE/CLARET/PINK/XL" > >>>>'-'.join(string.split('/',2)) > > 'WHITE-CLARET-PINK/XL' > > Dang! I started with split('/', 2) but stared at the > result trying to figure out how the heck to join it > to get the right result and ended up punting. :-( > > -Peter $ python Python 2.3.4 (#1, Jun 13 2004, 11:21:03) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> string = "WHITE/CLARET/PINK/XL" >>> string.replace('/','-',2) 'WHITE-CLARET-PINK/XL' >>> ><{{{*> From MAIL-SA at gcc-sg.org Wed Jun 16 03:20:01 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Wed, 16 Jun 2004 10:20:01 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F65092550@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = Nicole.Vuillame at wanadoo.fr Recipient(s) = python-list at python.org; Subject = Don`t worry, be happy! Scanning Time = 06/16/2004 10:20:01 Engine/Pattern = 7.000-1004/905 Action on message: The attachment www.ecard.com.funny.picture.index.nude.php356.pif contained PE_ZAFI.B virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Jun 13 09:29:06 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Jun 2004 09:29:06 -0400 Subject: does python have useless destructors? References: <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: In article , David Turner wrote: > >Objects with a __del__ method shall be reference counted. When the >reference count reaches zero, the __del__ method shall be called, and >any subobjects that have a __del__ method shall also be unreferenced. > >The point at which the memory allocated to the object is freed is >largely irrelevant. The point is that there's a predictable time at >which __del__ is called. This is what enables the RAII idiom. > >Now, this could be tricky to implement because we are now separating >the concepts of "destruction" and "finalization". But it's certainly >not impossible, and it would add a powerful new concept to the >language. So I don't think the idea should be rejected out of hand. > >Is this clearer? Problem is, that's exactly the situation we currently have in CPython, so I don't see what the improvement is. Are you suggesting that Jython change its semantics? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From squirrel at WPI.EDU Mon Jun 28 20:22:48 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Mon, 28 Jun 2004 20:22:48 -0400 Subject: Speed of str(positive_integer).. In-Reply-To: References: Message-ID: On Mon, 28 Jun 2004, alejandro david weil wrote: > *The thrid test is using divmod() that i thought that would be > faster (i thought it could make only one division and get both > qoutient and remainder, without having to multiply..) but > was worse. > PS: I want a faster divmod! :-) I was going to say that divmod was slower because it performs float division instead of the integer division of // (which is true), but I'm guessing the slowdown comes from the extra dictionary lookup needed for divmod (unless this is somehow optimized away) instead. If that's indeed true, then it seems that divmod doesn't adequately perform its intended purpose, i.e. make use of the FPU's ability to divide and modulusify in one step to gain speed. From tcm-users-request at cs.utwente.nl Sun Jun 20 18:36:35 2004 From: tcm-users-request at cs.utwente.nl (tcm-users-request at cs.utwente.nl) Date: Mon, 21 Jun 2004 00:36:35 +0200 (MET DST) Subject: Your mail to tcm-users-request@listserv.cs.utwente.nl In-Reply-To: <200406202236.i5KMaHN19838@netlx014.civ.utwente.nl>, from python-list@python.org Message-ID: <200406202236.i5KMaZ1w015604@utrhcs.cs.utwente.nl> This pre-recorded message is being sent in response to your recent email to tcm-users-request at listserv.cs.utwente.nl. All routine administrative requests (including subscriptions and unsubscriptions) concerning this mailing list are handled by an automated server. Please read this message carefully to find the information relevant to you. SUBSCRIBING =========== To subscribe to tcm-users, send the following in the body (not the subject line) of an email message to "Majordomo at listserv.cs.utwente.nl": subscribe tcm-users This will subscribe the account from which you send the message to the tcm-users list. If you wish to subscribe another address instead (such as a local redistribution list), you can use a command of the form: subscribe tcm-users other-address at your_site.your_net UNSUBSCRIBING ============= To unsubscribe from tcm-users, send the following in the body (not the subject line) of an email message to "Majordomo at listserv.cs.utwente.nl": unsubscribe tcm-users This will unsubscribe the account from which you send the message. If you are subscribed with some other address, you'll have to send a command of the following form instead: unsubscribe tcm-users other-address at your_site.your_net If you don't know what address you are subscribed with, you can send the following command to see who else is on the list (assuming that information isn't designated "private" by the owner of the list): who tcm-users If you want to search non-private lists at this server, you can do that by sending a command like: which string This will return a list of all entries on all lists that contain "string". HELP ==== To find out more about the automated server and the commands it understands, send the following command to "Majordomo at listserv.cs.utwente.nl": help If you feel you need to reach a human, send email to: tcm-users-approval at listserv.cs.utwente.nl From peter at engcorp.com Fri Jun 18 21:33:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 21:33:18 -0400 Subject: [python] using try: finally: except In-Reply-To: References: <4koAc.40662$ih7.11793@fe2.columbus.rr.com> Message-ID: <9Y-dncAm9oR9Ck7d4p2dnA@powergate.ca> OKB (not okblacke) wrote: > Carl Banks wrote: > >>The right way is: >> >> try: >> try: >> x = 'hello' >> except: >> print "oops" >> finally: >> y = 'world' >> print x," ",y > > I seem to recall reading somewhere that this was a cop-out for some > implementation reason. Is there any word on when or if it's going to be > remedied? It seems unbearably ugly and unintuitive; one of the most > irritating Python warts. I recall differently. I recall reading several times that since it is completely ambiguous what the programmer meant if both are specified together, Guido deliberately kept them separate so that one had to be very explicit about whether the finally was inside or outside the except. The behaviour of the code is quite different depending on the order... -Peter From jimka at rdrop.com Mon Jun 7 16:28:56 2004 From: jimka at rdrop.com (Jim Newton) Date: Mon, 07 Jun 2004 22:28:56 +0200 Subject: if does not evaluate In-Reply-To: References: <2if8daFmdreiU1@uni-berlin.de> Message-ID: <2ik4nnFnt7i1U1@uni-berlin.de> for compressions are quite nice but you are still pretty limited about what you can put inside the for. you cannot put any code otherwise acceptable in the language. For example what if i need two, three or four statements inside the for? another question, is why are "if" compressions not supported? x = [ if some_function() else some_other_function() ] or better x = [ if cond1(): elsif cond2(): else: cond3() ] whouldn't that be inkeeping with the compression syntax? -jim Dan Bishop wrote: > Jim Newton wrote in message news:<2if8daFmdreiU1 at uni-berlin.de>... > >>how do you put an if or a for inside a lambda? > > > I'm not quite sure what you'd expect "for" to evaluate to, but you > might want to take a look at list comprehensions: > > [expr(var) for var in seq if cond(var)] > > For "if", you can write "(F, T)[bool(C)]" or "(C and [T] or [F])[0]". > The latter has the advantage of short-circuiting. From peter at engcorp.com Wed Jun 16 07:14:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jun 2004 07:14:00 -0400 Subject: how to become a really good Python programmer? In-Reply-To: References: Message-ID: Randall Smith wrote: > I've been programming in Python for about 2 years. I think it offers > the best combination of simplicity and power of any language I have > explored. As I write more and larger and complex programs, I need to > code better. By better I mean clearer, cleaner, more efficient and > maintainable. As the subject states, I want to become a really good > Python programmer. I think one of the best ways to do that (in addition to the excellent suggestions you've already received) might be to learn test-driven development (TDD). The things it will tell you about the clarity, cleanliness, efficiency, and maintainability of your own code will surprise you, and you'll likely improve rapidly in these areas as a result. Not to mention find yourself beginning to write code with fewer bugs! -Peter From youngdubliner at hotmail.com Tue Jun 15 19:34:49 2004 From: youngdubliner at hotmail.com (youngdubliner at hotmail.com) Date: 15 Jun 2004 16:34:49 -0700 Subject: import numarray problems Message-ID: <4039221c.0406151534.28bc96@posting.google.com> I'm having a problem ........ I've stripped all my code to help isolate the problem. Its seems to be with importing numarray when python is embedded in C. I have a simple C program it Opens Python imports a script and then Closes Python like so ....... int main(int argc,char *argv[]) { int count = 0; PyObject *pmod; while ( count < 10) { /* ** Initialize Python */ Py_Initialize(); printf("\nOpen Python ---- >"); pmod = PyImport_ImportModule("test"); Py_DECREF(pmod); /* ** Close Python */ Py_Finalize(); printf("\n<---- Closed Python"); /* ** Do this 10 times ! */ count++; } getchar(); return(0); } and thats it ! The script it calls is test.py its very simple , it imports numarray and then returns. like so ....... ----------------------- test.py ----------------------- #Imports from numarray import * def test_func(): return (99) ----------------------- end of file ----------------------- The first time it is called from my C code it all works fine ! ( but only the first time ! ) In the second iteration above test .c crashes It has something to do with importing numarray. Beacase if you comment out the import line i.e ----------------------- test.py ----------------------- #Imports # Commented out ! #from numarray import * def test_func(): return (99) ----------------------- end of file ----------------------- its scrolls through the while loop and works fine. Its all very odd . any ideas ? I'm using Python 2.3.3 and Python 2.3 numarray - 0.8 Thanks in advance From pinard at iro.umontreal.ca Mon Jun 28 19:14:29 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 28 Jun 2004 19:14:29 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: <40E07441.8030805@rogers.com> References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> <40E07441.8030805@rogers.com> Message-ID: <20040628231429.GA9049@titan.progiciels-bpi.ca> [Mike C. Fletcher] > And developers; stop GPLing libraries which are essentially > commodities. The GPL is effective when you are dealing with code > which is so compelling and unique that it is easier to buy into > the FSF's manifesto than to switch or write a substitute. [...] > GPL is a PITA when working on commercial products and often forces > reimplementation... when it's commodity code that's just entirely > wasted effort. GPL is a likely PITA for whoever does not like it. If one doesn't like the GPL, then one should be congruent enough to merely not use GPL'ed code, instead of spending sweat and blood, trying to bend it. The original plan of the GPL is to have so much good and attractive code flying around, which is GPL'ed, than people will give in free software instead of doing it all over again. That plan went pretty well so far. Libraries are commodities, but so is a lot of non-library software. Developers who consider that the GPL brought good software to them, may well choose to produce some GPL code in return, in so contributing to the critical mass. You invite people to stop GPLing libraries because it annoys those who do not like the GPL. I would rather read this as a practical proof that the GPL serves its purpose: if people against the GPL were not a bit bitten by it, the GPL would be useless. Sometimes, people want the butter and the money of the butter (from a French idiom: "Le beurre et l'argent du beurre"). They want everything without giving anything back. The GPL is there to remind people that the overall game is a give-and-take. It is something useful. P.S. - Please do not read me as saying that the GPL is the only path to free software, there are other good free software licenses too. But the GPL is not "wrong", and developers are not "bad" because they choose it. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From winexpert at hotmail.com Mon Jun 7 08:06:28 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 07 Jun 2004 12:06:28 +0000 Subject: python -- question with list.pop(0) Message-ID: Hi, I'm getting an error 'oops an error pop from an empty list' However I am printing the contents of the list right before i am attempting the pop and there are items in the list. The weird thing is the list looks different than i expect it to be. code snippet: --- begin snippet -- ourFile = open(fileNamesList[0],'r') strData = ourFile.read() ourFile.close() records = [] # # do we need to use \r\n???? # print "split 0.5" records.append(strData.split("\n")) print "records '%s'" % records === end snippet ==== at this point the output looks like this '[['this is line 1', 'this is line 2', 'this is line 3', '' ]]' I don't understand why two [[ list symbols are showing up, its like its a list of lists? Then when I attempt to pop the first element I get the error. Probably the problem is somehow related to having [ [ ?? What am I doing wrong? Thanks David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Watch the online reality show Mixed Messages with a friend and enter to win a trip to NY http://www.msnmessenger-download.click-url.com/go/onm00200497ave/direct/01/ From __peter__ at web.de Mon Jun 28 02:43:17 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jun 2004 08:43:17 +0200 Subject: string concatenation References: Message-ID: selwyn wrote: > you can += strings, but you need to create the variable first: > > i.e. > for name in contextForm.keys(): > context = '' > context += "Input: " + name + " value: " + contextForm[name].value > + "
    " I guess the OP wants to collect data over the loop, i. e context = "" for name in contextForm.keys(): context += "Input: " + name + " value: " + contextForm[name].value > concatenating a string like this is supposed to be substantially slower > than using ''.join(sequence), where you can replace the blank string > with the separator of your choice. > > using your example: > > for name in contextForm.keys(): > sequence = ["Input: ",name, " value: ", contextForm[name].value, > "
    "] > context = ' '.join(sequence) The faster idiom will then become sequence = [] for name in contextForm.keys(): sequence += ["Input: ", name, " value: ", contextForm[name].value, "
    "] context = "".join(sequence) Peter From http Wed Jun 2 21:13:10 2004 From: http (Paul Rubin) Date: 02 Jun 2004 18:13:10 -0700 Subject: crypt and decrypt IP address for a php project References: Message-ID: <7xr7sxl9zt.fsf@ruckus.brouhaha.com> danielle d'avout writes: > Is it possible, difficult? How can spywareinfo.org decrypts the IP if Python > and Php have not their corresponding base64_encode related? It's easy, and the base64 routines should be compatible (that's why base64 is a standard). However, if you're having trouble with this, it may be easier for you to just stay with the php version. From nbrewer at visi.com Sat Jun 26 12:28:22 2004 From: nbrewer at visi.com (Chris Farley) Date: 26 Jun 2004 16:28:22 GMT Subject: Timeout on file write? Message-ID: <40dda426$0$32608$a1866201@newsreader.visi.com> I'm working on a cross-platform Python program that prints to a receipt printer. The code is simple, I just do something like this: printer = file('/dev/lp0','w') # on Win32, change to 'lpt1' p.write("whatever") p.close() I would like to gracefully handle situations such as when the paper is out or the printer is powered off. Right now the program just hangs. Suggestions? Thanks... From Vincent.Raaijmakers at ge.com Tue Jun 1 09:27:41 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Tue, 1 Jun 2004 08:27:41 -0500 Subject: Python with TestDirector Message-ID: <971323274247EB44B9A01D0A3B424C85098D1585@FTWMLVEM02.e2k.ad.ge.com> For a couple of weeks, we are using with success Python with TestDirector. TestDirector 7.6, Python 2.2 and Mark Hammond's windows extensions. Please let me know if there are any questions. Vincent -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of Chuck Sent: Saturday, May 29, 2004 8:52 AM To: python-list at python.org Subject: Re: Python with TestDirector Hi, I'm not using Python with TestDirector but I know that our QA group uses it. I'm a software architect and I am very interested in increasing the use of automated testing within my company. We are primarily a Java shop but I write a bit of Python for this and that especially testing. I've used PyUnit, JUnit, NUnit etc. and am trying to get others to use these tools. I'd be interested in learning about how Python can be used in conjunction with TestDirector. What's the relationship - Is TestDirector written in Python? "Taylor, Martin" < cmtaylor at ti.com> wrote in message news:mailman.375.1085682168.6949.python-list at python.org... Limor Hevroni asked on Mon Apr 19 06:49:06 EDT 2004 if anyone was using Python for testing with TestDirector. I am doing this extensively and would welcome discussions with other people who are either doing it or are interested in doing it. Regards, C. Martin Taylor Sr. Test Automation Specialist Texas Instruments, Inc. Educational and Productivity Solutions 7800 Banner Dr. MS 3946 Dallas, TX 75251 -------------- next part -------------- An HTML attachment was scrubbed... URL: From athyb at hotmail.com Fri Jun 4 07:12:23 2004 From: athyb at hotmail.com (Albert) Date: 4 Jun 2004 04:12:23 -0700 Subject: Need parser for C-like grammar Message-ID: Hi group I need to develop a parser for a descriptor file which uses a c-like syntax. Is there any package available (preferably with examples of such c-like grammar) that allows me to define the grammar in an easy way and use this to parse the file into a tree of python objects? Thanks Albert From __peter__ at web.de Thu Jun 10 03:40:07 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jun 2004 09:40:07 +0200 Subject: My simple script parse output screen and to a new file! References: Message-ID: Chuck, if you want to take full advantage of Python's superior readability, reduce the number of comments. Instead of commenting out code, remove it and keep a copy of the old version around. You can write general notes about file modes or file() vs. open() on a post-it and stick it on your screen until you've memorized them. The really important on-topic stuff is best moved into doc-strings. You'll see your script magically shrink and both we and you will better understand what it does - trust me :-) Peter From __peter__ at web.de Fri Jun 11 11:19:56 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 17:19:56 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> <2ituufFrgqhaU1@uni-berlin.de> Message-ID: Jim Newton wrote: > sorry, i do not understand. The python syntax is a bit > difficult for me. Maybe I obscured the issue by comparing name attributes to a string instead of using a predicate() function. > if i have a list x and a function f how do i know if > there is an element of x on which f returns something > other than False? Using the above identifiers, let's assume we are looking for a name starting with "M": >>> x = ["Peter", "Paul", "Mary", "Jane"] >>> def f(o): ... print "checking", o ... return o.startswith("M") ... If we call >>> map(f, x) checking Peter checking Paul checking Mary checking Jane [False, False, True, False] it invokes f() for every item in x and returns the above list of booleans. The equivalent list comprehension would be [f(i) for i in x]. Now >>> True in map(f, x) checking Peter checking Paul checking Mary checking Jane True gives the correct result but unfortunately does too much work as we don't need to calculate f("Jane") when we already know the outcome. Enter generator >>> def lazymap(predicate, seq): ... for item in seq: ... yield predicate(item) ... which calulates f(item) as needed. Proof: >>> True in lazymap(f, x) checking Peter checking Paul checking Mary True >>> itertools.imap() is just the fast C implementation of lazymap(). The equivalent generator expression (new in Python 2.4) will be (f(i) for i in x). Peter From peter at engcorp.com Tue Jun 29 00:26:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 00:26:01 -0400 Subject: How important is Python 1.5 compatibility? In-Reply-To: <40E092A9.43C2CDDF@alcyone.com> References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: <8MKdnZ2sOvvEcn3dRVn-hQ@powergate.ca> Erik Max Francis wrote: > How important do people think Python 1.5 compatibility is? IMO, absolutely unimportant. I'd ignore it completely. I keep 2.2 compatibility in mind at this point, but nothing earlier. -Peter From jbperez808 at yahoo.com Wed Jun 9 03:04:19 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 09 Jun 2004 15:04:19 +0800 Subject: dropping into the debugger on an exception Message-ID: <2inqlrFp53m5U1@uni-berlin.de> (sorry for the duplicate post, just wanted to make the subject line clearer) How do you set up pdb such that you will automatically get dropped into its prompt if an unanticipated exception occurs in a script you are using? ASPN Python cookbook gives you the following method which you can add to your script and hook into sys.excepthook. But is there a way to do it without adding stuff to your script? (It's okay if this means having to invoke the script from within pdb, but #1, I don't know how to get it stay inside pdb in the case of an /unanticipated/ exception. And #2, I don't know how to pass [the equivalent of] command-line arguments to a script invoked from within pdb.) def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Jun 11 17:21:57 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 11 Jun 2004 23:21:57 +0200 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfiaFphmh5U1@uni-berlin.de> <2iui4mFr1nafU2@uni-berlin.de> Message-ID: Bonsoir ! Lorsque j'ai besoin d'appeler un script Python, depuis une page HTML, en local, je passe par COM. J'ai fait un serveur COM, en Python avec win32all. En HTML j'ai quelque chose du genre : (Pyt.Com est le nom du serveur COM Python). @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B From mva at sysfault.org Fri Jun 11 10:29:31 2004 From: mva at sysfault.org (Marcus von Appen) Date: Fri, 11 Jun 2004 16:29:31 +0200 Subject: How do you write test suites for GUI components? References: Message-ID: <86isdynp6c.fsf@sysfault.org> j_mckitrick at bigfoot.com (j_mckitrick) writes: > What exactly do you test for? What GUI is exactly discussed here? A specific toolkit? Writing an own GUI render engine and components? I am currently writing an own GUI toolkit based on pygame (located at http://ocemp.sf.net) and my major approach for testing the components will be the following: * Testing object instantiation and addition to the render engine * Testing all public and private methods using various parameters * Testing the behaviour of the object after modifying (public) attributes * Testing the event management of the object * Testing the container behaviour (packed widgets in tables, Frames, etc.) * Testing collision detection of objects (if wanted) * Testing the removal of the widget (correct unregistering any events, deletion of all references, etc.) * Testing exception handling, if any * Testing threading behaviour, if any * Testing the object behaviour, when the renderer attributes (, etc.) change Though I did not implement any test stuff for my current engine and componenets I would (and will) always go that way. I also would place the test framework either in the corresponding module or into an own module (dependant on the implementation of the toolkit). Regards Marcus -- We don't understand the software, and sometimes we don't understand the hardware, but we can *see* the blinking lights! From a.schmolck at gmx.net Sat Jun 12 17:50:35 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Sat, 12 Jun 2004 22:50:35 +0100 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: Jacek Generowicz writes: > Alexander Schmolck writes: > >> Not quite. In fact in the language that more or less started it all, >> scheme, the standard iteration construct 'do' does indeed introduce >> a *new binding* on each iteration. > > Yes, but this is a consequence of Scheme faking iteration with > recursion. Why "faking"? How is this CL-style do below inferior to the real thing (apart from the fact that it's possibly inelgant or broken because it's quickly hacked together by someone of limited competence as a scheme programmer:)? ;; cl-style do (with mandatory step clause, to make the code a bit more ;; compact) (define-syntax cl-style-do (syntax-rules () ;; this... [(cl-style-do ((var init step) ...) (end-test result ...) body ...) ;; ... gets rewritten as (let ((var init) ...) ; normal let; similar to var = init; ... (let loop () ; named let: like def loop(): ...; loop() (if end-test (begin (if #f #f) ; trick to get void return value if no result form result ...) ; is given (begin body ... (set! var step) ... (loop)))))] )) ;; for comparison, this is a (again slightly simplified) scheme style do (define-syntax scheme-style-do (syntax-rules () ;; this... [(scheme-style-do ((var init step) ...) (end-test result ...) body ...) ;; ... gets rewritten as (let loop ((var init) ...) ; like def loop(var...): ...; loop(init...) (if end-test (begin (if #f #f) result ...) (begin body ... (loop step ...))))] )) Recycling the contorted pythonesque scheme example I posted earlier: (define l '()) ; an empty list (cl-style-do ((x 0 (+ 1 x))) ; start x with 0, then add 1 at each step ((= x 10)) ; stop when x is 10 (set! l (cons (lambda () x) l))) ; add a new function closing over x to ; the *front* of l (set! l (reverse l)) ; since we added to the front we ; have to reverse l ((list-ref l 3)) ; get list element 3 and execute it => 10 (same as in CL; not 3 as with standard do) >> Common Lisp OTOH doesn't -- like python: > > If you used recursion-based iteration constructs in either of these > languages, the same would happen. > > Future Googlers please refer to: > > http://www.google.com/groups?as_umsgid=tyfsmgtbewl.fsf%40lxplus030.cern.ch Again you seem to imply that somehow scheme does something inappropriate and/or is somehow limiting compared to CL/python style iteration -- whereas AFAICT the exact opposite applies. I can't see how the new bindings that scheme's do introduces on each iteration step matter unless you create a closure in the body of the do loop and in that case chances are scheme's behavior is *precisely* what you want. And if, for some (obscure ?) reason, CL style do is what you need then I think you can trivially implement it as above. OTOH, if you want scheme style tail recursion (which makes it feasible to express some problems significantly simpler and quite a few more lucidly than if you had to use plain iteration) in (standard) CL or python you're pretty screwed -- you can to some extent fake it in CL, but even that requires a lot of work. For python you'd have to write a compiler to standard python (or bytecode). 'as From dcsmpayne at bigpond.com Mon Jun 14 06:31:50 2004 From: dcsmpayne at bigpond.com (news) Date: Mon, 14 Jun 2004 10:31:50 GMT Subject: kid wants to know more about color on the screen References: Message-ID: Hi Doug, I am also using this text. On the whole I find it very very good. I am looking at the pages you mention and it looks like you have not added the rest of the code after the print \ statement ... there is a whole bunch of code in triple quotes that follows, when this is included you should get the correct syntax highlighting. Actually I did this exercise only last week with 2 year 7 classes. Your problems are common and you will soon get over them, wait till page 22 when you see escape sequences! .. realise all these things become old hat very quickly. regards Darren Payne "Doug Mitchell" wrote in message news:FMCyc.61975$8k4.1338501 at news20.bellglobal.com... > Dear Group, > > My son who is in grade 7 has *just* started going through the book "Python > for the Absolute Beginner" by Michael Dawson. He and I have no programming > experience. He is beginning this on an old win 95 computer with Python 2.2 I > think. > > He is getting a bit frustrated with color coding. > For example in Chapter 2 page 18 and 19 Mr. Dawson describes a more fancy > way of printing "Game Over" on the screen. According to *him*... > > When I type the command: print "Program 'Game Over' 2.0" > print \ > > Instead of getting the second "print" to turn orange, like it's supposed to > when you type in a command, it just stays black. And when its time to > actually run the program, Python just prints out Program Game Over 2.0 > instead of the fancy large text like that is shown in the book. > > Later on he says that strings within quotes will be green as expected and > then all of a sudden on the next line it will stay black :(. And when he > does a run script there will be a syntax error as Python wont recognize this > 'black' string but then on another occasion the 'black' will run ok :(. > > I am sure my inquiries are quite vague but I am trying to piece together > some of his 'groans and grunts' :(. > > Any suggestions or other info you need from him? > > Thanks for your advice. > > Jack > > From tim.golden at tesco.net Thu Jun 24 15:55:54 2004 From: tim.golden at tesco.net (Tim Golden) Date: Thu, 24 Jun 2004 19:55:54 +0000 (UTC) Subject: Using Python with SyBase In-Reply-To: References: Message-ID: Widom wrote: > Does anybody expirience Python for writing user front-end screens for > SyBase-Anyware databse ? > Where can I found more information how handle SyBase SQL-Anyware from Python > ? > Meybe it sounds strange but I am looking for languguage I can write TEXT > mode front-end software (in IBM old style) for diferent platforms (Windows, > Linux, Palm OS etc). > Tomasz Don't know if this helps, but Object Craft have a module to interface to Sybase ASE from Python at http://www.object-craft.com.au/projects/sybase/ Might be worth a look. TJG From mwh at python.net Wed Jun 2 05:42:34 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 2 Jun 2004 09:42:34 GMT Subject: extension modules in C for python, check for korrekt Object References: Message-ID: Torsten Mohr writes: > Hi, > > i write a set of extension modules for python in C. > I also use some new types that i defined there. > > At the moment i write some methods that expect some > of these types as parameters. I now want to check > that the right types were given as parameters. > > How can i do that? > > PyArg_ParseTuple only checks that an object was > given as parameter, but not its type. It can check type, using the "O!" incantation. If you're asking "how do I get hold of the type object I defined in some other extension module?", then that's a good question. One approach is to use "CObjects": http://docs.python.org/ext/using-cobjects.html > Do i need to check tp_name in the objects type? This sounds fragile :-) Cheers, mwh -- Of the four project development variables - scope, cost, time and quality - quality isn't really a free variable. The only possible values are "excellent" and "insanely excellent", depending on whether lives are at stake. -- Kent Beck, XP Explained From brian at sweetapp.com Fri Jun 4 14:37:06 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 04 Jun 2004 20:37:06 +0200 Subject: ANN: Vancouver Python Workshop - Registration open! In-Reply-To: <40AD0CD4.1090804@sweetapp.com> References: <40AD0CD4.1090804@sweetapp.com> Message-ID: <40C0C152.2060603@sweetapp.com> What's new? =========== Vancouver Python Workshop registration is now open. Thanks to the generosity of our hosts and sponsors, the first fifteen people to register will receive a free copy of either: 1. Andy McKay's "The Definitive Guide to Plone" 2. Charles F. Goldfarb and Paul Prescod's the "XML Handbook, Fifth Edition" 3. Mark Lutz and David Ascher's "Programming Python, 2nd Edition" The first to register will get the first choice of books so sign-up soon! To register, see: http://www.vanpyz.org/conference/registration For general conference information, see: http://www.vanpyz.org/conference The deadline for early bird registration fee is June 30th. About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Talk submissions: until June 15th Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From hungjunglu at yahoo.com Fri Jun 4 02:47:13 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 Jun 2004 23:47:13 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> Message-ID: <8ef9bea6.0406032247.73a2660a@posting.google.com> Alexander Schmolck wrote: > How do younger languages like IO make this point more forcefully than lisp, > smalltalk etc -- languages which have been around for decades? Sorry, the last time I used Lisp was more than 20 years ago. I might have to look it up again. I tend to rely on people that have more experience. Io was based on experience from lots of other languages. > with some limited subset of errors raised in *my* code -- I want to be able to > deal with *all* errors in an interactive session, no matter where they were > raised and I don't want to have to rewrite (or slow down) *any* code in order > to do so. One typical example mentioned in AOP is precisely exception handling. If you look at Python's internal way of handling exception (read the manual part on extending and embedding,) errors are typically indicated by returning a NULL value. And there are a few functions to call to set exceptions. That is, internally, Python exceptions are implemented going through function mechanisms, any how. Now, if these functions could be interceptible a la AOP, there you go with "catching *all* errors." Sure, I understand you don't want to write any code. You just want to be the end user and enjoy the free ride. But someone has to write it, at some level. What you are saying is that you don't want to be this someone. All the nice interactive, edit-and-continue features in the various languages are not born out of magic, they were written by someone, right? :) > It would allow some interception, but I don't think enough for my heart's > content because exceptions are completely different beasts from functions, > certainly in python (dynamically scoped ones, for starters). Exceptions in Python are implemented as (a) returning typically a NULL value in Python functions at the C level, (b) setting exception informations in global static variables, often via usage of some functions like PyErr_SetString(). And in this regard, conceptually is not different from AOP way of exception handling. And in this regard, perfectly interceptible via function overrides, if it were not C but some other language a la Io. What I am saying is, it is totally possible to design a language where exceptions are implemented using AOP approach, where each function could return an additional implicit value (or a NULL value as in the case of Python.) Now, the function (or "metafunction") in your AOP code that handles the exception raising or catching can be overridden, if you are using something like Io where all functions can be overriden. That is, exception handling conceptually can be done via functions. And in Microsoft C++, this is in fact the way how exceptions are implemented: by including an extra return value. It's just too bad that the end user cannot override internal C/assembler functions. (There are products to do this type of overriding. Profilers, memory leak detectors, debuggers, etc. are good examples... in their "instrumentation" phase, they do AOP-ish insertion of additional code and override the normal behavior.) In short, for many language implementations, exceptions ultimately are based on function features. They are not "completely different beasts". Mostly everything ultimately comes down to plain-vanilla function calls. > > It does not mean all hope is lost in Python. But it does mean that > > instead of using the raise... statement in Python, you need to call a > > function/method instead. > > Such an approach doesn't really help much -- not only because I obviously > can't (and don't want to) rewrite all the code that might raise an exception > (which often isn't even python). I know, that's why I said "it does not mean all hope is lost". It doesn't help much, but it helps a little. > Yes, but this is clearly insufficient. Do you have any better idea? Short of stopping whining and starting to re-write the Python interpreter yourself? I am sure you are totally welcome to do so. :) > > Interactive programming with features like edit-and-continue still has > > room to grow (most edit-and-continue features are not transactional, > > that is, you cannot revert changes easily.) But in my opinion that's > > an arena for prototype-based languages, > > I don't see how prototype-based languages have a particular edge here -- It does. You just don't see it. Most people can't see it. And I am not telling the details. :) Smart people know what I am talking about. And I'll just leave it at that. Sorry, can't say anymore. :) > I know -- I currently don't depend on weakref, Weakref is the key, at least that was my experience. I urge you to think again on why weakrefs are necessary. Whether to use metaclass, AOP-ish approach, or brute force class changes, it's all just icing on the cake. Weakref was the key, in my experience. > This is one of the sticky points -- it requires some work and expertise (and > even then you are a long way off from e.g. smalltalk) and this in turn is > likely to mean that most python users won't get to experience the benefits of > interactive development (which in turn presumably means that libraries and > utilities often don't cater well for interactive use). I know. Python has been criticized from many directions. But you either live with the workarounds, or stop whining and do the work inside the interpreter so others can enjoy your work. :) In my personal case, I choose the first alternative. The advantage is that I can keep whining. I am almost sure that this would also be your choice. :) regards, Hung Jung From bug-gnu-gettext at gnu.org Sat Jun 12 19:45:57 2004 From: bug-gnu-gettext at gnu.org (bug-gnu-gettext at gnu.org) Date: Sat, 12 Jun 2004 19:45:57 -0400 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: good work! -------------- next part -------------- A non-text attachment was scrubbed... Name: friend.zip Type: application/x-zip-compressed Size: 25479 bytes Desc: not available URL: From fumanchu at amor.org Sun Jun 6 00:49:34 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 5 Jun 2004 21:49:34 -0700 Subject: if does not evaluate Message-ID: Jim Newton wrote: > how do you put an if or a for inside a lambda? Example? The answer to that (using current syntax) depends upon the use-case. Short answer: don't use lambdas for that; use a full function. > The expression i'm suggesting as evaluatable > could be passable to a function call as well, > as being mappable, or usable inside a lambda. > It seems better to me in that it stops being > a special case. > > E.g., > > myfun( ( if cond1 expr1: else expr2 ), > ( if cond2 expr3: else expr4 )) I'm not sure what "it" is that is a "special case". The lambda? Have you read PEP 308, by the way? http://www.python.org/peps/pep-0308.html You'll notice that the community doesn't lack for syntax proposals to implement ternary operations. Indeed, there are perhaps too many. ;) Many of those have patches ready to go. The sticking point is currently more social than technical. Robert Brewer MIS Amor Ministries fumanchu at amor.org From jacek.generowicz at cern.ch Thu Jun 3 10:58:48 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 03 Jun 2004 16:58:48 +0200 Subject: speed problems References: Message-ID: "^" writes: > could you please [...] tell me where I should look for > optimizations? import profile help(profile) import hotshot help(hotshot) (Teach a man to fish ... and all that :-) From fredrik at pythonware.com Fri Jun 18 13:05:39 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Jun 2004 19:05:39 +0200 Subject: regexp substitution - a lot of work! References: Message-ID: Lukas Holcik quoted someone writing: > > I don't understand your point. The Python equivalent is: > > > > re.sub('(..)', r'x\1x', s) > > > > or using a precompiled pattern: > > > > pat.sub(r'x\1x', s) footnote: you can use a callback instead of the replacement pattern. callbacks are often faster, and can lead more readable code: http://effbot.org/zone/re-sub.htm#callbacks (as the other examples on that page show, you can do a lot of weird stuff with re.sub callbacks...) From bkc at Murkworks.com Tue Jun 29 14:33:48 2004 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 29 Jun 2004 14:33:48 -0400 Subject: embedded python? References: <55iEc.112810$2i5.78663@attbi_s52> Message-ID: "Alexander May" wrote in message news:55iEc.112810$2i5.78663 at attbi_s52... > PS: > > > I doubt you'll need to do much "porting". Unless the Linices you > > are considering are quite unusual, they ought to look a lot like any > > other Linux, and Python may well work largely unchanged. > > from http://www.vanille.de/projects/python.spy (from Christopher T King's > post) > > "You won't find many Python distributions for arm-linux, because Python is > pretty finnicky when it comes to cross-compiling. The build process of > Python compiles a core part of it (the parser generator pgen) and tries to > execute that later in the build process. This - of course - doesn't work for > cross compiling. My patches to the Python build scripts are available @ > sourceforge and are likely to be included into the main Python tree." Don't worry about this. I've ported Python to a 68K board (8 meg ram, 4 meg flash) running uClinux. That was a squeeze, due to uClinux limitations I had to statically link in libxml2, libxslt and other goodies I needed. It worked, and the build process was easy to tidy up (once you know how it works). I cross compiled from RH9 (386) using gcc tools. Put the binaries on NFS and tested from the 68K box. Later, burned a flash rom image with the binaries. From dooms at info.LESS.ucl.SPAM.ac.be Tue Jun 15 11:51:01 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Tue, 15 Jun 2004 17:51:01 +0200 Subject: FW: Good IDE for Python In-Reply-To: <8089854e.0406142319.23efb0b0@posting.google.com> References: <8089854e.0406142319.23efb0b0@posting.google.com> Message-ID: <40cf1b0d$0$41758$5fc3050@dreader2.news.tiscali.nl> Hi, You need the 'patch' program to apply a patch, the 'diff' program to produce one. If you are under windows you should get cygwin at http://www.cygwin.com/ though you could maybe get a standalone diff and patch program for windows. I've set-up an archive of the patched files in the Lib/idlelib directory for you to download the files affected by the patch: get it at http://www.info.ucl.ac.be/~dooms/idle-syntax-patched-files.zip just unzip and copy the files in your idlelib dir. HTH -- Gr?goire Dooms Fuzzyman wrote: > "Fred Allen" wrote in message news:... > >>Dear Michael, >> >>I've searched fruitlessly for your recommended IDLE patch's download >>point. While I am probably only slightly slower than the average python >>programmer, I expect that others, no less witless than I, have had >>similar experience. Would you please post either explicit instructions >>by which I (we) can find the download. With thanks in advance, I am, >> >>Gratefully, >> >>Fred Allen >> > > > Hello Fred, > > In actual fact I replied to Gregoire (?) asking how to *apply* the > patch (I did succeed in downloading it though !)... it's not actually > my patch. Whilst I've managed to download the patch I haven't a clue > what to do with it... and I was hoping Greg would let me know..... > > If you go to : > http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group_id=5470&atid=305470 > > Right at the bottom there is a heading saying 'Attached Files'. Below > this it says : > syntaxdiffs Diffs agains CVS in 29.02.04 Download > > Needless to say the download link.. is the download one. The actual > link is : > > http://sourceforge.net/tracker/download.php?group_id=5470&atid=305470&file_id=78388&aid=906702 > > Regards, > > > Fuzzy > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > >>-----Original Message----- >>From: Fuzzyman [mailto:michael at foord.net] >>Sent: Monday, June 14, 2004 8:35 AM >>To: python-list at python.org >>Subject: Re: Good IDE for Python >> >>Gr goire Dooms wrote in message >>news:<40cc1b05$0$41764$5fc3050 at dreader2.news.tiscali.nl>... >> >>>Kamilche wrote: >>> >>>>I love Python, but I'm less than in love with IDLE. It's OK, but it >>>>really doesn't have enough capabilities. >>>> >>>>What I consider critical, are a popdown listing of all my functions, >>>>colored syntax printing, and a right-click 'definition' context menu >>>>that will hop you to the spot where that keyword is defined, if >>>>possible. Everything else I could learn to do without, but these >>>>features keep me hoping for a better IDE for Python. >>>> >>>>I'm used to the Microsoft Visual C++ debugger, and though tooltip >>>>variable debugging and intellisense were nice, they broke often >> >> enough >> >>>>that you couldn't rely on them anyway, so I don't really need those >>>>features. >>>> >>>>I would also like the ability to create application 'forms' >> >> visually. >> >>>>I'm on a Windows XP machine. >>>> >>>>Any suggestions on what I should install next? >>> >>>This patch to IDLE improves it a bit: >>> >> >>http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group >> id=5470&atid=305470 >> >>>It adds among other things the pop-down function list. >>>It's a little cumbersome to apply but the result is quite good. >>>I've been using it for a few days and I'm quite happy with it. >>>I may provide a patch against python 2.3.3 or another version if >> >> someone >> >>>is interrested. >>> >>>If you are interresed, I made a smaller patch adding the qualified >> >> name >> >>>autocompletion (module.functions). But the former patch does it >> >> >> >>>better (it even supports filename autocompletion). >> >>This looks *very* interesting. >>How do you apply a patch like this ? >> >>Regards, >> >>Fuzzy >>http://www.voidspace.org.uk/atlantibots/pythonutils.html From steve.menard at videotron.ca Thu Jun 24 09:33:04 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Thu, 24 Jun 2004 09:33:04 -0400 Subject: mysql vs sqlite vs hsql In-Reply-To: References: Message-ID: stan k. wrote: > First of all i'm on a win32 platform using java. I also have mysql > installed. My question isabout benchmarks and multiple inserts & > selects > SQLITE: http://www.sqlite.org/ > HSQL: http://hsqldb.sourceforge.net > I current have a mysql database of approx. 80mb. > Each day I Insert approx .5mb of new records into this table, > and I might also run mutiple Update, Delete, and Select queries as > well. > I'm trying to get an idea of how fast a sql database engine will run > given that is is inside of the JVM. I know it's going to be slower > than a db engine written in C and that's a trade off for being > portable to different operating systems. > What I want to know is how much of a trade off though - I don't want > to have to wait 10 mins or deal with screen freezing... Right > now on a windows platform using mysql things move really fast. > Can anyone give me an idea of the time delay needed to do these > Inserts in HSQL (ie: how much does the jvm slow things down).. > Thanks in advance Quite a few things to address in this question ... First, lemme dispell the very common misconception that java is slow. It USED to be, back when it was fully interpreted. Nowadays, most benchmark agree that java is on par with C/C++ in raw speed, depending on the kind of operation you are doing. Modern Java most notable problems are with memory usage and startup speed, both of which are being addressed (to a point) in the upcoming JRE 1.5. Second, a database system is not even CPU bound, but rather IO bound. In that respect, the algorithm used for in-memory caching and indexing will have far more influence on overall speed. As for hsqldb, past experience shows it to be remarkably fast. As you are clearly trying to embed the database, I would nto even be surprised that hsql would come out faster for you, since you can get rid of the network-call overhead of calling MySQL. It will have no problem handling the 500 KB of data a day you wish to insert, and should cause no more "screen freezes" than any other databases. Lastly sqlite does not (as far as I know) have a JDBC driver, not is it as full-featured are hsql. I would recommend you look at your requirements (multi user, gui app, web app, etc ...) and make a choice based on that, rather than the mythical slowness of the JVM. Steve From MAIL-SA at gcc-sg.org Tue Jun 22 08:45:27 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Tue, 22 Jun 2004 15:45:27 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F6509257A@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = machongbo at sohu.com Recipient(s) = python-list at python.org; Subject = ?do0?i4grjj40j09gjijgp?d? Scanning Time = 06/22/2004 15:45:27 Engine/Pattern = 7.000-1004/911 Action on message: The attachment id43342.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dooms at info.LESS.ucl.SPAM.ac.be Fri Jun 11 11:22:30 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-15?Q?Gr=E9goire_Dooms?=) Date: Fri, 11 Jun 2004 17:22:30 +0200 Subject: dynamic import with heritage In-Reply-To: <40c9c54e$0$26793$626a14ce@news.free.fr> References: <40c8d0d0$0$26780$636a15ce@news.free.fr> <40c9c54e$0$26793$626a14ce@news.free.fr> Message-ID: <40c9ce46$0$41748$5fc3050@dreader2.news.tiscali.nl> marco wrote: > Gr?goire Dooms a ?crit : > >> In your dhuile package, you need bidon in your namespace. >> This can be done by importing the module containing bidon's definition. >> According to what you say ("here my main"), this module is __main__ . >> >> So a simple >> from __main__ import bidon >> class vidange(bidon): >> pass >> should do the job. >> > > your statement doesn't work > but it works, if i do : > ------------------------- > import sys > sys.path.append("../..") > from main import bidon > ------------------------- > > does it exists a way to do it easier ? (i don't like this technick to > append a path to sys.path) > I wrote from __main__ import bidon Not from main import bidon __main__ is the namespace of the script you run. It is always already loaded so you don't need any modification to sys.path. I would define bidon in base_classes.py, have the script import that module and have the plugin import __main__ and refer to the bidon it via from __main__.base_classes import bidon Otherwise have the script add the directory of base_classes.py to sys.path and the plugin just from base_classes import bidon -- Gr?goire Dooms From me at privacy.net Thu Jun 3 03:58:26 2004 From: me at privacy.net (Duncan Booth) Date: 3 Jun 2004 07:58:26 GMT Subject: Triple quoted repr References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in news:mailman.529.1086233144.6949.python-list at python.org: >> There were no responses. Anyone have an answer? > > Perhaps something like: > > s = repr("'''multi\n'line'\nstring'''") > s = "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''", > "\\'\\'\\'"),) > > which changes \n to a linefeed, \r to a carriage return, and ''' to an > escaped form (in case you have a triple-quoted string with the same > quote character). That doesn't work very well if you have escaped backslashes followed by 'n': >>> s = '\\n' >>> print "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''", "\\'\\'\\'"),) '''''' Try this instead: def trepr(s): text = '\n'.join([repr(line)[1:-1] for line in s.split('\n')]) quotes, dquotes = "'''", '"""' if quotes in text: if dquotes in text: text = text.replace(quotes, "\\'\\'\\'") else: quotes = dquotes return "%s%s%s" % (quotes, text, quotes) It isn't perfect (lines with both ' and " will escape the single quote), but it is pretty close. From roy at panix.com Wed Jun 16 09:01:52 2004 From: roy at panix.com (Roy Smith) Date: Wed, 16 Jun 2004 09:01:52 -0400 Subject: how to become a really good Python programmer? References: Message-ID: Randall Smith wrote: > I've been programming in Python for about 2 years. I think it offers > the best combination of simplicity and power of any language I have > explored. As I write more and larger and complex programs, I need to > code better. By better I mean clearer, cleaner, more efficient and > maintainable. As the subject states, I want to become a really good > Python programmer. What you really want to do is become a really good programmer, who happens to write programs in Python. The virtues you mention; clarity, efficiency, and maintainability, are pretty much universal, regardless of what language you write in, although I'm not sure I would put them in that order. For the vast majority of code that you'll write, efficiency should not be that high on the list. First off, you want your programs to be correct. The first step in correctness is understanding what they are supposed to do. If you don't know what it's supposed to do, how do you know if it's doing it or not? Whether you use some kind of formal specification process, or something more dynamic such as the XP folks espouse, don't start writing code until you know what you're trying to do. The second step in making sure your programs are correct is testing. You can spend a lifetime learning (and arguing) about the best way to test, but any testing is better than none. Once you start making testing an essential part of your process, you'll start to discover that some programs are easier to test than others. Strive to make what you write easy to test. Clarity comes from breaking your program up into logical units (functions, classes, modules, etc) which can be understood by themselves. Huge monolithic programs with complex interactions and global data are hard to understand. Good choice of variable and function names helps too, as does good use of comments (although, exactly what constitutes good use of comments is another whole topic of debate). None of the above is Python specific. From hungjunglu at yahoo.com Sun Jun 6 00:45:39 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 5 Jun 2004 21:45:39 -0700 Subject: "intermodule-global" variables References: Message-ID: <8ef9bea6.0406052045.792cf920@posting.google.com> eddy at netido.de (Eddy Ilg) wrote: > ---- helper.py > a=5 > > def printa(): > global a > print a > ---- > > >> from helper import * > >> a > 5 > >> a=6 > >> a > 6 > >> printa() > 5 Change that to ---- helper.py import sys sys.a = 5 def printa(): print sys.a ---- from helper import * sys.a = 6 printa() ---------------------------- There are three namespaces in Python at any given moment: local, global, and built-in. You need to go through the built-in namespace, for inter-module purposes. You could choose any other module instead of sys. A more drastic approach is to directly tweak the __builtin__ module. That simplifies the reading (retrieval), but not the writing (assignment). import __builtin__ __builtin__.a = 4 print a regards, Hung Jung From ivoras at __geri.cc.fer.hr Thu Jun 24 16:35:13 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Thu, 24 Jun 2004 22:35:13 +0200 Subject: Encryption with Python In-Reply-To: References: <889cbba0.0406221926.3f4e5776@posting.google.com> Message-ID: Pierre-Fr?d?ric Caillaud wrote: > > Blowfish encryption is very secure (128 bits) and very fast (10 > megabytes/s on a Celeron 400). > I used that, you could try it. Is that for the python implementation or a C one? :)) -- What part of "Ph'nglui mglw'nath Cthulhu R'lyeh wgah'nagl fhtagn" don't you understand? From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 15:46:14 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 21:46:14 +0200 Subject: Class Chaos In-Reply-To: References: <2kb09jF3t3eU2@uni-berlin.de> Message-ID: <2kbagnFc74pU2@uni-berlin.de> Paul McGuire wrote: > It is too bad that these class names are *so* natural and intuitive, that > one just *wants* to name some temporary list as 'list' or dict as 'dict'. Doesn't PyChecker complaint about such variable names being used? Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From jjl at pobox.com Sat Jun 5 13:17:29 2004 From: jjl at pobox.com (John J. Lee) Date: 05 Jun 2004 18:17:29 +0100 Subject: urllib2 - closing sockets References: <84fc4588.0406030041.77bcdeeb@posting.google.com> <40C07445.8040201@holdenweb.com> Message-ID: <87pt8dx6ty.fsf@pobox.com> Steve Holden writes: [...] > > A patch to fix this in urllib2.py would be nice. > > Thanks > > -Anand > > In which case you'd be well advised to add this as a bug report on > Sourceforge, as that is the only way to guarantee it will come to (and > stay in) the developers' attention. > > It isn't that hard to do. Steve's right that it's not hard to do. Unfortunately, since people who actually fix bugs (ie. Martin von Loewis <0.8 wink>) are in short supply, that doesn't guarantee that it will come to anybody's attention. Of course, you have a *vastly* higher chance of getting a bug fixed if you provide a patch with appropriate docs and test code to go with it. John From aahz at pythoncraft.com Tue Jun 15 14:57:30 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 Jun 2004 14:57:30 -0400 Subject: Q: attribute access and comparisons of two different objects References: <2418de8e.0406150420.1c1bde76@posting.google.com> Message-ID: In article <2418de8e.0406150420.1c1bde76 at posting.google.com>, Chris... wrote: > >1) Is there already a "fix" to avoid writing to an attribute that >isn't defined yet? I remember this being an often discussed problem, >but didn't see any changes. The only way I can think of is overriding >__setattr__, but this is huge overhead. While I like the idea of >being able to add new attributes on the fly, in great projects I'd >like to restrict some classes not to do so. Don't use __slots__. Why do you think __setattr__ is a huge overhead? >2) This is driving me nuts: I do not want to compare apples and peas. >I can say that they are not equal, but I cannot say that one is great >than the other (speaking not of greater taste ;-). Just ran into a >problem caused by comparing a string with a number ("1" > 10) -- I >simply forgot to convert the string to an integer. Since I cannot add >"1" + 10 which makes sense, I do not want to compare them. Any >development regarding this? Any """from __future__ import"""? You'll have to wait for Python 3.0 for the core to fully support this; meanwhile, you can only force this with your own classes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From roy at panix.com Mon Jun 21 12:56:41 2004 From: roy at panix.com (Roy Smith) Date: Mon, 21 Jun 2004 12:56:41 -0400 Subject: Python memory use (psyco, C++) References: Message-ID: In article , Tyler Eaves wrote: > On Mon, 21 Jun 2004 12:28:33 -0400, Roy Smith wrote: > > > I know all of the above is very vague, but I'm just trying to get a > > rough idea if a Python implementation is feasable (or at least > > plausable). If a C++ version takes 300 Mbytes and a Python version > > takes 1 Gig, that's probably not going to work. Are there any rules of > > thumb I could use to get a first-order estimate? > > Why wouldn't it work? Memory is still quite cheap. If this is an app of > any complexity, the development time saved vs C++ will probably far more > than additional memory would cost. Because memory use is one of the constraints I was given to work with. From miki.tebeka at zoran.com Thu Jun 10 03:12:55 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 10 Jun 2004 09:12:55 +0200 Subject: Priting Out in COLOURS In-Reply-To: <009e01c44e4c$e2f785d0$559ea380@D4XN6B41> References: <009e01c44e4c$e2f785d0$559ea380@D4XN6B41> Message-ID: <20040610071255.GE1876@zoran.com> Hello Satish, > This must be a simple thing to do, but am not sure about it. I like to > know how I can print my statements out, in colour. My web site is down so I'm adding the code in the mail. HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. --- ansiprint.py --- #!/usr/bin/env python '''Print message using ANSI terminal codes''' __author__ = "Miki Tebeka " # $Id: ansiprint.py,v 1.1 2003/09/07 13:26:28 mikit Exp $ # Copyright (c) Miki Tebeka # This file is under the GNU Public License (GPL), see # http://www.gnu.org/copyleft/gpl.html for more details from sys import stdout, stderr # Format bright = 1 dim = 2 underline = 4 blink = 5 reverse = 7 hidden = 8 # Forground black = 30 red = 31 green = 32 yellow = 33 blue = 34 magenta = 35 cyan = 36 white = 37 # Background on_black = 40 on_red = 41 on_green = 42 on_yellow = 43 on_blue = 44 on_magenta = 45 on_cyan = 46 on_white = 47 def ansiformat(msg, *args): '''Format msg according to args. See http://www.termsys.demon.co.uk/vtansi.htm for more details/ ''' return "\033[%sm%s\033[0m" % (";".join(["%s" % f for f in args]), msg) def ansiprint(msg, *args, **kw): '''Print formatted message. Should work on ANSI compatible terminal. ''' if kw.get("stderr", False): outfo = stderr else: outfo = stdout outfo.write(ansiformat(msg, *args)) outfo.flush() if __name__ == "__main__": from sys import argv, exit from os.path import basename h = { "bright" : bright, "dim" : dim, "underline" : underline, "blink" : blink, "reverse" : reverse, "hidden" : hidden, "black" : black, "red" : red, "green" : green, "yellow" : yellow, "blue" : blue, "magenta" : magenta, "cyan" : cyan, "white" : white, "on_black" : on_black, "on_red" : on_red, "on_green" : on_green, "on_yellow" : on_yellow, "on_blue" : on_blue, "on_magenta" : on_magenta, "on_cyan" : on_cyan, "on_white" : on_white } eg = "e.g. ansiprint hello red on_green underline -> %s" % \ ansiformat("hello", red, on_green, underline) # Check command line if len(argv) < 2: print >> stderr, "usage: %s message [format ...]" % basename(argv[0]) print >> stderr, eg exit(1) for i in argv[2:]: if i not in h: ansiprint("%s: Unknown format\n" % i, red, bright, stderr=True) print >> stderr, "Formats can be:", msg = ", ".join([ansiformat(f, h[f]) for f in h.keys()]) print msg print >> stderr, eg exit(1) # Print ansiprint(argv[1], *[h[i] for i in argv[2:]]) print --- ansiprint.py --- From moughanj at tcd.ie Tue Jun 8 01:59:16 2004 From: moughanj at tcd.ie (James Moughan) Date: 7 Jun 2004 22:59:16 -0700 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> <40c0b153$1_1@127.0.0.1> Message-ID: <16752bcc.0406072159.420426a3@posting.google.com> > >--Kamilche > > I am no C++ expert, to put it mildly, but couldn't some of your problems > have been solved by using C++ instead of C? C++ has data structures like > vectors, lists, and maps, with many algorithms in the STL to work with them. > Using references to pass arguments, one can avoid low-level pointers in many > cases. C++ strings are easier to use the C char's. There are templated classes > to replicate some of the functionality of Python's Numeric/Numarray or Fortran > 90/95 arrays. C is more of a low-level systems language than an application > programming language -- comparing it to Python seems unfair to me, when the > choice of C++ exists. > Heresy, but - often I find C++ a more natural way to express algorithms than Python. In particular iterators (OK, being blunt - pointers) are often a great way to break down complexity. Unfortunately, the amount of junk you have to deal with to get there is just not worth it. > For strictly numerical tasks Fortran 95 is in my experience both more readable > than Python (because of variable declarations and the ability to define constants) > AND much faster. You do not have to suffer Python's performance hit to program > in a clean, high-level language. > > (I like Python, but there is so much pro-Python propaganda in this newsgroup > that some anti-Python messages may be a healthy corrective.) > I keep hearing great things about F95; I'll have to try it out. > > > ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From mwh at python.net Fri Jun 4 03:58:54 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 4 Jun 2004 07:58:54 GMT Subject: 2.2 <-> 2.3 surprise References: Message-ID: Roman Suzi writes: > On Mon, 31 May 2004, Shalabh Chaturvedi wrote: > > >Roman Suzi wrote: > > > >> Hi! > >> > >> I really like python 2.3 but sometimes I write for 2.2 too. > >> > >> New cool feature of doing: > >> > >> f = open('file') > >> for line in f: > >> do_something(line) > >> > >> works strange in 2.2: I can't just quit first loop and do: > >> > >> for line in f: > >> do_some_more(line) > >> > >> (I as skipping message header by first loop and processing body > >> the the second). > >> > >> In 2.3 it works as intended! Of course, simple refacture made it one loop... > >> > >> > >> > >> Sincerely yours, Roman Suzi > > > >This is probably the following change as described in > >http://www.python.org/2.3/highlights.html > > > >"File objects are now their own iterators. This makes multiple > >interrupted iterations over the same file more reliable." > > Hmmm... Such gradual changes IMHO are worse than just adding something > at once. The problem is I was getting no warnings that something is wrong. > In some big project this could break a lot. Are you arguing that the 2.2 behaviour should have been retained? If so, you're wrong :-) Cheers, mwh -- This makes it possible to pass complex object hierarchies to a C coder who thinks computer science has made no worthwhile advancements since the invention of the pointer. -- Gordon McMillan, 30 Jul 1998 From qrczak at knm.org.pl Mon Jun 14 04:53:43 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Mon, 14 Jun 2004 10:53:43 +0200 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: On Mon, 14 Jun 2004 00:00:39 -0700, David Turner wrote: > The D programming language somehow contrives to have both garbage > collection and working destructors. So why can't Python? What happens in D when you make a pointer to a local variable, the variable goes out of scope, and you use the pointer? Undefined behavior? If so, it's unacceptable for Python. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From me at privacy.net Wed Jun 9 05:03:09 2004 From: me at privacy.net (Duncan Booth) Date: 9 Jun 2004 09:03:09 GMT Subject: parsing in python References: Message-ID: Peter Sprenger wrote in news:ca6ep3$8ni$01$1 at news.t-online.com: > I hope somebody can help me with my problem. I am writing Zope python > scripts that will do parsing on text for dynamic webpages: I am getting > a text from an oracle database that contains different tags that have to > be converted to a HTML expression. E.g. "" ( # is an integer > number) has to be converted to where the image data > comes also from a database table. > Since strings are immutable, is there an effective way to parse such > texts in Python? In the process of finding and converting the embedded > tags I also would like to make a word wrap on the generated HTML output > to increase the readability of the generated HTML source. > Can I write an efficient parser in Python or should I extend Python with > a C routine that will do this task in O(n)? You do realise that O(n) says nothing useful about how fast it will run? Answering your other questions, yes, there are lots of effective ways to parse text strings in Python. Were I in your position, I wouldn't even consider C until I had demonstrated that the most obvious and clean solution wasn't fast enough. You don't really describe your data in sufficient detail, so I can only give general suggestions: You could use a regular expression replace to convert tags with the appropriate image tag. you could use sgmllib to parse the data. you could use one of Python's many xml parsers to parse the data (provided it is valid xml, which it may not be). you could use the split method on strings to split the data on '<'. Each string (other than the first) then begins with a potential tag which you can match with the startswith method or a regular expression. You could replace '<' with '%(' and '>' with ')s' then use the % operator to process all the replacements using a class with a custom __getitem__ method. If you want to word wrap and pretty print the HTML, then that is better done as a separate pass. Just get a general purpose HTML pretty printer (e.g. mxTidy) and call it. That way you can easily turn it off for production use if you really are concerned about speed. From richie at entrian.com Thu Jun 17 08:59:25 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 17 Jun 2004 13:59:25 +0100 Subject: how to become a really good Python programmer? Message-ID: <0b53d0hd8kjie9ppng0j1g9uv5mnpceoc1@4ax.com> [Repost; apologies to anyone who sees this twice] [Randall] > As I write more and larger and complex programs, I need to > code better. By better I mean clearer, cleaner, more efficient and > maintainable. If you're not doing so already, start using Test-Driven Development. Google will give you any number of resources about that, but in a nutshell it means writing unit tests *before* writing code, then writing the code to make the tests pass. This forces you to think about the design of your modules up front, and usually leads to better-designed software. The modules you write will have cleaner interfaces and will be less dependent upon each other, more clearly written, more reusable, and more amenable to changing without breaking things. The other important feature of test-driven development is that it's *hard*, or at least it's hard for some application areas (like networking and GUIs). There's nothing like working on a hard problem to sharpen your skills - knocking up a messy script is easy, but you don't learn from it. A concrete example of why it's hard and why it leads to better code: I have a lightweight RPC system (as yet unpublished) that sends "safe pickles" over the network to invoke functions on another machine. The unit tests are a mess, because they run the client and server socket code in different threads in the same process, and synchronising them is painful. Had I thought more about it up front, I'd have realised that the RPC system should be transport-independent, and the unit tests should provide a trivial transport system for the RPC code to use during the tests, rather than mucking about with sockets. I'd have ended up with a nice transport-independent RPC module with simple and complete unit tests, plus a tiny transport module to implement a socket transport for it. Done right, the transport module would be so trivial that either it didn't need unit tests, or the tests would be very simple. A question for experienced TDD-ers: is TDD really more intellectually demanding than code-first, or am I either a) doing it wrong, or b) stupid? -- Richie Hindle richie at entrian.com From tgiles at nospamming.kc.rr.com Tue Jun 15 03:44:54 2004 From: tgiles at nospamming.kc.rr.com (tgiles) Date: Tue, 15 Jun 2004 07:44:54 GMT Subject: searching strings using variables Message-ID: Hi, all. Another bewildered newbie struggling with Python goodness. This time it's searching strings. The goal is to search a string for a value. The string is a variable I assigned the name 'myvar'. however, it doesn't seem to be seeing it... Here's a snippet. import re # list of items to search... mylist = [ 5 , 6 , 16 , 17 , 18 , 19 , 20 , 21 ] # my variable I want to search with... myvar = '16' print re.search('myvar','mylist') ... just returns none. Tried it also with... mylist.index('myvar') to see if I could spook it out but I get a ValueError (not in list) so it looks like it won't see it either. I did vague permutations trying to make it work but no go. I'm thinking it may be one of those "forest for the trees" things, i've been looking at it too hard. Any ideas? many thanks in advance! tom From tkpmep at hotmail.com Tue Jun 22 16:12:23 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 22 Jun 2004 13:12:23 -0700 Subject: Improving upon the Decorate-Sort-Undecorate idiom Message-ID: I recently had the need to sort a large number of lists of lists, and wondered if an improvement to the Decorate-Sort-Undecorate idiom is in the works. Ideally, I would like to sort the list of lists (or tuples) in place by using a simple variant of the current idiom, i.e. list_of_lists.sort(*columns) where *columns is a tuple that specifies the column order for the sort. If *columns is left blank, the sort ought to work as it does today, i.e. list_of_lists.sort() should sort by columns 0, 1,2,..... Has such a method been considered for inclusion in Python? Does it have any problems that would inhibit its adoption? Thomas Philips From winexpert at hotmail.com Thu Jun 17 06:38:22 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 17 Jun 2004 10:38:22 +0000 Subject: [python] Figured out how to go from email.Message.Message to string Message-ID: It took a little bit of digging but I finally figured it out by looking in my /usr/local/lib/py* directory's python modules. Turns out in the Message.py module there is a __str__ method you can call to convert to a string. And when i read more I found out its doing a fancy flatten. I've seen references to flatten around so this will help reinforce in my mind what it means for a flat tened or flat python object. David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Looking to buy a house? Get informed with the Home Buying Guide from MSN House & Home. http://coldwellbanker.msn.com/ From sh at defuze.org Wed Jun 16 06:28:40 2004 From: sh at defuze.org (Sylvain Hellegouarch) Date: Wed, 16 Jun 2004 11:28:40 +0100 Subject: python with Java API In-Reply-To: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> References: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Brendan, I would definitely go for Qt which doc is just awesome. Personnal opinion of course. - Sylvain Brendan J Simon wrote: > Hi, > > I have a Java application from a company. They also provide an API in > C++ (MSW platforms only) and Java (for all platforms) for developers > that want to create their own front end. I want to use wxPython to > create a decent Unix opensource frontend. > > Is it possible to Interface python to a java application easily ??? > > Assuming yes to above, would something like Jython or SWIG or some other > tool be required. > > Any advice or pointers would be greatly appreciated. > > Regards, > Brendan Simon. From fperez528 at yahoo.com Tue Jun 15 15:41:52 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 15 Jun 2004 13:41:52 -0600 Subject: Num Array problem with Embedding python in C References: <4039221c.0406150000.26c2d13@posting.google.com> Message-ID: youngdubliner at hotmail.com wrote: > I'm having a problem ........ > > I've stripped all my code to help isolate the problem. > > Its seems to be with importing numarray when python is embedded in C. > > I have a simple C program it Opens Python imports a script and > then Closes Python > > like so ....... > > int main(int argc,char *argv[]) > { > > int count = 0; > PyObject *pmod; > > while ( count < 10) > { > > /* > ** Initialize Python > */ > > Py_Initialize(); > printf("\nOpen Python ---- >"); > > pmod = PyImport_ImportModule("test"); > > Py_DECREF(pmod); > > /* > ** Close Python > */ > > Py_Finalize(); > printf("\n<---- Closed Python"); > > > /* > ** Do this 10 times ! > */ > count++; > > } > getchar(); > return(0); > > } > > and thats it ! > > The script it calls is test.py its very simple , it imports numarray > and then returns. like so ....... > > ----------------------- > test.py > ----------------------- > #Imports > from numarray import * > > def test_func(): > return (99) > ----------------------- > end of file > ----------------------- > > > The first time it is called from my C code > it all works fine ! ( but only the first time ! ) > > In the second iteration above test .c crashes From: http://www.pfdubois.com/numpy/html2/numpy-13.html ************************************************************************* The Numeric installation process installed arrayobject.h in a subdirectory Numeric in your Python include path, so you should include it this way: #include "Numeric/arrayobject.h" Is your C extension using Numeric blowing up? Maybe you didn't call import_array(). If the extension is not in a single file, also define PY_ARRAY_UNIQUE_SYMBOL. In addition to including arrayobject.h , the extension must call import_array() in its initialization function, after the call to Py_InitModule() . This call makes sure that the module which implements the array type has been imported, and initializes a pointer array through which the NumPy functions are called. If you forget this call, your extension module will crash on the first call to a NumPy function. ************************************************************************* This referst to Numeric, but I'm sure the same issue exists with Numarray (I still use Numeric, so I don't know the details with numarray). cheers, f From fumanchu at amor.org Sun Jun 6 10:35:01 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 6 Jun 2004 07:35:01 -0700 Subject: Using function parameters to determine method kind Message-ID: Humpty Dumpty wrote: > From: "Michele Simionato" > > No, I had in mind this (contrived) example: > > > > class Outer(object): > > def outermeth(self1): > > class Inner(object): > > def innermeth(self2): > > > > ... > > > > It is nice to have the ability to give any name to "self". > > like that). > > Strange, I would have thought that self1 would not be in > scope (it's not in > the local scope and it's not in the global scope AFAICT). If > true, you'd > have to have a parameter to your innermeth, which you can > call whatever you > want so call it self1. Have scoping rules changed in Python? Before or after 2.2? http://www.python.org/peps/pep-0227.html FuManChu From olli at haluter.fromme.com Fri Jun 25 13:25:24 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 25 Jun 2004 17:25:24 GMT Subject: Parameterized Functions without Classes References: Message-ID: <2k35g4F14l1o0U1@uni-berlin.de> Christian Tismer wrote: > just as a small comment on the side-effects of the > rather new concept of local functions with access to > their scope: > [...] > def _converter(scale): > def convert(arg): > return scale * arg > return convert In what way is that different from using an ordinary lambda function? i.e.: def _converter(scale): return lambda arg: scale * arg Of course, the use of lambda functions is very limited because (unfortunately) they can contain only one single expression. But other than that, it's pretty much the same concept, isn't it? Best regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From claird at lairds.com Sun Jun 6 21:03:19 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 07 Jun 2004 01:03:19 -0000 Subject: compiling python with unix References: <40c033e0$0$2277$afc38c87@news.easynet.fr> <10c0un6nf57b4ce@corp.supernews.com> <40c32fbd$0$2287$afc38c87@news.easynet.fr> Message-ID: <10c7fmn7te6nad8@corp.supernews.com> In article <40c32fbd$0$2287$afc38c87 at news.easynet.fr>, RosalieM wrote: . . . >I used a lfs 4.0 to build my unix. But is is very fat. I can compile python >from there and play with "Hello World", but i dont uderstand how to choose >what i need and what i dont need to compile it and choose features that >python would be able to do. > >For example, can i build python on a minix system? >Why socket module needs threads to compile ? > >I search answers to this kind of questions. . . . Now I understand MUCH better. Yes and no. No, standard Python does not generate cleanly under Minix. The sockets module wants to offer concurrency--do I need to explain why it's so natural to support services that can multitask?--and a design decision early in Python's history and architecture was to model concurrency on threading. It certainly is possible to construct good socket interfaces without threads; Tcl, for example, does so. Python simply made a different choice, though, and one which I think you're observing complicates its porta- bility to some operating systems. On yet another hand, some people work with "small Pythons", ones which include only a fraction of the standard Python's capabilities. I'm sure one of those will do fine under Minix. One quick way to make progress in that direction is to pick up an early distribution--Python 1.2? 2.0?--and see how you like that. What's the *real* goal, though? Do you want any small-but- capable language under any small-but-capable embedded operating system? If that's the only constraint, I might be inclined to look to a language more easily portable and slender than Python, maybe Lua, Tcl, Forth, or one of the small Lisps. -- Cameron Laird Business: http://www.Phaseit.net From reiner.block at bisoft.de Thu Jun 3 13:46:14 2004 From: reiner.block at bisoft.de (Reiner Block) Date: Thu, 03 Jun 2004 19:46:14 +0200 Subject: Background of editor in eric3 References: <2i8m0jFk8st1U1@uni-berlin.de> Message-ID: <2i96f6Fklj78U1@uni-berlin.de> MF wrote: > not so blind :-) wherefrom you know that I'm wearing glasses? ;-) > I can confirm Reiner's problem: installed eric3 two days ago and I could not > find a possibility to change the bg color. I am still searching too. :-) > > Moreover: qscintilla has an enormous right click menu with all kind of > options that should usually be placed somewhere in the real menu. Right > click by mistake makes me wishing a mouse without the right button :-) But not for change the background color. :-( > As for white screens, I don't know what other people think, but I used to > use them a lot in my now past night net wanderings, believing they are more > easy for the eyes. Apparently no, quite the contrary, when last checking my > eyes, the doctor told me white text in black screen (paper) is called > "inverse contrast" and because they are... so inverse to what we are used > to from school, they are in fact more tiresome, only we do not realize it. > > The right screen should look something like a book, black on white, anyway > light background... I just want to make it less white more fawn. Searching greetings Reiner -- "Was immer du tun kannst oder ertr?umst zu k?nnen, beginne es jetzt." von: Johann Wolfgang von Goethe (1749-1832) Reiner Block http://www.bisoft.de From nhirsh2 at ieee.org Mon Jun 14 10:15:12 2004 From: nhirsh2 at ieee.org (Neale) Date: 14 Jun 2004 07:15:12 -0700 Subject: How to Access Unix Shell References: <2d7af4f8.0406131648.42868c63@posting.google.com> Message-ID: <2d7af4f8.0406140615.310f1875@posting.google.com> > > > [[snip]] > > How about : > > === > > files = os.listdir(".") > > === > > > > Bye. > > -- > > ------------------------------------------------------------------------- > > Miki Tebeka > > Well, I could claim that I knew about listdir but was simply answering the > original question which was how to run arbitrary shell commands. > > But in fact I knew nothing of listdir (all of my coding so far has been with > wx(Python|Widgets) so I rarely use the python system stuff) , so I thank you > for the education :-). > > Pax. Thank you for such high quality help. If there are other Unix command functions like listdir, where/how do I find them? Is there a particular directory in Python, maybe? From tim.one at comcast.net Mon Jun 7 10:12:44 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 7 Jun 2004 10:12:44 -0400 Subject: how to get memory info from python? In-Reply-To: <6ee58e07.0406070442.6e8d32fe@posting.google.com> Message-ID: [Lothar Scholz] > But obmalloc.c has a high performance penalty That's a peculiar claim. All comparative timings I've seen showed it beating the platform malloc, starting with Vladimir Marangozov's original studies (Vladimir originally wrote obmalloc for "go fast" reasons). > and can't be recommend for productivity systems that must work on a > game console. That may be true regardless (or may not ). From __peter__ at web.de Sat Jun 12 09:16:34 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jun 2004 15:16:34 +0200 Subject: Unbind initial bind on basic widget (text) References: Message-ID: Askari wrote: > Do I can unbind the initial bind on basic widget? (ex.: the basic > widget > Text have the bind "" for the return to the first caracter of > the line; but me I don't want this!) > I try 'myText.unbind("")' but the bind is not remove. > :-( I see two options. 1. Prevent the event from being propagated to the class. def breaker(*args): return "break" mytext.bind("", breaker) 2. Unbind the event on the class level. mytext.unbind_class("Text", "") > N.B. I wan't disabled ALL initial bind (not just the "") Maybe you should just disable the widget? mytext["state"] = "disabled" Peter From me at privacy.net Thu Jun 3 12:11:38 2004 From: me at privacy.net (Duncan Booth) Date: 3 Jun 2004 16:11:38 GMT Subject: speed problems References: Message-ID: Steve Lamb wrote in news:slrncbuebm.i05.grey at dmiyu.org: > Python: >> for line in lf.readlines(): >> if string.count( line, "INFECTED" ): >> vname = re.compile( "INFECTED \((.*)\)" ).search( line >> ).group(1) > > If I read this correctly you're compiling this regex every time > you're > going through the for loop. So every line the regex is compiled > again. You might want to compile the regex outside the loop and only > use the compiled version inside the loop. > > I *think* that Perl caches compiled regexs which is why they don't > have > two different ways of calling the regex while Python, in giving two > different calls to the regex, will compile it every time if you > expressedly call for a compile. Again, just a guess based on how I > presume the languages work and how I'd write them differently. No, Python will cache the calls to compile the regex so you won't get much speed difference unless you have enough different regexes to overflow the cache. Pulling the compile out of the loop is a good idea on general principles though. The code you quoted does have one place to optimise: using readlines, especially on a large file will be *much* slower than just iterating over the file object directly. i.e. use for line in lf: ... whatever ... Some other things that could be improved (although I suspect the real problem was calling readlines): The original code posted uses functions from the string module. Using string methods instead ought to be faster e.g. line.count("INFECTED") instead of string.line(count, "INFECTED") Use if logfile.endswith('.gz'): instead of: if logfile[-3:] == '.gz': Use: if "INFECTED" in line: instead of calling line.count I don't understand why the inner loop needs two cases, one for vname containing a ',' and one where it doesn't. It looks to me as though the code could just split whether or not there is a comma. If there isn't one it just returns the original string. Untested revised code: INFECTEDPAT = re.compile( "INFECTED \((.*)\)" ) for line in lf: if "INFECTED" in line: vname = INFECTEDPAT.search(line).group(1) for vnam in vname.split(", "): if vnam not in virstat: virstat[vnam] = 1 else: virstat[vnam] += 1 total += 1 lf.close() From fumanchu at amor.org Tue Jun 8 22:33:44 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 8 Jun 2004 19:33:44 -0700 Subject: Perlish dictionary behavior Message-ID: Fred Allen wrote: > I fruitlessly tried your "thing counter", as you can see below. > > >>> class AllThingsStartAtZero(dict): > ... def getitem (self, key): > ... return dict.get(self, key, 0) > ... As Chris pointed out, it should be __getitem__ (two leading underscores and two trailing). If you read the original on Google (say, from the link in Dr. Dobb's? ;), they cut out underscores somewhere along the line. FuManChu From klachemin at home.com Fri Jun 25 16:36:31 2004 From: klachemin at home.com (Kamilche) Date: 25 Jun 2004 13:36:31 -0700 Subject: Code: Rolling a Container Into a String References: <889cbba0.0406241742.51a2980b@posting.google.com> Message-ID: <889cbba0.0406251236.4b6f42e8@posting.google.com> Pierre-Fr?d?ric Caillaud wrote in message news:... > Use YAML > It looked interesting, so I downloaded it... and was confronted with dozens of files, and the need to compile before use... when I was looking for a simple cross-platform 2 function solution that didn't take any DLL's. Dang. Well, it's a new day, maybe I'll be inspired. From siona at chiark.greenend.org.uk Thu Jun 3 10:19:41 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 03 Jun 2004 15:19:41 +0100 (BST) Subject: Why did no one invent Python before? References: Message-ID: j_mckitrick wrote: >Seriously, why is a language like this only NOW appearing? As others have pointed out, Python has been around for a good decade (as have a number of other powerfully expressive languages, particularly in the functional camp). A more pertinent question might be why, when languages like this appeared some time ago, are monstrosities like C# still being created? (I recently saw some basic socket server code in C# -- it's a poor reflection on a supposedly modern, high-level language when the pure C equivalent would be *less* verbose. And the library designers appear to have not encountered the concept of polymorphism.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From t-meyer at ihug.co.nz Sat Jun 26 19:55:07 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sun, 27 Jun 2004 11:55:07 +1200 Subject: How to trim n characters from right end of a string? In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1306E92DEF@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677FE6@its-xchg4.massey.ac.nz> > Please tell this newbie how to remove n characters from the > right end of a string. You can't - Python strings are immutable. You can, however, create a new string that is the same as the old one less the n rightmost characters, which should do what you need. >>> s = "This is a string" >>> s[:10] 'This is a ' The tutorial on strings would be well worth reading to help with this sort of thing. =Tony Meyer From skip at pobox.com Mon Jun 7 17:30:49 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 7 Jun 2004 16:30:49 -0500 Subject: if does not evaluate In-Reply-To: <2ik434Fntu3aU1@uni-berlin.de> References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> Message-ID: <16580.56969.935322.116296@montanaro.dyndns.org> Jim> lambda seem to work for very simple things but not for anything Jim> substantial. Right. Like Terry said, for anything more substantial use a named function. Lambda was never intended to be a replacement for def, and Python is fundamentally not a functional language (in the Haskell/Lisp sense of the term), so powerful anonymous functions are generally not needed. In fact, as list comprehensions and generator expressions take root, lambda's use dwindles. Skip From bpeng at rice.edu Sat Jun 5 00:24:38 2004 From: bpeng at rice.edu (Bo Peng) Date: Fri, 04 Jun 2004 23:24:38 -0500 Subject: Can python control complicated classes/objects written in C++ Message-ID: Dear Python group: I am planning on an application that involves several complicated C++ classes. Basically, there will be one or two big data objects and some "action" objects that can act on the data. I would like to use a script language to control the interaction between these c++ objects. I become interested in Python since it can load C++ objects and can even extend C++ classes. However, I am not quite sure to what extent can python do this. Ideally, I would like to have something like (pseudo code, not in python) > data = new TData( option1=..., option2=...) > action1 = new TAction(option1=range(1,10)...) > action2 = new TSubAction(option1=sin(5),..., option2=...) > data.run( action1, action2) > data.print The benefits here is that I do not have to worry about user-input (python handles functions like range(), and numeric/string operations for me and send them to my objects), running logic (user create the scripts) and need only focus on the objects themselves. It would be better if users can easily extend TAction by themselves, through either Python or C++. I am totally new to Python. I have read boost.python, python extension document but still do not know exactly what to do. My questions are: 1. can Python fully read/write member data and run member functions of my objects? 2. can python pass complicated objects (TAction) to another object (TData)? 3. If python can not do this, I will have to create my own scripting language. Given the above pseudo code, any suggestion on how to implement it? I have googgled Qt Script for Application and many other weird implementations but I either do not like the grammar of the script language or the huge overheads. Many thanks in advance. Bo From lbates at swamisoft.com Thu Jun 3 13:28:09 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 12:28:09 -0500 Subject: Case-insensitive globbing References: Message-ID: Just use os.path.normcase() on all of them. import glob import os flist=glob.glob(mask) flist=[os.path.normcase(f) for f in flist] ... HTH, Larry Bates Syscon, Inc. "Thomas Philips" wrote in message news:b4a8ffb6.0406030859.197ec3b3 at posting.google.com... > I'm using the function glob from module glob to obtain a list of all > files in a directory that match a pattern. Unfortunately, some > filenames are in upper case, others are in lower case and yet others > are in mixed case. How can I do a case-insenstive glob that picks up > all files that match a string regardless of case? If its any help, I'm > running Python 2.3.4 under Windows XP. > > Thomas Philips From Scott.Daniels at Acm.Org Fri Jun 4 12:03:53 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 04 Jun 2004 09:03:53 -0700 Subject: variables in string.count In-Reply-To: <97Vvc.91067$Qc.3537756@twister1.libero.it> References: <59eb2b00.0406032201.4bf6926d@posting.google.com> <97Vvc.91067$Qc.3537756@twister1.libero.it> Message-ID: <40c0a1a5$1@nntp0.pdx.net> Matteo Dell'Amico wrote: ... (good stuff)... > I'd code it like this: > > while secret: > print > letter = raw_input("What letter? ").lower() > # we probably should do something to make sure len(letter) == 1 > if letter not in secret: > print "Try again!" > else: > secret = secret.replace(letter, '', 1) Exceptions are your friend, don't ask permission: def tests(secret): parts = list(secret.lower()) while parts: reply = raw_input("What letter(s)? ") for letter in reply: try: parts.remove(letter.lower()) except ValueError: print "%r not found" % letter if parts: print len(parts), 'letters left; try again.' -- -Scott David Daniels Scott.Daniels at Acm.Org From aahz at pythoncraft.com Sun Jun 13 23:43:58 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Jun 2004 23:43:58 -0400 Subject: does python have useless destructors? References: <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: In article , David Turner wrote: > >The huge advantage that the RAII approach holds in this respect is >that the user of the library just does what comes naturally - for >example, he declares a file object and uses it. He would have done >that anyway. He doesn't need to know whether or not it's a RAII >object that needs a "with" or "using" or "dispose" or "try/finally" >clause. Do you know any RAII approach that does not depend on stack-based locals semantics? Python's global objects are extremely useful, and unless you want to essentially create a new language, anything remotely resembling pure RAII in the language core won't work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From dave at boost-consulting.com Wed Jun 23 17:30:37 2004 From: dave at boost-consulting.com (David Abrahams) Date: 23 Jun 2004 14:30:37 -0700 Subject: Determining caller's file and line number Message-ID: <8a638f47.0406231330.7d59152f@posting.google.com> Is there any way to determine the file and line number (if any) of a method's invocation from within its body? Many Thanks in advance, Dave -- David Abrahams Boost Consulting http://www.boost-consulting.com From davidf at sjsoft.com Mon Jun 14 11:10:12 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 14 Jun 2004 17:10:12 +0200 Subject: new to the list and... In-Reply-To: References: Message-ID: Daniel Farmer wrote: > Hi... I'm just getting started with P, but am very eager to explore it's > possiblities. > > Where would I begin to find out about creating windows like GUI with Python? > > I've downloaded tcl/tk... I'm not exactly sure what to do with them at > this point. ( they're sitting in folders on my desktop ). > As many other people might suggest, if/when you don't find tcl/tk to you liking, move on over to http://www.wxpython.org and give it a go David From pit.grinja at gmx.de Tue Jun 29 15:16:11 2004 From: pit.grinja at gmx.de (Piet) Date: 29 Jun 2004 12:16:11 -0700 Subject: wxPython: wxGrid vs. wxListCtrl Message-ID: <39cbe663.0406291116.166f436a@posting.google.com> Hello. I am working on an XML editor that will not display the xml file as plain text, but will rather work with a combination of a tree view for the main element nodes and some kind of tabular view to view attributes. By this way, the user (i.e. me) will only have the opportunity to change textual contents and attribute values, but neither element nor attribute names. Building the tree view was not a problem, but I haven?t found a good widget for the "grid view" component. wxGrid allows to edit the content of the table (which will be the attribute values) but I haven?t found a way to link a specific cell to a certain xml node. This is important, because when the cell content changes I would like to be able to directly communicate this change to the underlying xml tree (in the tree component of the editor, this is already achieved). wxListCtrl would be the second choice. THis where I first focused on an wrote the following code: class ListCtrlWindow(wxFrame): def __init__(self, parent, node): wxFrame.__init__(self, parent, -1,"Attribute list") attributeListCtrl = wxListCtrl(self,-1,style = wxLC_REPORT|wxLC_VRULES|wxLC_HRULES|wxLC_EDIT_LABELS ) numberOfAttributes = 0 attributeNameList = [] attributeListCtrl.InsertColumn(0,"Number",format=wxLIST_FORMAT_LEFT, width=-1) for attribute in node.attributes.keys(): attr = node.attributes.get(attribute) print attr.nodeName + "\n" attributeListCtrl.InsertColumn(numberOfAttributes+2,attr.nodeName,format=wxLIST_FORMAT_LEFT, width=-1) +numberOfAttributes attributeNameList.append(attr.nodeName) for entry in attributeNameList: print entry + " " + str(attributeNameList.index(entry)) + "\n" numberOfSiblings = 0 if node.parentNode != None: childs = node.parentNode.childNodes numRows = 0 for numberOfSiblings in range(len(childs)): print childs.item(numberOfSiblings).nodeType if childs.item(numberOfSiblings).nodeType == 1: attributeListCtrl.InsertStringItem(numRows,str(numRows)) if childs.item(numberOfSiblings).attributes != None: for attribute in childs.item(numberOfSiblings).attributes.keys(): attr = childs.item(numberOfSiblings).attributes.get(attribute) if attributeNameList.count(attr.nodeName) == 0: attributeNameList.append(attr.nodeName) attributeListCtrl.SetStringItem(numRows,attributeNameList.index(attr.nodeName)+1,attr.nodeValue) numRows = numRows + 1 attributeListCtrl.EnsureVisible(True) attributeListCtrl.SetColumnWidth(-1,-1) But there I have two problems/questions: First, a very general one: I would like to edit the contents of the table, but when I double click on the respective line, only the first element is editable. Second, I have not yet completely understood the "data structure" behind a list item. Does each line of a listctrl represent a single item? Is it possible to address the entries in the line in the same was as "cells" of a "table row"? Can items which are located in different lines but are positioned in the same "column" be selected like grid cells which belong to one column? To me it looks a little as if listctrl was mainly for displaying data and not for editing. So do I have to use a wxGrid for the attribute list and define my own mechanism to connect a cell to a data object? Any hints are appreciated. Regards Peter From R.Brodie at rl.ac.uk Tue Jun 1 08:30:10 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 1 Jun 2004 13:30:10 +0100 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: "A.M. Kuchling" wrote in message news:a8udncumWbla7iHdRVn-uw at speakeasy.net... > Timo Virkkala wrote: > > When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! > > I suspect the letters are simply random. The usual way to complete the > sentence would be "only outlaws will have cryptography", but that doesn't > match the word lengths. There is also a lot of keyboard locality: adjacent letters, nothing from the bottom row, etc. From rogerb at rogerbinns.com Thu Jun 17 19:13:27 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 17 Jun 2004 16:13:27 -0700 Subject: Queue module and Python Documentation Rant References: Message-ID: <6bl9q1-e98.ln1@home.rogerbinns.com> Bart Nessux wrote: > How can one view the contents of a queue? You are over thinking the whole thing :-) Especially note that the Queue is intended to be used in threaded programming (multi-producer, multi-consumer) which the doc clearly states. > I'd like to verify that the queue has the same number of objects > as the list that has been put into it. There is a qsize() method clearly documented. What is wrong with that? > Also, should one think of a queue as static or dynamic (on the put > side)? The constructor documentation clearly describes how it behaves. You can limit the number of items in the Queue at which point new puts will block, or you can have the default behaviour which allows unlimited items in the queue. > Do you put stuff in it once and then get from it until it's empty > or do you put stuff in it a bit at a time? You put items into the Queue and get items out. Each item is an object of any type. The Queue does not split up items. For example if you place a string into the queue, you cannot retrieve just part of the string first and another part later. You only get the whole string out. > Also, > does the queue actually get smaller as the threads feed from it or does > it stay the same size and remember what stuff has been gotten from it > already? It is a classic queue in the computer science sense. Objects can be added (via the put method) and taken off (by the get method). The size is the number of objects in the queue. The order is FIFO (first in first out). Contrast with a stack which is LIFO (last in is the first out). The "staying the same size" part of your comment usually refers to another data type known as a circular buffer (or circular queue). I would strongly recommend getting a copy of the Python Cookbook and reading it. The contents are also available online but the dead tree version is a better read. > Is this an appropriate way to create a queue of 100,000 items? > > url_queue = Queue.Queue(0) > for url in urls: > url_queue.put(url) Yes. However in most code you are unlikely to do that. In general you will have some code producing items, and other code consuming them. Another thread in this group had an example. One piece of code was producing IP addresses to scan, and a seperate piece of code (for example a worker thread) would take one work item and do the scanning. Consequently the number of items would be small since you would expect the rate at which items are produced to be a similar order of magnitude to the rate at which they are consumed. > I ask all of these questions because I find the Python documentation > lacking, to say the least. The documentation for this class is actually short and sweet and I don't think it could be improved. How would you improve it? It is however missing an example which would make things a lot clearer especially for people who aren't used to standard programming idioms. The tutorial is a little brief but does cover data structures: http://docs.python.org/tut/tut.html > PHP especially. Pretty much anyone who has done PHP in anger raves about their docs (me included). Not only is the meta-data really good (eg which version the item was introduced in etc), but the user contributions are what makes the big difference. Also as far as I can tell, every single page includes an example. There was a discussion here about doing the Python docs in a similar fashion (especially the user annotations) a few weeks ago. As far as I could tell, the results were that anyone who wanted to submit changes had to do it via SourceForge bugs and wait a fair while (months) for the changes to appear, or construct a wiki that is seperate from the docs. > Python should be ashamed of its module documentation The documentation is fine. It is pretty standard for docs constructed "cathedral" style. I do wish it was more bazaar style like the PHP ones, but I don't have the time or inclination to help put the infrastructure in place. Do you? Roger From __peter__ at web.de Tue Jun 8 03:03:33 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 09:03:33 +0200 Subject: Passing parameters using **kargs References: Message-ID: Thomas Philips wrote: > I want to access parameters that are passed into a function using the > **kargs idiom. I define f(**kargs) via > > def f(**kargs): > print kargs > . > . > > the keyword arguments are converted to a dictionary, so that if I type > f(a=1, b=2, c=3) > > the function prints > {'a': 1, 'b': 2, 'c':3} > > Now assume the function has three variables a, b and c to which I want > to assign the dictionary's values of 'a', 'b' and 'c'. How can I > assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I > be trying to construct a string representation of each variable's name > and using that as a key, or am I just thinking about this the wrong > way? How about >>> def f(a=None, b=None, c=None, **moreargs): ... print locals() ... >>> f(x=22, b=99) {'moreargs': {'x': 22}, 'a': None, 'c': None, 'b': 99} >>> Peter From corey.coughlin at attbi.com Wed Jun 30 14:55:37 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 30 Jun 2004 11:55:37 -0700 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: Actually, the last time somebody propsed writing a python based OS, I had pretty much the same idea. The idea you have currently looks good for a pure text environment, but you may want to think about what enhancements would look like as people add things like GUIs in the mix and see how that works. I suppose it could wind up looking something like a Naked Object framework, but it could go a lot of different ways. But in general, putting together an interactive object based interface will probably lead you down the OS optimization path. As main memory gets cluttered with objects, you'll want to swap some back to disk, so you'll need some kind of virtual memory system, and some way to store those objects on disk, which implies an object file system, and once you start screwing with file systems, you may as well get right into the OS level. And that sounds like a vaguely good idea, although the top down approach seems like a different way of doing it, start with a basic linux kernel, then start modifying what you need to, rewriting parts in python as needed, until you get down to a core and the python object space. But to take another tack, you may also want to think about the user experience. Generally, if the system works on a text level, you'll definitely want to bring it into a gui framework, and when people see a gui, they'll want to start doing all the things they can do on other systems, like creating documents, spreadsheets, databases, listening to mp3s, looking at pictures and movies, and so on. So you may want to start thinking about more complicated standard types above list and dict, like Picture, Document, Sound, Table, and so on. Then make sure that creating these basic objects is fairly easy, then think about how scripting data flow in and around these objects can be done, object casting (for instance, casting a picture to a document would seem to require an OCR engine) and so on, and then you can begin to see how a whole framework could work, and act somewhat as expected in a normal setting. Of course, this has certain implications, for a system like this to interoperate with other normal file based systems, you'll need automatic conversion of incoming and outgoing files into your base object types, so it would probably help to pick current standards as the basis for your object models (like jpeg for pictures and so on) so that they can easily be cast as files to the outside world. So I wouldn't go too crazy coloring outside the lines with this. But it could be a great thing. And yes, I have thought about this before. Ville Vainio wrote in message news:... > >>>>> "mjt" == mjt writes: > > mjt> Ville Vainio wrote: > >> Pythonic Nirvana - towards a true Object Oriented Environment > > mjt> ... with every new language/scripting language, we are > mjt> supposed to discover nirvana > > Nirvana is not discovered - Nirvana just is ;-). > > The point was not liberation-through-Python, it was > liberation-through-interactive-integration-at-deeper-level. From lbates at swamisoft.com Wed Jun 23 10:38:42 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 23 Jun 2004 09:38:42 -0500 Subject: Testing for membership speed References: Message-ID: The dictionaries are faster because they are indexed. Lists/tuples must be searched serially from the beginning. Dictionary indexes are hashed and the hashing algorithm has more to do on a string than on an integer (see first article link below for explanation). You could check into pre-hashing your strings and using these as integer keys. It will take longer to build the dictionary, but searching should be faster. Here are some articles that might interest you: http://effbot.org/zone/python-hash.htm http://mail.python.org/pipermail/python-dev/2003-June/036556.html http://www.egenix.com/files/python/mxTextTools.html Searching list or tuple serially from the beginning should take approximately the same time. Nothing about the mutability can help the search speed. HTH, Larry Bates Syscon, Inc. wrote in message news:mailman.42.1087998564.27577.python-list at python.org... > I just ran this stuff for my own knowledge. Though it might be > useful to some other people to know and maybe spark a discussion. > > I needed a fast way to test for membership, so naturally the > choices were the builtin containers: lists, dictionaries, and > tuples. The following is the test code and results: > > import timeit > > lst_i=timeit.Timer('random.randrange(10000) in l','import > random; l=range(10000)') > dct_i=timeit.Timer('l.has_key(random.randrange(10000))','import > random; l=dict([(i,None) for i in xrange(10000)])') > tup_i=timeit.Timer('random.randrange(10000) in l','import > random; l=tuple(range(10000))') > > lst_str=timeit.Timer('md5.md5(str(random.randrange(10000))).hexdigest() > in l','import random,md5; l=[md5.md5(str(i)).hexdigest() for i > in xrange(10000)]') > dct_str=timeit.Timer('l.has_key(md5.md5(str(random.randrange(10000))).hexdig est())','import > random,md5; l=dict([(md5.md5(str(i)).hexdigest(),None) for i > in xrange(10000)])') > tup_str=timeit.Timer('md5.md5(str(random.randrange(10000))).hexdigest() > in l','import random,md5; l=tuple([md5.md5(str(i)).hexdigest() > for i in xrange(10000)])') > > print 'Integer lookup' > r=lst_i.repeat(100,100); print 'list:',min(r),max(r); > r=dct_i.repeat(100,100); print 'dict:',min(r),max(r); > r=tup_i.repeat(100,100); print 'tupl:',min(r),max(r); > print 'String lookup' > r=lst_str.repeat(100,100); print 'list:',min(r),max(r); > r=dct_str.repeat(100,100); print 'dict:',min(r),max(r); > r=tup_str.repeat(100,100); print 'tupl:',min(r),max(r); > > [[[Ran on IRIX64 6.5, 24 processors, 12G Memory, 4G Swap, this > code only uses one processor at %100 the full length of the run]]] > Python 2.2.3 (#1, Nov 25 2003, 18:58:21) [C] on irix646-n32 > Type "help", "copyright", "credits" or "license" for more > information. > >>> ## working on region in file > /usr/tmp/python-119959673PMu.py... > Integer lookup > list: 0.126830816269 0.160212993622 > dict: 0.00362300872803 0.00385618209839 > tupl: 0.119297981262 0.161748170853 > String lookup > list: 0.142526865005 0.188524961472 > dict: 0.00711393356323 0.00760197639465 > tupl: 0.143892049789 0.186873912811 > >>> > > The results are conclusive, go for dictionaries. But this > surprised me a little, anyone have insight as to why? > > I was also surprised that tuples and lists scored exactly the > same. I was hoping that immutable tuples might earn it some > speed over lists. > > I will eventually need this for testing strings. So the > doubling of speed for strings over integers for dictionaries > is a little alarming. Lists and tuples only saw a modest increase. > > Thank you in advance for any clever tricks you suggest. > > -Brian > From eurleif at ecritters.biz Thu Jun 17 19:00:16 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 17 Jun 2004 19:00:16 -0400 Subject: How to make an immutable instance In-Reply-To: References: Message-ID: <2jem4iF10udstU1@uni-berlin.de> Batista, Facundo wrote: > So, if you use this "immutable" class in a dict, and then you (on purpose) > modify it, you'll have different hashes. > > Said that, how safer is this approach? Is there a better way? The best I know of is this: class Foo(object): __slots__ = ('x',) # __new__ is used instead of __init__ so that no one can call # __new__ directly and change the value later. def __new__(cls, value): self = object.__new__(cls) self.x = value return self def __setattr__(self, attr, value): if attr in self.__slots__ and not hasattr(self, attr): object.__setattr__(self, attr, value) else: raise AttributeError, "This object is immutable." But note that you can still use object.__setattr__ directly to get around it. I don't think there's a way to get true immutability in pure Python. From eurleif at ecritters.biz Mon Jun 28 12:45:37 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 28 Jun 2004 12:45:37 -0400 Subject: Class Chaos In-Reply-To: References: Message-ID: <2kb09jF3t3eU2@uni-berlin.de> Paul McGuire wrote: > You will also find that you avoid some funny Python behavior if you avoid > using built-in type names (such as list, dict, and str) for variable names. What sort of funny behavior? From james at logicalprogression.net Mon Jun 14 11:53:43 2004 From: james at logicalprogression.net (James Henderson) Date: Mon, 14 Jun 2004 16:53:43 +0100 Subject: [python] mailbox -- Question on usage In-Reply-To: References: Message-ID: <200406141653.43449.james@logicalprogression.net> On Monday 14 June 2004 4:03 pm, David Stockwell wrote: > Hi, > After looking at http://docs.python.org/lib/module-mailbox.html I am a bit > confused. > > The bottom of the page refers to some shortcut usage for getting a mail box > > import email > import mailbox > > mbox = mailbox.UnixMailbox(fp, email.message_from_file) > > My question is what is fp? and how come you don't have to say > email.message_from_file(fileName) on the second parameter? > > Is fp supposed to be something like this? > > myname = 'mymailboxfilename' > fp = open(myname) > > Then > > mbox = mailbox.UnixMailbox(fp, email.message_from_file(myname) ) ???? > > I tried executing the original statement in python (the one from the > website) and it seemed to take it. > > So what does it mean to specify the second parameter like that? > mbox = mailbox.UnixMailbox(fp, email.message_from_file) > > Finally, where can I find a list of all the apis that I can call for > mailbox? > So far I have only found one 'next()' that returns a message object. > > Thanks in advance, > > David >From the top of the page you were looking at: class UnixMailbox(fp[, factory]) Access to a classic Unix-style mailbox, where all messages are contained in a single file and separated by "From "(a.k.a. "From_") lines. The file object fp points to the mailbox file. The optional factory parameter is a callable that should create new message objects. factory is called with one argument, fp by the next() method of the mailbox object. The default is the rfc822.Message class (see the rfc822 module - and the note below). So "fp" is a file object as you rightly surmise, and "email.message_from_file" is acting as the factory function. As it says, the factory can be any function that takes a file object and returns a message object. The public API consists entirely of the next() method and the contructors listed on the page you're looking at. Being iterables you should also be able to use mailbox objects in the many of the same ways that you use other sequences. HTH, James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From gpul-traduccion-bounces at ceu.fi.udc.es Tue Jun 1 15:46:16 2004 From: gpul-traduccion-bounces at ceu.fi.udc.es (gpul-traduccion-bounces at ceu.fi.udc.es) Date: Tue, 01 Jun 2004 21:46:16 +0200 Subject: Your message to gpul-traduccion awaits moderator approval Message-ID: Your mail to 'gpul-traduccion' with the subject hi Is being held until the list moderator can review it for approval. The reason it is being held: SpamAssassin identified this message as possible spam Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://ceu.fi.udc.es/cgi-bin/mailman/confirm/gpul-traduccion/408b3ee063ace2f80a342344c65e10ca06079d10 From km at mrna.tn.nic.in Tue Jun 29 11:20:19 2004 From: km at mrna.tn.nic.in (km) Date: Tue, 29 Jun 2004 20:50:19 +0530 Subject: wxPython woes In-Reply-To: <2kcnmuFm9cgU1@uni-berlin.de> References: <2kcnmuFm9cgU1@uni-berlin.de> Message-ID: <20040629152019.GA29654@mrna.tn.nic.in> Hi all, So does it mean that access will be much faster when PyGTK or PyQT are used instead of wxPython as one can see one layer additionallyunder *nix? regards, KM ------------------------------------------------------------------------------ > The difference is the number of layers on the different platforms: > > Under Un*x: > wxPython --> wxWidgets --> GTK --> Xlib > -- or -- > PyGTK --> GTK --> Xlib > -- or -- > PyQt --> Qt --> Xlib > > Under Windows: > wxPython --> wxWidgets --> Native Windows Controls > -- or -- > PyGTK --> GTK --> Wimp --> Native Windows Controls > > Reinhold > > -- > Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows > mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines > "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. > -- David Kastrup in de.comp.os.unix.linux.misc > -- > http://mail.python.org/mailman/listinfo/python-list -- From davidf at sjsoft.com Fri Jun 25 10:31:54 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 25 Jun 2004 16:31:54 +0200 Subject: python service problem In-Reply-To: References: <6NKdnaDwjYlTQUfdRVn-uA@comcast.com> Message-ID: Peter Hansen wrote: > Larry Bates wrote: > > "David Fraser" wrote: > > > >>One thing I noticed about the first computer is that, even after > >>uninstalling everything, there were some registry entries to do > >>with the installed services. I could not delete these entries - I > >>got an access denied error (details below) > [...] > >> I can tell you that I use InnoInstaller to do my installations >> and have it "clean" up during uninstallation by removing the >> left over registry keys. If you cannot remove them, I would >> suspect a "rights" issue (no administrative rights?). > > > For what it's worth, in a possibly related situation we just > encountered something similar. In our case it was not a service, > but a COM server (using ctypes or win32com, running as LocalServer32 > which launches pythonw.exe in the background). On my machine > I've had no troubles, but on a remote machine there were > "access denied" errors whenever the developer tried to "-unregserver", > which removes the registry entries. I believe he tried removing > them manually as well, but could not. It was a long-distance > thing, so I couldn't troubleshoot it myself... > > I theorized there was a leftover process running, but after > checking over the task list he insisted there was not anything > active that could be doing this. > > A reboot cured the problem, and so far we haven't seen it > again. > > He definitely had administrative rights, so it wasn't that. I'm > positive it was a leftover "lock" of some kind, but I don't > know anything about that area of Windows so we just moved on. > > My point is that it may not even be limited to the service > stuff, but could be a little broader, maybe more fundamental > to doing these kinds of background things using Python > under Windows. > > -Peter Very interesting. This has also occured on one of our customer sites where it was difficult to debug... At least it has also occurred on our own machines so if we manage to work out more details I'll post them here, maybe it will solve your problem to... David From nun at meyl.com Mon Jun 21 13:33:56 2004 From: nun at meyl.com (Mitja) Date: Mon, 21 Jun 2004 19:33:56 +0200 Subject: Game - Map data structures References: <40D39B53.13F679FF@alcyone.com> Message-ID: Innocence (news:b2o8d0t01m8p1n7e20mv1g1ffb2lb6hbta at 4ax.com) wrote: > On 19 Jun 2004 02:43:06 GMT, sholden at flexal.cs.usyd.edu.au (Sam > Holden) wrote: > >> Which imples to me that the water object has an armies list or >> something hanging of it. > > Of course there's an army-list containing all the army objects in the > game, but the plan was to make indexed links to this list from each > tile containing one or more armies. That way, if a player clicks a > tile the game knows which armies exists on that tile. > > If I didn't have such links, I'd have to search through the entire > army list every time a tile is selected. > > I know this makes for redundant data, but it's the only way I could > figure out how to avoid potiential performance issues when selecting > tiles. However, if there's a better way to do this I'd be happy to > know :) If the number of armies is small enough (say 1000, to be on the safe side), don't worry about performance. > > Thanks :) > > 0:) Innocence From lard at tardis.ed.ac.molar.uk Tue Jun 29 10:26:41 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 29 Jun 2004 15:26:41 +0100 Subject: sending of mail (smtp) - connection refused - but smtp server is running! Message-ID: <10e2v1446n95e4b@corp.supernews.com> I am using the smtp module to send emails via a local SMTP server on our network. I am failing with "connection refused" error, even though we definitely have an smtp server running on port 25! the code is like this: me = 'ahunsley at companyname.com' you = 'someonelse at companyname.com' msg['Subject'] = '*** alert' msg['From'] = me msg['To'] = you s = smtplib.SMTP('192.168.1.105') s.connect() s.sendmail(me, [you], msg.as_string()) s.close() print "Email sent." When I run this code, I get: Traceback (most recent call last): File "C:\Python23\check.py", line 58, in -toplevel- s.connect() File "C:\Python23\lib\smtplib.py", line 302, in connect raise socket.error, msg error: (10061, 'Connection refused') here's me verifying that SMTP server is indeed alive at port 25 on my local network: $ telnet 192.168.1.105 25 Trying 192.168.1.105... Connected to 192.168.1.105. Escape character is '^]'. 220 grain.companyname.com ESMTP Server FTGate helo 250 grain.companyname.com any ideas what the problem could be? this usually happens when someone is not aware they have to run an SMTP server, but we do have one running, as can be seen above! thanks alex From mrjean1 at comcast.net Tue Jun 15 18:13:22 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Tue, 15 Jun 2004 22:13:22 GMT Subject: Proper way to kill child processes References: <1774q1-63c.ln1@valpo.de> Message-ID: <150620041524087053%mrjean1@comcast.net> It should be the other way around self.popen = popen2.Popen3(["/usr/local/bin/python", "-O", "myscript.py"]) Item [0] must be the path to the executable and items[1:] are the arguments. See the Popen3._run_cmd() method in Lib/popen2.py partially copied here:

        def _run_child(self, cmd):
            if isinstance(cmd, basestring):
                cmd = ['/bin/sh', '-c', cmd]
            .....
            try:
                os.execvp(cmd[0], cmd)
            finally:
                os._exit(1)
    
    /Jean Brouwers ProphICy Semiconductor, Inc. In article <1774q1-63c.ln1 at valpo.de>, Mathias Waack wrote: > Bob Swerdlow wrote: > > > My application starts up a number of processes for various purposes > > using: > > self.popen = popen2.Popen3("/usr/local/bin/python -O > > "myscript.py") > > This works for me: > > self.popen = popen2.Popen3(["python", "/usr/local/bin/python", > "-O", "myscript.py"]) > > But I don't know if its a hack or a desired feature. > > Mathias From aahz at pythoncraft.com Thu Jun 10 16:53:07 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2004 16:53:07 -0400 Subject: Dicts 5x Faster than Sets References: <889cbba0.0406091124.4c29126e@posting.google.com> Message-ID: In article <889cbba0.0406091124.4c29126e at posting.google.com>, Kamilche wrote: > >Hm, I just saw the 'sets' feature, and ran some timings to see if I >should use it instead of 'dict' sometimes. I discovered it's 4x slower >in adding, and 6x slower in removing items! Speed is not the raison d'etre for sets, convenience and clarity are. You are better off using sets if you need set intersection and union, for example. Keep in mind that dicts are probably the single most highly optimized chunk of code in Python, and that sets are built on top of dicts. Unless you need the absolute utmost in speed, the penalty you're paying for the wrapper code shouldn't be an issue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From lreenaers at hotmail.com Wed Jun 9 13:20:18 2004 From: lreenaers at hotmail.com (Krapul) Date: 9 Jun 2004 10:20:18 -0700 Subject: Zope NewBie loosing hairs on python Message-ID: Hi everybody, I'm using python for long time, now; currently developing a web-based game working with python CGI and IIS. I've heard about various interesting zope functionalities, but I'm facing a problem while simply trying to integrate my python code within zope. Let's depict a bit of example, I could schematise my current apps like this: ***on one side, I have a python module...let's say testa.py, formated like this: class testb: def __init__(self): self.x='hello' def dsp(self): return self.x ***on the second side I have a CGI: import cgi,cgitb import sys import testa sys.stderr = sys.stdout print "HTTP/1.0 200 OK" + chr(13)+chr(10) a=testa.testb() x=a.dsp() print ""+str(x)+" cgitb.enable() ************************************************************************ What I would understand is : "Is there a way to upload my python module to zope and then using it in a dtml page (I guess)instead of CGI?" Please somebody help...I'm completly lost...Thanks in advance, Ludo From lbates at swamisoft.com Wed Jun 23 10:16:43 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 23 Jun 2004 09:16:43 -0500 Subject: parse output screen ok but cant get desired output new file! References: Message-ID: I wrote something a couple of weeks ago that might help. It works with POP3 mailboxes and it handles messages with body text and/or attachments, but you could easily change it. Hope it helps. Larry Bates Syscon, Inc. import poplib import email import email.Parser import os import sys class email_attachment: def __init__(self, messagenum, attachmentnum, filename, contents): ''' arguments: messagenum - message number of this message in the Inbox attachmentnum - attachment number for this attachment filename - filename for this attachment contents - attachment's contents ''' self.messagenum=messagenum self.attachmentnum=attachmentnum self.filename=filename self.contents=contents return def save(self, savepath, savefilename=None): ''' Method to save the contents of an attachment to a file arguments: savepath - path where file is to be saved safefilename - optional name (if None will use filename of attachment ''' savefilename=savefilename or self.filename f=open(os.path.join(savepath, savefilename),"wb") f.write(self.contents) f.close() return class email_msg: def __init__(self, messagenum, contents): self.messagenum=messagenum self.contents=contents self.attachments_index=0 # Index of attachments for next method self.ATTACHMENTS=[] # List of attachment objects self.msglines='\n'.join(contents[1]) # # See if I can parse the message lines with email.Parser # self.msg=email.Parser.Parser().parsestr(self.msglines) if self.msg.is_multipart(): attachmentnum=0 for part in self.msg.walk(): # multipart/* are just containers mptype=part.get_content_maintype() filename = part.get_filename() if mptype == "multipart": continue if filename: # Attached object with filename attachmentnum+=1 self.ATTACHMENTS.append(email_attachment(messagenum, attachmentnum, filename, part.get_payload(decode=1))) print "Attachment filename=%s" % filename else: # Must be body portion of multipart self.body=part.get_payload() else: # Not multipart, only body portion exists self.body=self.msg.get_payload() return def get(self, key): try: return self.msg.get(key) except: emsg="email_msg-Unable to get email key=%s information" % key print emsg sys.exit(emsg) def has_attachments(self): return (len(self.ATTACHMENTS) > 0) def __iter__(self): return self def next(self): # # Try to get the next attachment # try: ATTACHMENT=self.ATTACHMENTS[self.attachments_index] except: self.attachments_index=0 raise StopIteration # # Increment the index pointer for the next call # self.attachments_index+=1 return ATTACHMENT class pop3_inbox: def __init__(self, server, userid, password): self._trace=0 if self._trace: print "pop3_inbox.__init__-Entering" self.result=0 # Result of server communication self.MESSAGES=[] # List for storing message objects self.messages_index=0 # Index of message for next method # # See if I can connect using information provided # try: if self._trace: print "pop3_inbox.__init__-Calling poplib.POP3(server)" self.connection=poplib.POP3(server) if self._trace: print "pop3_inbox.__init__-Calling connection.user(userid)" self.connection.user(userid) if self._trace: print "pop3_inbox.__init__-Calling connection.pass_(password)" self.connection.pass_(password) except: if self._trace: print "pop3_inbox.__init__-Login failure, closing connection" self.result=1 self.connection.quit() # # Get count of messages and size of mailbox # if self._trace: print "pop3_inbox.__init__-Calling connection.stat()" self.msgcount, self.size=self.connection.stat() # # Loop over all the messages processing each one in turn # for msgnum in range(1, self.msgcount+1): self.MESSAGES.append(email_msg(msgnum, self.connection.retr(msgnum))) if self._trace: print "pop3_inbox.__init__-Leaving" return def close(self): self.connection.quit() return def remove(self, msgnumorlist): if isinstance(msgnumorlist, int): self.connection.dele(msgnumorlist) elif isinstance(msgnumorlist, (list, tuple)): map(self.connection.dele, msgnumorlist) else: emsg="pop3_inbox.remove-msgnumorlist must be type int, list, or tuple, not %s" % type(msgnumorlist) print emsg sys.exit(emsg) self.msgcount-=1 return def __len__(self): return self.msgcount def __iter__(self): return self def next(self): # # Try to get the next attachment # try: MESSAGE=self.MESSAGES[self.messages_index] except: self.messages_index=0 raise StopIteration # # Increment the index pointer for the next call # self.messages_index+=1 return MESSAGE if __name__=="__main__": server="www.domain.com" # set server here userid="userid" # set userid here password="password" # set password here inbox=pop3_inbox(server, userid, password) if inbox.result: emsg="Failure connecting to pop3_inbox" print emsg sys.exit(emsg) print "Message count=%i, Inbox size=%i" % (inbox.msgcount, inbox.size) counter=0 for m in inbox: counter+=1 print "Subject: %s" % m.get('subject') print "-------------Message (%i) body lines---------------" % counter print m.body print "-------------End message (%i) body lines-----------" % counter if m.has_attachments(): acounter=0 for a in m: acounter+=1 print "-------------Message (%i) attachments-------------" % counter print "%i: %s" % (acounter, a.filename) print "-------------End message (%i) attachments---------" % counter a.save(r"C:\temp") else: print "-------------Message has no attachments----------" # # See if I can delete all messages # #if inbox.msgcount: inbox.remove(range(1, inbox.msgcount+1)) inbox.close() "chuck amadi" wrote in message news:mailman.32.1087971963.27577.python-list at python.org... > By the way list is there a better way than using the readlines() to > > > >parse the mail data into a file , because Im using > > > >email.message_from_file it returns > > > >all the data i.e reads one entire line from the file , headers as > well > > > >as just the desired body messages . > > > > > > > >fp = file("/home/chuck/pythonScript/testbox") > > > >mb = mailbox.UnixMailbox(fp, > > > >email.message_from_file) > > > > > > > > > > > >mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") > > > >for mail in fp.readlines(): > > > > mailout.write(mail) > > > > > > > >Something like this> > > > > > > > >for mail in mb: > > > > body = mail.get_payload() > > > > mailout.write(body) # write only the body messages to > SurveyResults.txt > > > > > > > >Cheers if the is a better way I can't get my head round how I can > print > > > >mail ( > > > >only the body messages) to screen and the entire mail headers and > body > > > >to the new file. > > > > > > > >Hi have any one got any suggstions to my script I can parse the > email > > > >body messages to screen but I want the same desired effect to save > to a > > > >new file.I have tried a few things to no effect. > > > . > > > . > > > . > > > There's a lot going on in your message. I *think* what you want > > > is the suggestion to replace > > > for mail in fp.readlines(): > > > mailout.write(mail) > > > with > > > mailout.write(fp.read()) > > > -- > > > > > > > > > Hi again where I print mail.get_payload() > > I want to write this to the file. Bu uisng readlinds() function I > > obviously get the entire contents including the headers thus I want to > > do something like this > > > for bdymsg in mb: > > bdymsg = mail.get_payload() > > print mail.get_payload()# prints body msg's to screen > > mailout.write(bdymsg) > > # mailout.write(mail.get_payload()) # Something along these lines. > > mailout.close() > > > > > > From gen2n at seznam.cz Wed Jun 16 00:58:37 2004 From: gen2n at seznam.cz (p.kosina) Date: Wed, 16 Jun 2004 06:58:37 +0200 Subject: bindings in Tkinter In-Reply-To: References: Message-ID: Solved.- I must have old documentation, I used 'n'. Thank you. Pavel Jeff Epler napsal(a): > The following program just fine for me, printing "Control-N" > multiple times without the need to release and re-press control each > time: > from Tkinter import Tk > t = Tk() > def puts(s): print s > t.bind("", lambda e: puts("Control")) > t.bind("", lambda e: puts("Control")) > t.bind("", lambda e: puts("Released Control")) > t.bind("", lambda e: puts("Released Control")) > t.bind("", lambda e: puts("Control-N")) > t.mainloop() > > Your problem must be because you've done something more complicated than > you've told us. For instance, if your binding for creates > or destroys widgets, moves the input focus, etc., maybe something bad is > happening. > > Jeff From duncan-news at grisby.org Wed Jun 30 10:43:06 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 30 Jun 2004 16:43:06 +0200 Subject: Listing functions in a file IN ORDER References: Message-ID: <3d166$40e2d17a$51604868$9218@nf1.news-service-com> In article , Ian Sparks wrote: >I have a python file with a number of functions named with the form doX so : > >doTask1 >doThing >doOther > >The order these are executed in is important and I want them to be >executed top-down. They all have the same parameter signature so I'd >like to do : All you need to do is sort them by line number: from types import FunctionType def linecompare(a,b): return cmp(a.func_code.co_firstlineno, b.func_code.co_firstlineno) func_list = [ f for (n,f) in vars(mymodule).items() if isinstance(f, FunctionType) and n.startswith("do") ] func_list.sort(linecompare) Notice that I looked just for functions since other callables like classes don't have the right attributes. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From pwatson at redlinepy.com Thu Jun 24 09:47:28 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 24 Jun 2004 08:47:28 -0500 Subject: Writing binary to stdout References: <2jrglkF153jroU1@uni-berlin.de> <2jsm1iF7ott5U4@uni-berlin.de> <2jubemF14b1jjU1@uni-berlin.de> <10dk8nbr1m51k04@corp.supernews.com> Message-ID: <2k04bjF15kggbU1@uni-berlin.de> "Chris King" wrote in message news:10dk8nbr1m51k04 at corp.supernews.com... > Paul Watson wrote: > > Even when I try to use low-level I/O it does CRLF interpretation. What am I > > doing wrong? > > Are you using Cygwin? It will automatically CRLFify anything it thinks > should be (I'm not sure what the exact critera are); this has bit me > before, too. There's an option to disable it in Cygwin setup. This is > being passed on to the script because the stdout redirections are done > in Cygwin, not in Python. The following appears to work under 2.1 in Cygwin and 2.3.4 under a DOS box. I did not change any Cygwin setting. Is there anything undesireable in the code below? The intent is to say if this is running on Windows, set stdout to binary mode. Am I safe in assuming that 'import msvcrt' will fail on all other machines? Is there a better way? $ cat ./wb.py #! /usr/bin/env python import sys import os try: import msvcrt msvcrt.setmode(1, os.O_BINARY) except: pass sys.stdout.write("now\n") print "and then" $ ./wb.py >jjj $ od -c jjj 000000 6e 6f 77 0a 61 6e 64 20 74 68 65 6e 0a n o w \n a n d t h e n \n 00000d From klappnase at web.de Thu Jun 24 18:08:55 2004 From: klappnase at web.de (klappnase) Date: 24 Jun 2004 15:08:55 -0700 Subject: Python and MP3 References: Message-ID: Rod Stephenson wrote in message news:... (...) > It might be worth mentioning the snack sound library for Tcl, > (though the orginator of this thread is after something for > wxPython) > > http://www.speech.kth.se/snack/index.html > > (...) > > from Tkinter import * > root=Tk() > > snackScript = '''package require -exact sound 2.2; > snack::sound s -file "chaconne.mp3"; > s play -block 1 > ''' > > root.tk.eval(snackScript) > > It's even easier, because snack comes with a python wrapper included: from Tkinter import * import tkSnack root=Tk() root.withdraw()#in case you don't want to see a Tk window in your app tkSnack.initializeSnack() s=tkSnack.Sound(file="chaconne.mp3") s.play() Michael From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 10 10:39:52 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 10 Jun 2004 16:39:52 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B74201634F2F@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = sebastien.chaumat at ens-lyon.fr Recipient(s) = python-list at python.org; Subject = great xxx! Scanning time = 06/10/2004 16:39:52 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment yours.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From martin at v.loewis.de Sun Jun 27 17:22:41 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 27 Jun 2004 23:22:41 +0200 Subject: Can you make this faster? In-Reply-To: <889cbba0.0406271022.fd1f9ac@posting.google.com> References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <40DF3AA1.4000100@v.loewis.de> Kamilche wrote: > I have a routine that I really need, but it slows down processing > significantly. Can you spot any ineffeciencies in the code? I would use a dictionary, and I would pre-allocate the result list: _code = {types.StringType: 's', types.IntType: 'i', types.LongType: 'q', types.BooleanType: 'c', types.FloatType: 'd' } def fmtstring(args): fmt = ['\0']*(len(args)+1) fmt.append('<') for i, arg in enumerate(args): t = type(arg) try: c = _code[t] except KeyError: raise Exception("Can't pack argument of type %s!" % t) if c == 's': fmt[i] = str(len(arg))+'s' else: fmt[i] = c return ''.join(fmt) Regards, Martin From qrczak at knm.org.pl Wed Jun 16 05:20:15 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Wed, 16 Jun 2004 11:20:15 +0200 Subject: mutable default parameter problem [Prothon] References: Message-ID: On Tue, 15 Jun 2004 22:01:19 -0800, Troy Melhase wrote: > $ find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} \; | wc > > And see 67 instances just in the standard library. I don't know how you counted them: [qrczak ~/src/python/Python-2.3.4]$ egrep 'def.*= ?\[\]' **/*.py | wc -l 45 [qrczak ~/src/python/Python-2.3.4]$ egrep 'def.*= ?None' **/*.py | wc -l 1420 Now consider that many of the Nones are a workaround for the current Python behavior. I agree that it's probably impractical to change Python rules because some code relies on the current behavior. OTOH evaluating the default argument each time when the function is applied is technically better. This is one of warts which is hard to fix because of compatibility. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From hungjunglu at yahoo.com Thu Jun 3 20:03:04 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 Jun 2004 17:03:04 -0700 Subject: Why did no one invent Python before? References: Message-ID: <8ef9bea6.0406031603.3ca464dd@posting.google.com> Matthew Thorley wrote: > Hear Hear !!! I'll second that. Programming in pythong is fun. Pythong? PythonG? Sure, if you speak Spanish, then bienvenido a probar el siguiente entorno fabuloso del pit?n gr?fico: http://www3.uji.es/~dllorens/PythonG/ Or if you use it as a fashion statement: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=FOidnSvClJ3UvDfdRVn-sw%40powergate.ca regards, Hung Jung From richie at entrian.com Wed Jun 30 03:43:03 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 30 Jun 2004 08:43:03 +0100 Subject: How important is Python 1.5 compatibility? In-Reply-To: <40E092A9.43C2CDDF@alcyone.com> References: <40E092A9.43C2CDDF@alcyone.com> Message-ID: <6fr4e0h5senhjgm42dggrgqusvvr7saqo7@4ax.com> [Erik] > How important do people think Python 1.5 compatibility is? We still have 1.5.2-based systems in production use, for various reasons. One is "if it ain't broke, don't fix it." Another is that some are on obscure platforms and getting Python to build there was some effort, which we don't want to gratuitously spend again. Another (as Christopher pointed out) is that some ISPs are still running 1.5.2. -- Richie Hindle richie at entrian.com From mrmakent at cox.net Fri Jun 11 09:50:03 2004 From: mrmakent at cox.net (Michael Kent) Date: 11 Jun 2004 06:50:03 -0700 Subject: Q: Making Python use no shared extension modules? References: <30260531.0406101310.65489ea7@posting.google.com> Message-ID: simoninusa2001 at yahoo.co.uk (simo) wrote in message news:<30260531.0406101310.65489ea7 at posting.google.com>... > I don't think you can do it. > > The closest you'd get is McMillan Installer's --onefile which > basically zips up all the modules into one file, which decompressed on > the fly when run, although when I've tried it on clean Linux boxes, it > still requires non-Python stuff (like a wxPython app still requires > wxTGK installed). Thanks for the reponse, but let's make sure we are talking about the right problem. I know that I can put '*static*' in Modules/Setup, which will cause all of the extension modules build via the Setup mechanism to be staticly-linked to the Python executable. That's what I'm after, but it requires me to specifically turn-on each extension module that I want staticly-linked. What I'm really after is some sort of configure option that says "universally build all extension modules so that they will be staticly-linked into the Python executable, build NO shared libraries". You would think such an option exists. You would think it was '--disable-shared'. But this does not seem to be the case. From brian at sweetapp.com Wed Jun 2 11:56:12 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 02 Jun 2004 17:56:12 +0200 Subject: How to demonstrate bigO cost of algorithms? In-Reply-To: References: Message-ID: <40BDF89C.9080901@sweetapp.com> Rusty Shackleford wrote: > Hi - > > I'm studying algorithms and I want to write a python program that > calculates the actual runtimes. > > I want to increment up some global variable called n in my program so > that I can see the relationship between the size of the problem and the > number of steps. > > Here's my clumsy attempt to implement this: > > [snipped] What is that ugly try-except block for? All it seems to do is hide potential errors. Anyway, if you are only testing comparison-base sorting algorithms then why not create a new class (maybe by subclassing a builtin) and implement a __cmp__ method that increments a global whenever called. That way you will get an exact count of the number of comparisons. Cheers, Brian From balaji at email.arizona.edu Mon Jun 14 14:37:42 2004 From: balaji at email.arizona.edu (Balaji) Date: 14 Jun 2004 11:37:42 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> Message-ID: <494182a9.0406141037.418dd6a4@posting.google.com> Hello Everybody... Let me try to explain what do I mean by "ordering importance". In our application a expression 100>=x reads as 100 is an upper bound on x. Mathematically it is same as saying x<=100 which also bounds x by 100. But in modelling, the user wants to preserve the order in which he has written the expression. If the left side of an operand is an immutable type then this ordering is no longer preserved, even if both the methods are implemented(i.e __le__ and __ge__). __radd__ allows you to have an immutable type on the left side. An __rge__ method would provide the same functionality for relational operators. Is there a way to obtain this behavior with current syntax? Regards Balaji From a at a.a Tue Jun 29 16:50:19 2004 From: a at a.a (mutah) Date: Tue, 29 Jun 2004 20:50:19 +0000 Subject: creating graphs from lists In-Reply-To: References: Message-ID: Luis P. Mendes wrote: > I'm developing a program in Python, with no gui, and now I've reached a > point where I would need to plot list of elements on a graph. > > How can I do it? preferably in a simple way? > > > Luis Depending on how sexy must look your graph, have a look on gnuplot and his pythonixc interface gnuplot-py, http://gnuplot-py.sourceforge.net/, it may fits your requirements Mutah From Scott.Daniels at Acm.Org Wed Jun 23 12:45:33 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 23 Jun 2004 09:45:33 -0700 Subject: python-list to news gateway down? In-Reply-To: References: Message-ID: <40d9b8b2$1@nntp0.pdx.net> Brad Clements wrote: > I have not seen any new posts in gmane.comp.python.general since 6/18/2004. > > However when I post to gmane, that post seems to make it out to the python > list. > > Does anyone know if its a gmane problem, or a general news to python-list > problem? > > > If you go to , you will discover they are having mail problems and will be switching mail servers. I'd not expect it to be solved real soon; try again next week or so? -- -Scott David Daniels Scott.Daniels at Acm.Org From mab at iee.lu Tue Jun 8 07:25:01 2004 From: mab at iee.lu (Marco Bartel) Date: Tue, 08 Jun 2004 13:25:01 +0200 Subject: ideas Python / Network Admin In-Reply-To: References: Message-ID: <40c5a25d$1@news.vo.lu> Norm wrote: > I was wondering if you would give me some examples (not code, but general > ideas) of what you are using Python for in Network Administration / Security > ? > > Thanks > Norm > > Hello Norm, we use python in many places of our company, here only a few examples: production monitoring ( counting pieces, runtimes of machines, collecting temperature and humidity informations, general automation stuff, printing inline barcodes.... ) userinterfaces for different database applications monitoring of our harddisks in the servers monitoring of hard/software raid-devices in the servers many scripts for our mailscanners the mailproxies are written in python our knowledge-database / content-management-system is written in python the flextime of the employees are managed by python programms including the hardware stuff (badge readers). user-management-software ( creating unix,ldap,nis,mail and some specific account for new user, editing them...) and of course a lot of helping scripts for the daily work. I think there is a lot of power hidden in this little interpreter, and there is more possible, as we are currently using. CU Marco From simonroses at granisla.com Thu Jun 17 06:49:43 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Thu, 17 Jun 2004 12:49:43 +0200 Subject: Something simular to java's hsqldb for python?? References: <792ea523.0406160601.1b217d78@posting.google.com> Message-ID: <006b01c45458$cd7293f0$0200a8c0@lucifer> I did ask the same question last week and here are the answer I did get! Pysqlite : http://pysqlite.sourceforge.net/ Metakit: http://www.equi4.com/metakit/python.html Hope this help. Sincerely, SRF ----- Original Message ----- From: "pet100us" Newsgroups: comp.lang.python To: Sent: Wednesday, June 16, 2004 4:01 PM Subject: Something simular to java's hsqldb for python?? > Hi, > > Is there some program that is simular to java's hsqldb > (http://hsqldb.sourceforge.net/). It is a relational database that can > easily be used within a small java program without installing a MySQL, > Postgresql etc. It is used within the same virtual machine whitout > installing anything extra. > > Is there somthing similar for python? I need a small database that I > can build into my application. When the program starts the database > should start and when the programm exits the database can stop. I know > that the samething could be done with xml files or binary files. The > database has some advantages. e.g. when I want to change the program > that it uses a "real" database I dont need to replace much of the > code. I just change the database driver an off we go. (the programmers > dream) > > Thanks in advance > pet100us > -- > http://mail.python.org/mailman/listinfo/python-list From FBatista at uniFON.com.ar Wed Jun 16 13:18:47 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 16 Jun 2004 14:18:47 -0300 Subject: ANNOUNCE: SiGeFi v0.1 Message-ID: We're proud to announce the 0.1 version of SiGeFi, which you can find at: http://sourceforge.net/projects/sigefi What is SiGeFi? --------------- SiGeFi is a Financial Management System, with focus in the needs of the administration of the money in each personal life and house. Always keeping the easy usage and concepts, SiGeFi has features of a complex Management system: - Complies with Double Entry Accounting - Has a Budget-based Money Distribution system - Allow to make Loans between accounts (with associated financial costs) And of course, it's completely written in Python (didn't decided the GUI yet). What is in this version? ------------------------ We finished all the test cases, which mainly sets the system interface. Be aware that the documentation is not translated yet, it's only in spanish. What can I expect for the next version? --------------------------------------- To us to finish writing and fixing the code itself to comply with the test cases. We'll also update all the documentation: the actual one is not an exact reflex of the test cases. How can I help? --------------- In a thousand ways, there's a lot of things to do: documentation, fixing code, set up the web page, etc... If you want to participate, send us a mail! (we did not configure the mail list yet, :) Thank you. . Facundo From peter at engcorp.com Fri Jun 11 07:06:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 07:06:38 -0400 Subject: Anonymous file closing In-Reply-To: References: Message-ID: <35udnZ0dL4DcD1TdRVn-ug@powergate.ca> Sergey Krushinsky wrote: > If I need to read a string from a file and use syntax like: > text = open(filename, 'r').read() > ... > is the file object ever closed? Duncan's response says it all, but here's the solution if you don't like the uncertainty inherent in the above: f = open(filename, 'r') try: text = f.read() finally: f.close() That will ensure that the file is properly closed under all versions of Python, all platforms... For small scripts, I do what you did above. For anything larger I take the more explicit approach. -Peter From gandalf at geochemsource.com Fri Jun 11 07:46:14 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 11 Jun 2004 13:46:14 +0200 Subject: split In-Reply-To: <20040612151044.GA9619@mrna.tn.nic.in> References: <20040612151044.GA9619@mrna.tn.nic.in> Message-ID: <40C99B86.8060201@geochemsource.com> This way: >>> s = 'some string' >>> l = [] >>> for c in s: ... l.append(c) ... >>> l ['s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'] >>> However, in most cases, you do not need this. Please note that strings are seuqences. You can do these: s[2] s[1:3] s[-4] e.g. almost anything that you could do with a list. Best, G km wrote: > hi all, >i have a string like this >s = "znfciuheiahkcjnksdhuicvh" >how to cut it into individual characrers and create an array out of it ? >i tried s.split() >but it doesnt work >regards, >KM > > > > > From NOmanlio_perilloSPAM at libero.it Wed Jun 23 09:56:32 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 23 Jun 2004 13:56:32 GMT Subject: [PEP] auto keyword for automatic objects support in Python References: Message-ID: On Tue, 22 Jun 2004 12:16:05 +0300, Christos "TZOTZIOY" Georgiou wrote: >On Fri, 18 Jun 2004 16:32:39 GMT, rumours say that Manlio Perillo > might have written: > >[snip] > > >[snip] > >I'm afraid your PEP's strongest adversary will be the "Explicit is >better than implicit". You suggest complications to the language >implementation that can be avoided just by user code. > >For example, you could have a class Deallocator (untested improvised >code): > >class Deallocator: > def __init__(self, *args): > self.args = args > def deallocate(self): > for obj in self.args: > obj.__deinit__() > >then in your function start: > auto = Deallocator(obj1, obj2 ...) > >and in your function end: > auto.deallocate() > >If your function has multiple exit points, wrap its code in a try ... >finally sequence. > > The problem is that one have to use finally consistently. The C++ RAII pattern is more simple. Thanks and regards Manlio Perillo From xavim at fqingenieria.es Mon Jun 7 07:53:10 2004 From: xavim at fqingenieria.es (=?ISO-8859-1?Q?Xavier_Mart=EDnez?=) Date: Mon, 07 Jun 2004 13:53:10 +0200 Subject: heredoc and variables In-Reply-To: <10c30h24e15dh14@corp.supernews.com> References: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> <10c161nfembfq14@corp.supernews.com> <10c30h24e15dh14@corp.supernews.com> Message-ID: <40C45726.2080709@fqingenieria.es> Michael Geary wrote: > Now that I think of it, if you do want to get rid of both newlines, > here are > a couple of other ways to do it: > > end_html = """\ > > \ > """ > > That is a bit ugly, but this seems reasonable (and better than the [1:-1] > slice trick): > > end_html = """\ > > """ > > -Mike > > Just for completeness, you can also use lstrip(), rstrip() and strip() string methods to remove whitespace at the beggining, end or both parts of a string, respectively. I.e.: end_html = """ """.lstrip() will get rid of the beginning newline. Using strip(), will get rid of both. I still prefer Mike's backslash solution, as getting rid of the newline is done at parse time rather than at run time. Also lstrip() will eat too much space if the first line of the string (" From vng1 at mac.com Wed Jun 23 07:41:55 2004 From: vng1 at mac.com (Victor Ng) Date: 23 Jun 2004 04:41:55 -0700 Subject: Learning Pyrex with libxml2 Message-ID: <5a2ed384.0406230341.71efe67e@posting.google.com> Hi, I'm trying to learn how to use Pyrex by converting some of the libxml2 examples. I'm not having much luck - I can create a document, but any attempt to create nodes causes a segfault. The code I'm trying to port is io2.c (http://xmlsoft.org/examples/io2.c) I've commented the couple lines that cause a problem for me. thanks, vic ---- cdef extern from "libxml/tree.h": ctypedef xmlDocPtr ctypedef xmlNodePtr ctypedef xmlNsPtr xmlDocPtr xmlNewDoc(unsigned char *) xmlNodePtr xmlNewNode (xmlNsPtr, unsigned char *) void xmlNodeSetContent (xmlNodePtr, unsigned char *) xmlNodePtr xmlDocSetRootElement (xmlDocPtr, xmlNodePtr ) void xmlDocDumpFormatMemory (xmlDocPtr, unsigned char **, int *, int ) xmlNodePtr xmlNewChild (xmlNodePtr, xmlNsPtr, unsigned char *, unsigned char *) void xmlFreeDoc (xmlDocPtr) void xmlFree (xmlDocPtr) def testNewDoc(): cdef xmlNodePtr n cdef xmlDocPtr doc cdef unsigned char* xmlbuff cdef int buffersize doc = xmlNewDoc( "1.0") ## The following three lines cause a segfault # n = xmlNewNode(None, "root") # xmlNodeSetContent(n, "content") # xmlDocSetRootElement(doc, n) xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1) xmlFrag = xmlbuff print "%d bytes in string" % len(xmlFrag) print "[%s]" % xmlFrag vic From ajw140NO at SPAMyork.ac.uk Tue Jun 8 11:52:24 2004 From: ajw140NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Tue, 08 Jun 2004 16:52:24 +0100 Subject: Citing Python Message-ID: Hi, Has anyone out there cited Python in a paper, if so how did you do it? Is there a published paper by Guido van Rossum (or someone similarly important to the project) that is suitable for this? Currently I'm just citing http://www.python.org, but I'm not too happy with that. Thanks in advance, Andrew Wilkinson From peter at engcorp.com Mon Jun 14 10:35:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 10:35:21 -0400 Subject: setattr using invalid attribute names - bug or feature? In-Reply-To: <40cdb3d5.2146906@news.t-online.de> References: <40cdb3d5.2146906@news.t-online.de> Message-ID: <1oadnWVlX580KlDdRVn-ug@powergate.ca> Gerson Kurz wrote: > I stumbled across this (while using my homebrewn enum class): > > class test: > pass > > instance = test() > setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) > > I would've expected some kind of error message here when calling > setattr(); after all, its not a regular attribute? Okay. But so what? -Peter From qrczak at knm.org.pl Tue Jun 15 06:16:51 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 15 Jun 2004 12:16:51 +0200 Subject: does python have useless destructors? References: Message-ID: On Tue, 15 Jun 2004 01:09:05 -0700, David Turner wrote: > So what I'll do is write a PEP to fix the exception handling semantics > in CPython, and hope that pressure from users who discover how much > easier it is to write RAII -style code will eventually introduce > reference counting to Jython and friends. Jython will not switch to reference counting, and programs relying on destructors run immediately are still broken, relying on an implementation detail of CPython. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From imbosol at aerojockey.com Tue Jun 15 12:27:31 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 15 Jun 2004 09:27:31 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <60dfb6f6.0406150827.6dcc5ef5@posting.google.com> David Eppstein wrote in message news:... > In article , > Carl Banks wrote: > > > > Ok, see, here's the thing. I look at the Ruby code and can kind > > > of follow it. I look at the Python code and can kind of follow it. > > > but in neither case have I, in glancing here and there today, been > > > able to decipher exactly what is going on. Care to show the 5 line > > > long form to see if I get that? No explination, just curious to see > > > if I can get it reading real code instead of hacked up line noise. > > > > Of course you can. > > > > import glob > > import os > > import re > > > > f = {} > > for pattern in ("*.rar.*","*.r[0-9][0-9].*"): > > for listing in glob.glob(prefix+pattern): > > f[listing] = None > > for filename in f: > > os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) > > > > > > I don't know what sesc is. I assume he had defined it elsewhere, > > because he said this was only part of a script he wrote (and that's > > what scares me--I can understand a throwaway one-liner looking like > > this, but not a line in a script). > > As long as we're cleaning up code, how about > > import glob, os, sets > f = Set() > for pattern in ("*.rar.*","*.r[0-9][0-9].*"): > f.update(glob.glob(prefix+pattern)) > for filename in f: > os.system("cat %s.* > %s" % (sesc(filename),sesc(filename))) > > Now it's not even much longer than the original unreadable mess... I just noticed that I mistakenly left out the regexp in my clean code. Where I had f[listing] = None, I should have f[re.sub(r"\.\d+[\d.-]*$","",listing)] = None, or an extra varible. -- CARL BANKS From tim.one at comcast.net Sun Jun 13 12:35:38 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 12:35:38 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: Message-ID: [David Fraser] > Is it possibile to have a better algorithm for binary to base 10 > conversion, or is that limited to quadratic time? Sub-quadratic general base-conversion algorithms certainly exist. Practical implementations are complex and long-winded, and I doubt Python will ever have one natively. > Any links to papers/discussions on this? There's a huge literature on asymptotic complexity of elementary arithmetic operations on unbounded ints, and that's relevant because general base conversion boils down to multiplication and division. Unless your interest is purely theoretical, I recommend searching GMP discussions. For example, here's a pointer into a thread from last December giving an overview of what GMP developers were planning to try at that time: "mpf_get_str() is slow for big numbers?" http://www.swox.com/list-archives/gmp-discuss/2003-December/000901.html From noamr at correctme.users.sourcephorge.net Mon Jun 21 17:30:50 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Tue, 22 Jun 2004 00:30:50 +0300 Subject: Reference implementation of an import hook Message-ID: Hello, Do you know of a reference implementation of an import hook? I mean a class, written in Python, that imitates Python's default module loading behaviour. I mean that I would be able to append the class to sys.path_hooks, and modules will be imported in the same way they are currently imported. I want it so that it would be easy for me to change it, or subclass it, for my own needs, while preserving its behaviour. (The situation, if you are interested, is that currently modules are loaded from the network, which takes a long time, and I want to create a caching mechanism which will use the local hard-disk.) Thank you, Noam Raphael From chuck.amadi at ntlworld.com Sun Jun 13 10:05:56 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sun, 13 Jun 2004 15:05:56 +0100 Subject: EMAIL script parse output screen and to a new file! In-Reply-To: <200406101354.i5ADsUeb006064@sevenofnine.smtl.co.uk> References: <200406101354.i5ADsUeb006064@sevenofnine.smtl.co.uk> Message-ID: <40CC5F44.5060403@ntlworld.com> Chuck Amadi wrote: >Cheers for pointing that out !. > >By the way list is there a better way than using the readlines() to parse the >mail data into a file , because Im using email.message_from_file it returns >all the data i.e reads one entire line from the file , headers as well as just >the desired body messages . > >fp = file("/home/chuck/pythonScript/testbox") >mb = mailbox.UnixMailbox(fp, email.message_from_file) > ># > >mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") >for mail in fp.readlines(): > mailout.write(mail) > ># > >for mail in mb: > body = mail.get_payload() > mailout.write(body) # write only the body messages to SurveyResults.txt > >Cheers if the is a better way I can't get my head round how I can print mail ( >only the body messages) to screen and the entire mail headers and body to the >new file. > > > >Hi hav any one got any suggstions to my script I can parse the email body messages to screen but I want the same desired effect to save to a new file. > The above works but also parse's the email headers as well as the desired body messages. Cheers Chuck From jhs at oes.co.th Tue Jun 29 23:28:47 2004 From: jhs at oes.co.th (Jason Smith) Date: Wed, 30 Jun 2004 10:28:47 +0700 Subject: Does Python optimize regexes? In-Reply-To: References: Message-ID: <40E2336F.8050009@oes.co.th> Thanks much to Peter and Michael for the clarification. Peter Otten wrote: > So not explicitly calling compile() in advance only costs you two function > calls and a dictionary lookup - and maybe some clarity in your code. The reason I asked is because I felt that re.compile() was less clear: someRegex = re.compile('searchforme') while something: theString = getTheString() if someRegex.search(theString): celebrate() I wanted to remove someRegex since I can shave a line of code and some confusion, but I was worried about re.search() in a loop. The answer is this is smartly handled in Python, as opposed to bytecode optimizations. Great! -- Jason Smith Open Enterprise Systems Bangkok, Thailand http://oes.co.th -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 264 bytes Desc: OpenPGP digital signature URL: From dfdahlke at charter.net Mon Jun 7 12:10:15 2004 From: dfdahlke at charter.net (Doug) Date: 7 Jun 2004 09:10:15 -0700 Subject: PythonWin 2.3.2 (#49) problem with win.quit callback Message-ID: Mark, I'm using activestates version of your PythonWin in their version 2.3 of python. I've also noticed this as well with the version that was exported with version 2.2 as well. I'm going through the exercized in Mark Lutz's "Programming Python" which has been very informative with examples of coding. In his gui tour, he uses a lot of Tk window.quit functions for call backs to exit his code. Using PythonWin to run this code works fine until that callback gets executed and the result I get is either PythonWin locking up, or dieing with a call to an illegal memory area error. When the code is run from a shell, the program works fine. Is there something in the wrapper causing this to lock up? Just posting to find if this is a know problem and if there is a workaround. I'd like to start using python for a project I have and I like your IDE for quickly put something together. Thanks Doug From skip at pobox.com Thu Jun 17 14:27:41 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 17 Jun 2004 13:27:41 -0500 Subject: Using Fortran libraries from Python? In-Reply-To: References: Message-ID: <16593.58013.592759.110832@montanaro.dyndns.org> Carl> I have experimented with f2c and swig-generated wrappers to create Carl> python modules from Fortran files. ... Carl> Any help is appreciated! I'd take a look at f2py, part of the scipy package (and also available on its own): http://www.scipy.org/ http://www.python.org/pypi?%3Aaction=search&name=f2py&_pypi_hidden=0 Skip From peufeu at free.fr Mon Jun 28 03:23:21 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Mon, 28 Jun 2004 09:23:21 +0200 Subject: Help formatting a mysql query string References: <40DD7414.6080406@holdenweb.com> Message-ID: The PHP way is awful (you have to escape your strings and if you forget, you have a vulnerability).. Is you want to have dynamic fields you can do : cursor.execute( "INSERT INTO mytable SET %s=%s", (fieldname, value) ) or you could also do this : query = "INSERT INTO mytable SET %s=%%s" % fieldname cursor.execute( query, (value,) ) The last one is preferred if - your SQL library precompiles and reuses queries (I don't know if it does) - You use executemany to insert several lines. HOWEVER The last variant has a security vulnerability : fieldname is not quoted. Solution : On entering your script, test : if fieldname not in ('field1', 'field2'): raise ValueError, "Invalid field name" > Thanks for the help, sorry I posted this twice, my news reader was not > showing the original post so i resubmitted it. I normally work with php > thats why I was trying to build it as a string. I now see how I can load > the data values from my variables, however is the same possible for the > fields? I know you say its best to specify the column names etc however > my > script is parsing a web page and getting the field headings (which will > stay the same), data and table name so I wanted to make the script handle > all this rather than having to have a seperate cursor.execute() for each > table I want to update - does this make sense? > > Regards > > Rigga From alex-news-deleteme at comcast.net Tue Jun 29 11:20:45 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 29 Jun 2004 15:20:45 GMT Subject: embedded python? Message-ID: Hi, I love Python! I've been using it for a couple of years now and have found it to be a highly productive language. I evangelize it to my developer friends and am probably responsible for the sale of at least 10 Alex Martelli books. I am now in the fortunate position of being able to use Python for a large project, and as such I have a question. We are developing a distributed application running on approximately six thousand nodes with somewhat limited hardware resources. Our hardware target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected specific hardware yet; the hardware target is what we are trying to fit into based on price constraints. Each device needs to be able to handle about 2 kbs (yes kilo, not mega) worth of network traffic. I intend to a least prototype the system in Python. It would be great if we could we could use Python in production by embedding it in the hardware. My question is does anyone have any real world experience using python in an embedded system? Two general categories of questions: 1) Are there any embedded Pythons out there? The nodes will likely be running some form of Linux, but I don't particularly feel like devoting resrouces to porting python. Any embedded Linuxes supporting Python? Thoughts in general? 2) What are the resource requirements of Python? How much overhead do the network related modules add? Obviously I'll be able to determine our application's resource usage once the prototype is written, but I curious about other people's past experience. In short, is embedding python realistic? Thoughts and comments are greatly appreciated! Thanks, Alex From arctic at tuxtrax.com Sun Jun 6 07:41:13 2004 From: arctic at tuxtrax.com (TuxTrax) Date: 6 Jun 2004 04:41:13 -0700 Subject: Python on a thumbdrive References: <10d9011b.0406051246.7eac1408@posting.google.com> <40c2389a$0$21557$626a14ce@news.free.fr> Message-ID: <10d9011b.0406060341.5464ef67@posting.google.com> Christophe Cavalaria wrote in message news:<40c2389a$0$21557$626a14ce at news.free.fr>... > TuxTrax wrote: > > > I tried setting pythonhome from Bash: > > > > PYTHONHOME="/mnt/sda1/python/python2.3" > > If you did it like that it's a mistake : > > $ PYTHONHOME="/mnt/sda1/python/python2.3" > $ /mnt/sda1/python/python > > Do that instead : > $ export PYTHONHOME="/mnt/sda1/python/python2.3" > $ /mnt/sda1/python/python Thanks, that did the trick except for one remaining error on startup. I moved the python executable into the python2.3 directory (which is inside a directory simply called "python"), with the other python files and directories. I then used the following line in my .bashrc file: export PYTHONHOME="/mnt/sda1/python/python2.3" I don't get the errors on the internal and external component loads when I start up python now, but I sill get one last error: 'import site failed'; use -v for traceback Yet 'site.py' and 'site.pyc' exist in the python2.3 directory. When I type: >>> import site after the initial python import error on starting python up, There are no errors or complaints from python, and the module seems to have been loaded in just fine. Thanks for the help, Mathew From newsgroups at jhrothjr.com Mon Jun 21 17:57:42 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 21 Jun 2004 17:57:42 -0400 Subject: Unicode perplex References: <10deickd7vpmo7a@news.supernews.com> <40d74e5d$0$568$e4fe514c@news.xs4all.nl> Message-ID: <10demg1jdvu3f3c@news.supernews.com> "Irmen de Jong" wrote in message news:40d74e5d$0$568$e4fe514c at news.xs4all.nl... > John Roth wrote: > > > Remember that the trick > > is that it's still going to have the *same* stream of > > bytes (at least if the Unicode string is implemented > > in UTF-8.) > > Which it isnt't. > > AFAIK Python's storage format for Unicode strings is > some form of 2-byte representation, it certainly isn't > UTF-8. > > So if you want to turn your string into a Python Unicode > object, you really have to push it trough the UTF-8 codec... I see. I'm really very much a novice at unicode and all the codec stuff. If I understand you, I need to get the utf-8 codec and use the decode function to turn it into a unicode string, and then use the encode function to turn it back to a standard 8-byte string so I can write it out (or send it down the pipe or socket...) Thanks. Now that you point it out, it does look kind of obvious - the second time. John Roth > > --Irmen From chuck at smtl.co.uk Thu Jun 10 09:54:30 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Thu, 10 Jun 2004 14:54:30 +0100 Subject: My simple script parse output screen and to a new file! In-Reply-To: Your message of "Thu, 10 Jun 2004 12:20:25 +0200." References: Message-ID: <200406101354.i5ADsUeb006064@sevenofnine.smtl.co.uk> Cheers for pointing that out !. By the way list is there a better way than using the readlines() to parse the mail data into a file , because Im using email.message_from_file it returns all the data i.e reads one entire line from the file , headers as well as just the desired body messages . fp = file("/home/chuck/pythonScript/testbox") mb = mailbox.UnixMailbox(fp, email.message_from_file) # mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") for mail in fp.readlines(): mailout.write(mail) # for mail in mb: body = mail.get_payload() mailout.write(body) # write only the body messages to SurveyResults.txt Cheers if the is a better way I can't get my head round how I can print mail ( only the body messages) to screen and the entire mail headers and body to the new file. From imbosol at aerojockey.invalid Mon Jun 14 21:06:45 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 15 Jun 2004 01:06:45 GMT Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <9hdzc.93679$DG4.801@fe2.columbus.rr.com> <10cr9m1q7tlp4b4@corp.supernews.com> Message-ID: Peter Hansen wrote: > Carl Banks wrote: >> Heh. It seems to me that, by the same reasoning, we could claim that >> Python has verbose execution. Someone's obviously willing to give >> Perl the benefit of the doubt here, but not Python. I smell >> shenanigans. > > I tried a few Google searches, even apparently reaching the page that > started this thread, but I can't see what "verbose execution" might > mean other than (a guess) a "trace" mode which prints something for > every line executed as the interpreter runs. And, if that's really > what it is, then Python does have the capability pretty easily, via > sys.settrace(). (Which I'm sure Carl knows, therefore I assume my > guess is wrong.) I took it to mean the same thing you did (you might note that shell scripts are listed as having verbose execution, which pretty much can only mean that one thing). My point was, Perl's interactive interpretter isn't "real"; to get it, you have to invoke the debugger, or use a little Perl program to get the effect. Likewise, Python's verbose execution isn't "real"; you can't get it with a simple command line argument. You have to define a settrace function. Yet, they list Perl as having an interactive interpretter, by Python as not having verbose execution. Smells like a someone has an unconscious bias here. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From http Tue Jun 29 03:41:49 2004 From: http (Paul Rubin) Date: 29 Jun 2004 00:41:49 -0700 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04> <034301c4547b$e8d99260$8119fea9@boba> Message-ID: <7xacymstdu.fsf@ruckus.brouhaha.com> Christopher T King writes: > Lisp and Scheme do the same thing: > > (set! a 5) <- sets a variable (i.e. changes its value) > (eq? a 6) <- tests equality (returns true or false) Actually just Scheme. Traditional Lisp uses (setq a 5) and (eq a 6). For less frequently used predicates, Lisp sometimes uses the -p convention, similar to your ? convention. From dummy at scriptolutions.com Tue Jun 15 14:33:41 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Tue, 15 Jun 2004 20:33:41 +0200 Subject: (OT) Boa Constructor and Python 2.3.4 References: Message-ID: On Tue, 15 Jun 2004 11:49:48 GMT, "flupke" wrote: > >"Lothar Scholz" schreef in bericht >news:hajtc01o1it4ss4npcu5ba6045j7thuvkh at 4ax.com... >> On Tue, 15 Jun 2004 10:15:39 GMT, "flupke" >> wrote: >> >> >Hi, >> > >> >My wxPython is version 2.5.1.5u. >> >Any ideas? >> > >> >> AFAIK the CVS version only works with wyPython 2.4. > >Hhhmm. Bummer. I wanted to use it to quickly get a wxPython app >going as i'm pretty new to Python & wxWindows. >Well, i guess i can also "type" :) >Are there any other screen designers (i've tried wxGlade but it >seems a bit limited) > >Benedict > Maybe WxDesigner, but commerical and looks a little bit strange when you use it the first time. From dmq at gain.com Fri Jun 11 15:00:42 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 11 Jun 2004 12:00:42 -0700 Subject: Can someone explain this weakref behavior? References: Message-ID: On Fri, 11 Jun 2004 13:56:19 -0400, "Tim Peters" wrote: >That will pass under CPython today, but there's no general guarantee about >exactly when a weak dict will notice that keys (or values) have become >unreachable by strong references. OUCH!! We just built a module that uses weak references to keep a "robust count" of instances in various classes. The claim is that this is more robust than simply incrementing and decrementing class variables using __init__ and __del__. The module seems to be working OK, immediately deleting the weak reference as soon as all references to the corresponding instance are deleted. If I understand you correctly, there is some chance that a future implementation of Python may have the weak references "out-of-sync" with the actual count of live instances. Is that a remote possibility, or something quite likely to occur? I have to decide now whether to rip out some risky code. Is there a good way to track the count of instances? If not, would it make sense to request a guarantee on the current behavior of weak references? Maybe it could be an option, assuming there is some performance penalty, an option to be used when accuracy is more important than speed. -- Dave From leo at sie.arizona.edu Tue Jun 15 21:04:27 2004 From: leo at sie.arizona.edu (Leo) Date: 15 Jun 2004 18:04:27 -0700 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> <40cf1112$0$41761$5fc3050@dreader2.news.tiscali.nl> Message-ID: <626705ff.0406151704.11bc7387@posting.google.com> > The comparison operators should be used in cases where the "reflective" > behaviour is sound. I beleive they should not be used for other things > than comparing instances for witch there is a complete order (many > others will disagree). I don't immediately see why we should restrict the usage of comparison operators to that case, but that doesn't matter. What (maybe) matters is: If we were to ask (PEP) for an __rge__ with a default implementation that calls __le__ with the parameters inverted, would that break anything? I can think of other applications where this would be useful. For example: generating MathML from python expressions. Or looking at it another way, wouldn't it improve language consistency to add an __rge__ method? Unfortunately in PEP 207 the issue of reflexivity is raised and decided, but not justified. Maybe at the time no one had an example where this feature would be useful? Would it be too hard to change? Thx, Leo. From roy at panix.com Thu Jun 3 10:45:13 2004 From: roy at panix.com (Roy Smith) Date: Thu, 03 Jun 2004 10:45:13 -0400 Subject: python vs awk for simple sysamin tasks References: Message-ID: In article , Matthew Thorley wrote: > My friend sent me an email asking this: > > > I'm attemtping to decide which scripting language I should master and > > was wondering if it's possible to do > > these unixy awkish commands in python: > > > > How to find the amount of disk space a user is taking up: > > > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > > {print "User rprice total disk use = " sum}' > > > > How to find the average size of a file for a user: > > > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > > {print "The ave size of file for rprice is = " sum/NR}' > > I wasn't able to give him an afirmative answer because I've never used > python for things like this. I just spent the last while looking on > google and haven't found an answer yet. I was hoping some one out there > might have some thoughts ? > > thanks much > -matthew Neither of these are really tasks well suited to python at all. I'm sure you could replicate this functionality in python using things like os.walk() and os.stat(), but why bother? The result would be no better than the quick on-liners you've got above. Even if you wanted to replace the awk part with python, the idea of trying to replicate the find functionality is just absurd. I'm sure you could replicate them in perl too, but the same comment applies. Find is an essential unix tool. If you're going to be doing unix sysadmin work, you really should figure out how find works. From project5 at redrival.net Tue Jun 29 15:54:11 2004 From: project5 at redrival.net (Andrei) Date: Tue, 29 Jun 2004 21:54:11 +0200 Subject: wxPython: wxGrid vs. wxListCtrl References: <39cbe663.0406291116.166f436a@posting.google.com> Message-ID: <1v4erg10g7cds.y7kspsysjyuy.dlg@40tude.net> Piet wrote on 29 Jun 2004 12:16:11 -0700: > Building the tree view was not a problem, but I haven?t found a good > widget for the "grid view" component. wxGrid allows to edit the > content of the table (which will be the attribute values) but I > haven?t found a way to link a specific cell to a certain xml node. Have you looked at the Huge grid table example in the demo, the one with the 100 million cells? It demonstrates how to use a table for the grid. I've made an app inspired by that example which loads stuff on demand from a bsddb and stores changed items immediatly back to the db - seems quite similar to what you intend to do. > This is important, because when the cell content changes I would like > to be able to directly communicate this change to the underlying xml > tree (in the tree component of the editor, this is already achieved). The Grid table is basically sitting in between the grid that the user sees and whatever storage backend you have. The grid asks the table for data to be inserted in cell at some coordinates, the table does whatever it deems necessary and answers. Even better, the grid asks the table about what attributes each displayed cell should have (color, read-only, custom editor, the whole lot). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dbecker at cpicorp.com Thu Jun 3 16:49:59 2004 From: dbecker at cpicorp.com (Derek Chen-Becker) Date: Thu, 03 Jun 2004 15:49:59 -0500 Subject: Problem with LargeFile support (Debian, Woody) In-Reply-To: References: Message-ID: <40BF8EF7.3010207@cpicorp.com> Eddie Parker wrote: > Hello! > > Standard disclaimer here - I'm new, so I'm not sure if this is the wrong > place to be posting, so please be kind if I am, and I'll kindly move my > question elsewhere. :) Otherwise - thank you for your help! > > I'm trying to set up Zope, but everytime I do, I get a warning that > largefile support isn't enabled. > > I hop into my ever friendly python interpreter, and run 'import > test.test_largefile', and I get the following: > > >>>>import test.test_largefile > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.3/test/test_largefile.py", line 47, in ? > raise test_support.TestSkipped, \ > test.test_support.TestSkipped: filesystem does not have largefile support > > Now, I'm not sure what I'm doing wrong? I'm running on Debian woody, and > uname -a gives me the following information: > > Linux server 2.2.20-idepci #1 Sat Apr 20 12:45:19 EST 2002 i686 unknown > > And df -HT gives me the following: > > Filesystem Type Size Used Avail Use% Mounted on > /dev/hda1 ext2 3.0G 470M 2.3G 17% / > > Does ext2 not have largefile support? I'm not familiar with the whole issue > at hand, so any information you can give me would be great. :) > > Thanks! > > -e- > > Python or your glibc may not be compiled with Largefile support, although if this is a recent dist I'd be surprised at this. IIRC, ext2 supports Large files, but your libraries have to as well. Derek From imbosol at aerojockey.invalid Sun Jun 13 06:03:50 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 13 Jun 2004 10:03:50 GMT Subject: does python have useless destructors? References: <40CC19D5.6040401@v.loewis.de> Message-ID: "Martin v. L?wis" wrote: >> myfile = open("myfilepath", "w") >> myfile.write(reallybigbuffer) >> myfile.close() >> >> If the write fails due to a lack of disk space, the exception will >> prevent the explicit close() from happening. Now, if myfile goes out of >> scope, I would hope that the file object is destroyed and thus the file >> is closed, but after reading the python documentation, it seems that >> the only way to guarantee closure of the file is using the mentioned >> try/finally construct... > > C-Python 2.3.4 will close the fil if myfile goes out of scope, Not so fast, my friend. What if reallybigbuffer is an instance of the following class, defined in the same function: class reallybigbufferclass(object): def __str__(self): __builtins__.myfile = myfile; return "sucker!" Whoops, looks like there's still a reference hanging around. Python STILL doesn't guarantee this file will be closed upon exit. Even more perniciously: class reallybigbufferclass(object): def __init__(self): self.self = self def __str__(self): self.myfile = myfile; return "sucker!" def __del__(self): pass I think if reallybigbuffer goes out of scope and no one else references it, then myfile will never be closed, ever. At least not until someone gets at it using the gc module. These are silly examples, of course, but with more intricate stuff (or with code by other people who are always less disciplined than you) this can become a real problem. Face it, people, it's ludicrous to rely on the garbage collector to finalize stuff for us. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From VIRUS-SCANNER at ipmotor.com Wed Jun 30 02:43:38 2004 From: VIRUS-SCANNER at ipmotor.com (VIRUS-SCANNER at ipmotor.com) Date: Wed, 30 Jun 2004 14:43:38 +0800 Subject: =?iso-8859-1?q?=B2=A1__=B6=BE__=BE=AF__=B8=E6?= Message-ID: <2004630144338.15145.quarkmail@mailserver> ??????????????????????????<>????????????????. ??????????????????????????: ALERT: [Worm/Lovgate.W worm] /quark/tmp/.unpacked-1088577818-9787-169/body.zip <<< Contains signature of the worm Worm/Lovgate.W ????????????????????????????????. ??????????????????????????: ------------------------- ?????? ----------------------------- Received: from 218.19.65.141 (HELO python.org) (envelope-from python-list at python.org) by (quarkmail-1.2.1) with ESMTP id S458854AbUF3GnY for xw_gz at dahengit.com; Wed, 30 Jun 2004 14:43:24 +0800 From: python-list at python.org To: xw_gz at dahengit.com Subject: TEST Date: Wed, 30 Jun 2004 14:41:32 +0800 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0012_A1EFA1A1.4DE548FD" X-Priority: 3 X-MSMail-Priority: Normal -------------------------------------------------------------- From a at a.com Sun Jun 6 22:44:44 2004 From: a at a.com (Andy C) Date: Mon, 07 Jun 2004 02:44:44 GMT Subject: how to get memory info from python? References: Message-ID: I posted a similar question awhile back but have not been able to get any info. I wanted to see if Python could be embedded in game consoles -- but the lack of memory info is a dealbreaker. If you look in google there are a lot of people asking this same question with no info! Andy "Gardner Pomper" wrote in message news:mailman.637.1086562751.6949.python-list at python.org... > Hi, > > I'm pretty new to python, but I have not found any way to find out how much > memory is being used by my python application. I have some fairly large data > to load in and I am concerned about hitting the 2GB limit on my 32 bit > processes. > > I would like to have the program check itself for memory usage. I know I can > get the memory information from a 'ps -l'. Btw, I will be running on AIX and > linux, although I may do some development on Windows. > > - Gardner > > From segphault at sbcglobal.net Sat Jun 12 16:29:31 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 12 Jun 2004 20:29:31 GMT Subject: Language Suitablilty References: Message-ID: On Sat, 12 Jun 2004 21:00:19 +0200, Jens Thiede wrote: > I'd like to know what other people think about Python. In particular, what > is Python best suited for? > > I've been using Python for a little while now and in my opinion Python is a > great all-terrain language. I would describe it as concrete scaffolding. > > Could anyone comment on how Python fares against C++, Java and Perl? > > Jens. In my experience, python is almost always more practical than java. The python vs. c++ comparison is an interesting issue. I strongly dislike c++, and avoid it wherever possible. In certain cases, python is not fast enough for what I need to do. When I need fast execution and static typing, I write a library in OCaml and write a python wrapper for it. Python is a great language for text processing. It is also very good at dealing with databases and xml. In many cases, python is also an excellent choice for a complex web application (just look at zope!) Python's greatest strengths, in my opinion, are its simplicity and its introspective power. Perl is really a very useful and powerful tool in its own right, and there are some places were it can be a better choice than python, particularly the shell. I still use perl one-liners from the command line almost every day. I recently started learning ruby, and I personally feel that for shell scripts, ruby is a better choice than perl or python - it is an elegant compromise between the two. If I want to use regular expressions, I almost always use ruby or perl instead of python. -- SegPhault From klachemin at home.com Sun Jun 13 03:46:34 2004 From: klachemin at home.com (Kamilche) Date: 13 Jun 2004 00:46:34 -0700 Subject: Good IDE for Python Message-ID: <889cbba0.0406122346.2e77941b@posting.google.com> I love Python, but I'm less than in love with IDLE. It's OK, but it really doesn't have enough capabilities. What I consider critical, are a popdown listing of all my functions, colored syntax printing, and a right-click 'definition' context menu that will hop you to the spot where that keyword is defined, if possible. Everything else I could learn to do without, but these features keep me hoping for a better IDE for Python. I'm used to the Microsoft Visual C++ debugger, and though tooltip variable debugging and intellisense were nice, they broke often enough that you couldn't rely on them anyway, so I don't really need those features. I would also like the ability to create application 'forms' visually. I'm on a Windows XP machine. Any suggestions on what I should install next? From http Fri Jun 11 16:40:33 2004 From: http (Paul Rubin) Date: 11 Jun 2004 13:40:33 -0700 Subject: Insecure Pickling References: <781dd16f.0406111114.17959b90@posting.google.com> Message-ID: <7xacz9x1z2.fsf@ruckus.brouhaha.com> surferjeff at gmail.com (Jeff) writes: > However, it is so insecure it can hardly ever be used. How often can > you truly trust the think you're unpickling? If it's a pickle you created yourself and nobody else has had a chance to tamper with, then it's presumably trustworthy. > Has anyone seen a secure pickle alternative? I think anything with the amount of flexibility that pickles have is inherently insecure. But there are certainly lots of serialization formats with less flexibility and more security. From christopher at baus.net Mon Jun 28 15:59:51 2004 From: christopher at baus.net (Christopher Baus) Date: Mon, 28 Jun 2004 12:59:51 -0700 (PDT) Subject: try/except/finally construct not available? In-Reply-To: <2kbagnFc74pU2@uni-berlin.de> References: <2kb09jF3t3eU2@uni-berlin.de> <2kbagnFc74pU2@uni-berlin.de> Message-ID: <33485.12.146.21.163.1088452791.squirrel@mail.baus.net> Hi, I'm just learning python after years of C/C++/Java/bash/etc. It is going pretty good except a few minor issues regarding syntax. I have to admit the while/else contruct is a bit weird, but I think I understand the motivation. But I am confused about exceptions having read the chapter in Learning Python. How do I do something similar to the following java code? try{ a.mightThrow(); } catch(Exception e){ System.out.print("looks like an exception"); } finally{ a.cleanup(); } try: pass finally: pass Doesn't allow the programmer to catch certain exceptions, handle them, and then perform operations in either case. -- Christopher Baus http://www.baus.net/ Tahoe, Wine, and Linux. From db3l at fitlinxx.com Wed Jun 30 02:02:00 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Jun 2004 02:02:00 -0400 Subject: does not work on freeBSD but works on linux, and windows References: <1NoEc.79428$kV1.13425@newssvr29.news.prodigy.com> Message-ID: John fabiani writes: > 2. below is a simple ftp program > > import ftplib > import sys > remote=ftplib.FTP(host='myIpAddress',user='username',passwd='password') > mohpac07=open("/usr/home/spx/servplus/outbounds/mohpac07.dbf",'rb') > remote.set_debuglevel(2) > remote.set_pasv(0) > remote.storbinary("STOR mohpac07.dbf",mohpac07,8192) > remote.close > remote.quit Just a shot in the dark, but if your last two lines are accurate, you're simply referencing the close and quit names within the ftplib object, but aren't actually calling them. Also, quit() includes the close operation, so I think you'd want that to end with: remote.quit() Note that your log never shows the Goodbye during a clean exit from the server. It's possible that the platform differences you are seeing has to do with differences in buffering at the application and/or protocol stack layer and perhaps how stranded data is handled during process/socket shutdown. It's possible that the final portion of the data related to the STOR is never getting transmitted to the remote ftp server. -- David From M.Waack at gmx.de Tue Jun 29 16:36:25 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 29 Jun 2004 22:36:25 +0200 Subject: sending signals to the calling function References: Message-ID: <9f09r1-468.ln1@valpo.de> Haim Ashkenazi wrote: > I have a function that receive a list of files and creates a zip > from these files. I want it to send signal to the calling function > with the name of the file it currently compressing. is there a way > to do this (without threads)? Maybe. You should better explain your problem then asking how to implement your solution. Mathias From gohaku at earthlink.net Thu Jun 10 21:45:55 2004 From: gohaku at earthlink.net (gohaku) Date: Thu, 10 Jun 2004 21:45:55 -0400 Subject: Does a Python Sound Library exist? Message-ID: <143FA2AF-BB49-11D8-A44D-000A9574CFD8@earthlink.net> Hi everyone, I would like to know if there is a sound library for manipulating and retrieving information from .WAV or .MP3 Files. I came across the page for Pythonware Sound Toolkit but that toolkit is no longer available. Thanks in advance. -gohaku From MAIL-SA at gcc-sg.org Wed Jun 16 03:20:01 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Wed, 16 Jun 2004 10:20:01 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F65092553@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = manoj_tamhankar at hotmail.com Recipient(s) = python-list at python.org; Subject = Re: Administration Scanning Time = 06/16/2004 10:20:01 Engine/Pattern = 7.000-1004/905 Action on message: The attachment data.txt .scr contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoulsam at yahoo.com Fri Jun 18 14:50:42 2004 From: raoulsam at yahoo.com (Raoul) Date: 18 Jun 2004 11:50:42 -0700 Subject: win32com.client passing a list of values to a C++ COM object. References: <7b22ae5b.0406131604.6d99de2c@posting.google.com> <8360efcd.0406140009.360521f5@posting.google.com> Message-ID: <7b22ae5b.0406181050.7d5c31a1@posting.google.com> tim.golden at viacom-outdoor.co.uk (Tim Golden) wrote in message news:<8360efcd.0406140009.360521f5 at posting.google.com>... > raoulsam at yahoo.com (Raoul): > > I wrote a COM server object in C++ a few months ago. I can use it from > > Visual Basic, Visual C++, S-Plus and a number of other scripting > > environments. > > > > What I can't do is use it with my FAVOURITE scripting language, > > Python. > > import win32com.client > > > > vals = [1.2,1.4,1.5,3.4] > > > > seg = win32com.client.Dispatch("CN.averager") > > seg.learnAndRun(vals) > > OK. I'm absolutely no expert here, but I understood that > pywin32 automatically converted an arbitrary Python sequence > to an array of VARIANTS. If you haven't already, have a look > at this chapter of Hammond & Robinson's Python Win32 book: > > http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html > > Also, try posting to the python-win32 list, in the hope > that someone more knowledgeable than I see your post: > > http://mail.python.org/mailman/listinfo/python-win32 > > TJG I found it. It was a subtle bug in my COM class. Basically my code expected row major layouts of lists and python did it's in column major form... From peter at engcorp.com Mon Jun 21 16:30:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 16:30:53 -0400 Subject: Running the makepy tool automatically from a python script In-Reply-To: <67c8710b.0406211039.1824b6dc@posting.google.com> References: <67c8710b.0406211039.1824b6dc@posting.google.com> Message-ID: Svenn-Ivar Svendsen wrote: > I use the makepy tool in pythonwin to generate wrappers for my > connection point (event) interfaces in a project. It works fine. > The question is; Is it possible, in a python script, to detect if > wrappers for COM (event) interfaces the script uses have been created, > and in case not somehow call the makepy tool manually before > proceeding? How should this be done? Run makepy.py manually with the "-i" option first, and it will give you this sort of output: PeterTest 1.0 type library {7FAE1795-E030-401D-BCD9-C05CC1D318EC}, lcid=0, major=1, minor=0 >>> # Use these commands in Python code to auto generate .py support >>> from win32com.client import gencache >>> gencache.EnsureModule('{7FAE1795-E030-401D-BCD9-C05CC1D318EC}', 0, 1, 0) Does that help? (Basically, you need the GUID for the type library, and the LCID and version major/minor numbers, and just pass them to EnsureModule() as above.) -Peter From vng1 at mac.com Wed Jun 23 07:35:30 2004 From: vng1 at mac.com (Victor Ng) Date: Wed, 23 Jun 2004 7:35:30 -0400 Subject: libxml2 and node identity References: Message-ID: <0001HW.BCFEE3420001441BF02845B0@news1.on.sympatico.ca> Ok - well I got a reply from Daniel Veillard, there's no way to properly get the identity of a node in libxml2 by using the standard Python bindings. This is a really bad since it allows you to leak memory very easily. If you can't properly determine node identity, then you don't know if it's safe to free the node's memory. vic Victor Ng wrote: > I've been trying to find information with how to figure out node > identity in libxml2 - but I'm at a loss. I can't seem to find what I'm > looking for on the xmlsoft.org site and google doesn't seem to help at > all with the following query: > > http://www.google.com/search?q=libxml2+node+identity > > Here's a snippet to show the problem: > > >>> import libxml2 > >>> doc = libxml2.newDoc('1.0') > >>> root = doc.newChild(None, 'root', None) > >>> print root, doc.children > > >>> print root._o, doc.children._o > > > What I'd _like_ to do is to be able to check that two nodes are actually > identical. The Python wrappers as well as the PyCObject references > don't seem to match up. I also can't seem to find any way to do > something like "node.isSameNode(otherNode)" > > Help! > > From jeffbarish at starband.net Wed Jun 16 12:43:07 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Wed, 16 Jun 2004 10:43:07 -0600 Subject: Bug in popen2.Popen3? Message-ID: Popen3 provides the method poll() which returns the exit status of the child process if it has finished or -1 if the process is still running. Here is the code: def poll(self): """Return the exit status of the child process if it has finished, or -1 if it hasn't finished yet.""" if self.sts < 0: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) if pid == self.pid: self.sts = sts _active.remove(self) except os.error: pass return self.sts If the child process has already exited when poll() is first called, the os.waitpid will raise an exception (No child process). The exception is caught and poll() returns self.sts, which is -1. There is no way for the value of self.sts to change from -1. -- Jeffrey Barish From loic at fejoz.net Wed Jun 16 10:30:42 2004 From: loic at fejoz.net (Yermat) Date: Wed, 16 Jun 2004 16:30:42 +0200 Subject: list to dict In-Reply-To: References: Message-ID: Bart Nessux wrote: > Peter Hansen wrote: > >> Bart Nessux wrote: >> >>> What is the easiest/fastest way to build a dictionary from a list? >>> The list contains 100,000 entries. >> >> >> >> A dictionary has key/value pairs. How do you want to map >> the elements of your list to this format? In pairs, or >> are you using them all as keys, or something else? >> >> -Peter > > > 1 = book1 > 2 = book2 > 3 = book3 > etc... >>> dict(enumerate(['a','b','c'])) {0: 'a', 1: 'b', 2: 'c'} >>> From ptmcg at austin.stopthespam_rr.com Sat Jun 26 06:54:27 2004 From: ptmcg at austin.stopthespam_rr.com (Paul McGuire) Date: Sat, 26 Jun 2004 10:54:27 GMT Subject: any trick to allow anonymous code blocks in python? References: Message-ID: > Maybe this relates to the fact that GUI toolkits are mostly C/C++ > based, and that years of limited languages have directed our mind > toward the 'you have to subclass' dictat. I wonder if SmallTalk GUIs > have something like this. Smalltalk supports inline anonymous code blocks, looking something like: mylist sort: [ :a :b | b-a ] invokes the sort message on mylist, using a code block with two arguments, a and b, using b-a as the comparison (implements a descending order sort). -- Paul From fowlertrainer at anonym.hu Mon Jun 28 03:21:27 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 28 Jun 2004 09:21:27 +0200 Subject: What is the meaning of static and class methods ? Message-ID: <40DFC6F7.8070808@anonym.hu> Hi ! I read the MetaClasses / Unifying Howto in python.org, but I cannot understand many things. I use Delphi - I use many classes in it, and I know the Java class-es too. In Delphi the class method is a method of class that callable without class creation. In Delphi the object creation is used class method named Create. Button:=TButton.Create(Owner); The Create is working on class, not on created object, and it is create, and return the created object. This is the only way to create objects. But I don't understand, why we need class method-s in python. If I want to create an object, that is don't need to I execute this object's Create method. Some other possible meaning is to create some class methods, that creates object with preinitialized state. Example: an ftp object with opened, and setted state. But we can do that with simple functions too. Another question is that what is the meaning of static methods ? In Delphi the not overrided methods of class are static, but you cannot use the Self parameter in that methods. In Java, the without static methods the JVM cannot run your main class, so it is needed to execute your program. But in py I don't understand the meaning of that methods. In the examples I see that we cannot use self parameter in static method - it is correct - but everything is seems to be that this is only a method with "special sign" that make the static method the piece of an object. So: I want to anyone please send an example of class/static methods that HAVE MEANING. A real example, to I understand, why we need that methods in python. Thanx for it: FT From chuck.amadi at ntlworld.com Wed Jun 9 19:48:41 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Thu, 10 Jun 2004 00:48:41 +0100 Subject: UML Tools In-Reply-To: <40C0458B.2080901@cenix-bioscience.com> References: <40C0458B.2080901@cenix-bioscience.com> Message-ID: <40C7A1D9.5020003@ntlworld.com> Neil Benn wrote: > Hello, > > Does anyone know of a decent tool to write UML diagrams > (mainly class diagrams but sequence would also be useful) that's aware > of Python's syntax (i.e. modules). I'd like round-trip as well but I > can live without it. > > cheers, > > Neil > Try ArgoUml is open source and I used to use when I was a Systems Net programmer . preety cool and free. Cheers Chuck From mithrandi at mithrandi.za.net Mon Jun 28 13:59:22 2004 From: mithrandi at mithrandi.za.net (Tristan Seligmann) Date: Mon, 28 Jun 2004 19:59:22 +0200 Subject: Class Chaos In-Reply-To: <2kb09jF3t3eU2@uni-berlin.de> References: <2kb09jF3t3eU2@uni-berlin.de> Message-ID: <20040628175922.GA11651@mithrandi.za.net> On Mon, Jun 28, 2004 at 12:45:37 -0400, Leif K-Brooks wrote: > Paul McGuire wrote: > >You will also find that you avoid some funny Python behavior if you > >avoid > >using built-in type names (such as list, dict, and str) for variable > >names. > > What sort of funny behavior? Code that uses the names without expecting them to be masked by other objects: str = "Blah blah" ... later ... str(5) Produces the slightly mysterious: TypeError: 'str' object is not callable Correct behavior, to be sure, but potentially confusing. -- mithrandi, i Ainil en-Balandor, a faer Ambar -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From peter at engcorp.com Mon Jun 14 19:04:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 19:04:07 -0400 Subject: Mod_python licensing? In-Reply-To: References: Message-ID: Leif K-Brooks wrote: > I'm writing an application for mod_python which I would like to cover > under the GPL. However, mod_python is licensed under the Apache license, > which I've heard isn't GPL-compatible. Does this force me not to use the > GPL? If so, which license would others recommend? Recommend for what purpose? For your entire application? If that's what you mean, perhaps the obvious answer is "use the Apache license". If that's not possible, explain why and also describe your requirements and then someone can give a (more) useful answer. -Peter From shalabh at cafepy.com Wed Jun 23 21:44:12 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 23 Jun 2004 18:44:12 -0700 Subject: Mozilla, XUL and the snake In-Reply-To: <40D5DA33.6040907@poczta.onet.pl> References: <40D5DA33.6040907@poczta.onet.pl> Message-ID: Jakub Fast wrote: > Hi, > > Does anybody know how far you can get nowadays with trying to use Python > as the script language for XUL instead of JS? Is it possible (even > theoretically) to write full-fledged applications on the Mozilla > platform with python only? > > In a parallel vein, anybody know what the architecture of Komodo is? > > Thanks for any pointers, information, etc > > Kuba > > PS. [snip] No specific answer but just a pointer to PyXPCOM: http://aspn.activestate.com/ASPN/Downloads/Komodo/PyXPCOM/ I believe it is used in Komodo. Cheers, Shalabh From NOmanlio_perilloSPAM at libero.it Tue Jun 15 06:41:27 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Tue, 15 Jun 2004 10:41:27 GMT Subject: does python have useless destructors? References: Message-ID: On Wed, 9 Jun 2004 20:40:11 +0000 (UTC), "Michael P. Soulier" wrote: > [...] Hi. Since __del__ isn't really 'useful', *maybe* a better solution is to add another special method for classes, ad example a __finalize__ method. Such method, if present, *will* be called during stack unwinding. So, in __finalize__ one can release 'external' resources. class file: __init__(self, ...): ... __finalize__(self): self.close() ... Another useful addition could be to add a 'block' statement: a_file = '...' block: f = open(a_file) f.write(...) As an example, block can be supposed to be equivalent to: block: statement => def __block() statement __block() Regards Manlio Perillo From tismer at stackless.com Fri Jun 25 20:34:53 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 26 Jun 2004 02:34:53 +0200 Subject: Parameterized Functions without Classes In-Reply-To: References: <2k35g4F14l1o0U1@uni-berlin.de> Message-ID: <40DCC4AD.4090809@stackless.com> Christopher T King wrote: > On Fri, 25 Jun 2004, Christian Tismer wrote: > > >>Lambdas were not the topic, since they are a deprecated >>feature, but sure it works. > > > Since when are lambdas deprecated? And if so, why? Not really deprecated, but Python is trying to replace it since a longer time. PEP 290, for instance. > IMHO, the best way to parameterize functions is with 2.4's proposed > partial() function: My intent was to show a nice thing that can be done today, not a contest which alternatives are there, including unreleased features. And lambda is nothing than a function with restricted syntax, so why do we burn bandwidth off-topic. -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From maschio_77 at hotmail.com Mon Jun 14 17:29:40 2004 From: maschio_77 at hotmail.com (Federico) Date: Mon, 14 Jun 2004 23:29:40 +0200 Subject: MsInternetExplorer CGI problem Message-ID: Using Cgihttpserver I put a python this script called time1.py: import time print "Content-Type: text/html\n\n" print '\n\n' print time.localtime() print '' in cgi-bin directory, and when I get localhost:8000/cgi-bin/time1.py in Internet Explorer I can see my localtime... then I go around on internet with my browser and when I go again in localhost:8000/cgi-bin/time1.py it shows the old time value and I have to refresh the page to have the rigth value.... Can I do something to resolve this problem? PS: under Linux with Netscape it works well without refreshing the page.... From dkturner at telkomsa.net Tue Jun 8 05:44:04 2004 From: dkturner at telkomsa.net (David Turner) Date: 8 Jun 2004 02:44:04 -0700 Subject: Destructors and exceptions References: Message-ID: Hi > > There is no Python equivalent of C++'s "destructor garanteed to be called > upon scope exit", for a couple of reasons: scope exit only destroys > references to objects, not the objects themselves; destruction of objects is > left to the garbage collector and you have no influence on it. In > particular, the gc is not required to release resources, so finalizers (the > __del__ method, closest to C++'s destructor) may not get called. This means > __del__ is pretty much useless (AFAIMC), and you can't rely on them being > called before program exit (or ever, for that matter). > In the documentation for the "gc" module, it states that objects with a __del__ method are not subject to garbage collection; they are collected using reference counting. Which means that one can rely on locals (to which there is only one reference) being destroyed in a predictable fashion -- but there's an exception. Section 3.1 of the Python Reference Manual specifies that raising exceptions may keep objects alive. What I take this to mean from an implementation point of view is that the exception mechanism doesn't unwind scope. Therefore, the destruction of locals in the presence of an exception is deferred to global clean-up time when the program exits. I can't think of any technical objections to having the exception mechanism also release references to locals that are going to go out of scope (unless one was planning to support resuming). Can you? Regards David Turner From michele.simionato at gmail.com Thu Jun 24 06:21:52 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 Jun 2004 03:21:52 -0700 Subject: Classic and New Style Classes? References: Message-ID: <4edc17eb.0406240221.708028bd@posting.google.com> "Chris S." wrote in message news:... > I'm generating the source of an object from a list of objects. Therefore > I need to determine if the object is a class definition (i.e. 'def > something(whatever):') or a class instance (i.e. 'somename = > somethingelse()'). With classic classes this is trivial, since all I > have to do is check the type. However, for the new "improved" style > classes this seems next to impossible, since everything is essentially > an instance of something. > > isinstance(class, classinfo) won't work since I won't necessarily know > classinfo. > > Is there any way to make this distinction? Any help is appreciated. >>> from types import ClassType >>> class Old: pass ... >>> isinstance(Old, ClassType) True >>> class New(object): pass ... >>> isinstance(New, type) True Also Old.__class__ raises an error whereas New.__class__ returns type(New). Is this what you are asking for? Michele Simionato From jens.spamfree at webgear.co.za Sat Jun 12 15:00:19 2004 From: jens.spamfree at webgear.co.za (Jens Thiede) Date: Sat, 12 Jun 2004 21:00:19 +0200 Subject: Language Suitablilty Message-ID: I'd like to know what other people think about Python. In particular, what is Python best suited for? I've been using Python for a little while now and in my opinion Python is a great all-terrain language. I would describe it as concrete scaffolding. Could anyone comment on how Python fares against C++, Java and Perl? Jens. -- Jabber ID: jtza7 at jabberafrica.co.za Location: South Africa Time Zone UTC +2 From sdahlbacSPAMSUCKS at abo.fi Thu Jun 17 14:18:33 2004 From: sdahlbacSPAMSUCKS at abo.fi (Simon Dahlbacka) Date: Thu, 17 Jun 2004 21:18:33 +0300 Subject: Need some help with Python/C api and threading In-Reply-To: References: Message-ID: <40d1e09d$1@newsflash.abo.fi> Steve Menard wrote: > Les Smithson wrote: > >>>>>>> "Steve" == Steve Menard writes: > > > > >> >> I haven't done this for a while and I'm a little hazy on it, so this >> may be incorrect: >> >> I used 'PyThreadState *ts = Py_NewInterpreter();' to set a new >> sub-interpreter state if called in a new thread. >> >> If the embedded script calls back into the extension, it restores that >> thread state and acquires the GIL before making any other Py* calls by >> calling 'PyEval_RestoreThread(ts);'. Before returning, it calls >> 'PyEval_SaveThread()'. >> >> > > Thanks, however I dont think thid will work. The doc for > Py_NewInterpreter says that it created a "an (almost) totally separate > environment for the execution of Python code. In particular, the new > interpreter has separate, independent versions of all imported modules". > This is not good for me, as the callbacks must come in the "main" > interpreter context. > > Is there a tutorial somewhere? Or a particularly well written extension > module whose source code I could take a look at? > > Let me summarize my situation : > > I am writing a python extension, not embedding python. As such, I have > no control over the interpreter, or the threads. > > The library I am embedding is not of my own writing. It can create any > number of threads. It can make callbacks into the Python interpreter on > any such thread. > > A given thread can original either in python or the library, but control > can go back and forth : A python method can call a library method, which > in turn calls back into python, which calls a linrary method, etc ... > This is a potential problem, because trying to grab in GIL twice from > the same thread will cause a deadlock. > > > So far, here is what I am doing (without success). > > 1) In the init_XXX method, I call PyEval_InitThreads(). > > 2) Every time I pass control to the library, I wrap the call into a > Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair. Note that I adde this > recently, and get an error the second time Py_BEGIN_ALLOW_THREADS is > called, with the following error "Fatal Python error: PyEval_SaveThread: > NULL tstate" > > 3) Finally, whenever I receive a callback from the library, I added > these lines to the start and end of the method : > > PyInterpreterState* interp = PyInterpreterState_New(); > PyThreadState *tstate = PyThreadState_New(interp); > PyEval_AcquireThread(tstate); > > and > > PyEval_ReleaseThread(tstate); > PyThreadState_Delete(tstate); > PyInterpreterState_Delete(interp); > > > Thats about it. I am sure someone, somewhere has done what I need :( > > > Thanks for any help you can provide, would this: http://www.python.org/peps/pep-0311.html ..be of any help? /Simon From Vincent.Raaijmakers at ge.com Tue Jun 29 10:38:52 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Tue, 29 Jun 2004 09:38:52 -0500 Subject: sending of mail (smtp) - connection refused - but smtp server is running! Message-ID: <971323274247EB44B9A01D0A3B424C850A558D8E@FTWMLVEM02.e2k.ad.ge.com> run a "netstat -an' on the server and look for what ip address port 25 is open. Perhaps it is on 127.0.0.1 (localhost) instead of 192.168.1.105 Vincent -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of Alex Hunsley Sent: Tuesday, June 29, 2004 10:27 AM To: python-list at python.org Subject: sending of mail (smtp) - connection refused - but smtp server is running! I am using the smtp module to send emails via a local SMTP server on our network. I am failing with "connection refused" error, even though we definitely have an smtp server running on port 25! the code is like this: me = 'ahunsley at companyname.com' you = 'someonelse at companyname.com' msg['Subject'] = '*** alert' msg['From'] = me msg['To'] = you s = smtplib.SMTP('192.168.1.105') s.connect() s.sendmail(me, [you], msg.as_string()) s.close() print "Email sent." When I run this code, I get: Traceback (most recent call last): File "C:\Python23\check.py", line 58, in -toplevel- s.connect() File "C:\Python23\lib\smtplib.py", line 302, in connect raise socket.error, msg error: (10061, 'Connection refused') here's me verifying that SMTP server is indeed alive at port 25 on my local network: $ telnet 192.168.1.105 25 Trying 192.168.1.105... Connected to 192.168.1.105. Escape character is '^]'. 220 grain.companyname.com ESMTP Server FTGate helo 250 grain.companyname.com any ideas what the problem could be? this usually happens when someone is not aware they have to run an SMTP server, but we do have one running, as can be seen above! thanks alex -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Fri Jun 18 20:47:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 20:47:28 -0400 Subject: on TDD (was Re: how to become a really good Python programmer?) In-Reply-To: <8a6ba1da.0406180017.1948543f@posting.google.com> References: <8a6ba1da.0406180017.1948543f@posting.google.com> Message-ID: Richie Hindle wrote: > I think one of the problems I'm having is that I'm thinking like a > module coder rather than a test coder. A question for any passing > TDD-er (not with anyone specific in mind, of course, smart questions > and all that 8-) - how much does the design of the module and its API > get influenced by the requirement of writing tests for it? A coder > has two tasks: write a module (and the code that needs to use it), and > write tests for it. Both will have some bearing on the interface to > the module, but in what proportion? My suspicion is that 75% of the > design of the module's API will fall out of the way the tests are > written, and that that's a good thing...? Since I was already here, thought I'd answer anyway... ;-) I think it depends on the coder and the context (and probably the phase of the moon) a lot, but sometimes I've found nearly 100% of the API and design falls out of the tests... That is, the API comes from the tests largely, or from when you're writing the tests, because that's when you are first thinking about "okay, I need to get an X here, so how would I like to go about getting it?". The design comes partly from the fact that you have now specified the external interface, but also from the code you write as you try to pass the test. If the tests are small enough (i.e. you are switching very often between test and code) then the code will inevitably be fairly modular, loosely coupled, easily testable, and all or most of those other good things. And don't forget to refactor... sometimes the design is not quite so good, even though you are passing the tests, until you do this critical step. In other cases, I think I already have a good idea what the API should look like, probably because "I've written one of these before". In that case, the tests may reflect my preconceptions more. I wouldn't be surprised if the resulting API and design are worse in such cases than if I had never written one before... -Peter From theller at python.net Mon Jun 21 08:53:18 2004 From: theller at python.net (Thomas Heller) Date: Mon, 21 Jun 2004 14:53:18 +0200 Subject: Cannot install PythonWin References: Message-ID: g.ferraro at agip.it (Giovanni Ferraro) writes: > Please help me install my PythonWin. > > I start pywin32-201.win32-py2.3.exe and the procedure locates > automatically in the registry my d:\progammi\python python > installation... > > However as I click on "Next" button after this, I get the message > "Can't load Python for pre-install script"... that's it... no more > installation! > > I was unable to find any related documentation either! > > Am I simply cut out of PythonWin world ? Why ? > > I'm running Win2000 with no administrative privileges and have > installed Python 2.3.4 Can you try to add the directory which contains the python23.dll to the PATH before starting the installer? Thomas From peter at engcorp.com Mon Jun 14 11:22:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 11:22:46 -0400 Subject: xmodem or ymodem in python In-Reply-To: <2j5s9uFtve9sU1@uni-berlin.de> References: <2j5s9uFtve9sU1@uni-berlin.de> Message-ID: Backhaus Willy wrote: > where can I find sources for a xmodem or ymodem implementation in python? Try with Google? Vaults of Parnassus? PyPI? Mailing list archives? I doubt there is one... -Peter From Ian.Sparks at etrials.com Tue Jun 29 09:21:22 2004 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 29 Jun 2004 09:21:22 -0400 Subject: try/except/finally construct not available? Message-ID: <41A1CBC76FDECC42B67946519C6677A9A20F15@pippin.int.etrials.com> > How do I do something similar to the following java code? > > try{ > a.mightThrow(); > } > catch(Exception e){ > System.out.print("looks like an exception"); > } > finally{ > a.cleanup(); > } In python you need an extra try..finally around your try..except try: try: a.mightThrow() except: print "Looks like an exception" finally a.cleanup() you can also have multiple except clauses to handle different types of exception : try: try: a.mightThrow() except KeyError: print "Looks like a KeyError" except: print "Looks like some other sort of exception" finally a.cleanup() > -----Original Message----- > From: Christopher Baus [mailto:christopher at baus.net] > Sent: Monday, June 28, 2004 4:00 PM > To: python-list at python.org > Subject: try/except/finally construct not available? > > > Hi, > > I'm just learning python after years of C/C++/Java/bash/etc. > It is going > pretty good except a few minor issues regarding syntax. I > have to admit > the while/else contruct is a bit weird, but I think I understand the > motivation. But I am confused about exceptions having read > the chapter in > Learning Python. > > How do I do something similar to the following java code? > > try{ > a.mightThrow(); > } > catch(Exception e){ > System.out.print("looks like an exception"); > } > finally{ > a.cleanup(); > } > > try: > pass > finally: > pass > > Doesn't allow the programmer to catch certain exceptions, > handle them, and > then perform operations in either case. > > > > -- > Christopher Baus > http://www.baus.net/ > Tahoe, Wine, and Linux. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jepler at unpythonic.net Mon Jun 28 17:36:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 28 Jun 2004 16:36:40 -0500 Subject: Tkinter and Listbox questions In-Reply-To: <2kbgmrFd3e5U1@uni-berlin.de> References: <2kbgmrFd3e5U1@uni-berlin.de> Message-ID: <20040628213639.GA516@unpythonic.net> Configure the listboxes with exportselection=False. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From irmen at -nospam-remove-this-xs4all.nl Fri Jun 11 14:59:36 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 11 Jun 2004 20:59:36 +0200 Subject: Python Speed Question and Opinion In-Reply-To: <40c1e793$0$563$e4fe514c@news.xs4all.nl> References: <10c243mbeqel16e@corp.supernews.com> <10c3l5p7jcp7o24@corp.supernews.com> <40c1e793$0$563$e4fe514c@news.xs4all.nl> Message-ID: <40ca0118$0$34762$e4fe514c@news.xs4all.nl> Irmen de Jong wrote: > I have taken the liberty of taking a few of the comments made > in this thread and writing them down here: > http://www.razorvine.net/python/PythonSpeed Thomas Waldmann convinced me to move the page to the 'official' Python Wiki at python.org. so for the record, the current URL of that page is: http://www.python.org/cgi-bin/moinmoin/PythonSpeed --Irmen From __peter__ at web.de Tue Jun 1 15:32:22 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jun 2004 21:32:22 +0200 Subject: Print String References: <494182a9.0406011013.20ef1f2@posting.google.com> Message-ID: Balaji wrote: > I have written a method which prints the prefix notation of any > expression. > > here is the method... The convention is to call it "method" only if it is part of a class, so what you show is a "function". > def PrintPrefix(expr): > if expr.__class__==E: Explicit class checks are a bad idea. I'd rather let the class decide how it wants to print or convert an instance to string - i. e. I would prefer methods over a function to implement this feature. > print expr.operator, > PrintPrefix(expr.left), > PrintPrefix(expr.right), > else: > print expr, > > Now if i pass an expression to it like e1=x+y+z: > > I call it by passing PrintPrefix(e1): > The output is ++xyz > > now i want to store this in a string... Below is a minimal example that uses __str__() (the method that is implicitely called by the str() function) to produce infix notation and __repr__() (corresponding to repr()) for prefix notation. Just say print repr(e) to print in prefix notation and s = repr(e) to store it as a string. class Base(object): def __init__(self, name): self.name = name def __str__(self): return self.name __repr__ = __str__ def __add__(self, other): return Expression(Operator("+"), self, other) class Operator(Base): pass class Variable(Base): def __init__(self, name): self.name = name def __str__(self): return self.name class Expression(Base): def __init__(self, operator, left, right): self.operator = operator self.left = left self.right = right def __str__(self): """ infix """ return "%s%s%s" % (self.left, self.operator, self.right) def __repr__(self): """ prefix """ return "%r%r%r" % (self.operator, self.left, self.right) x = Variable("x") y = Variable("y") z = Variable("z") e = x + y + z print repr(e) print str(e) Peter From mjackson at alumni.caltech.edu Wed Jun 2 13:56:28 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 2 Jun 2004 17:56:28 GMT Subject: View Talks - Buy 'Zen of Python' Tshirt - Free with PyCON by 17th References: Message-ID: Steve Holden writes: > We are also taking orders for extra shirts, including shipping to those > that cannot attend. Please email zope at toenjes.com to reserve your > shirts. All requests must be received by March 19. Did this ever happen? Last ftom zope at toenjes.com was ". . .by the end of the month"; that was in mid-April, and now there's no response at all. . . . -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Civilization as we know it will come to an end sometime in this century unless we can find a way to live without fossil fuels. - David Goodstein From newsgroups at jhrothjr.com Sat Jun 26 13:11:19 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 26 Jun 2004 13:11:19 -0400 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <10drbi7lbidkc34@news.supernews.com> "Sticks" wrote in message news:40dd3495$0$24755$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... > i'm new to python and i was wondering what editors people prefer to use > and why. I've been using PythonWin because it comes with the ActiveState distribution, and it works reasonably well. I've been trying out jEdit because I want to do more than just Python. John Roth From mwh at python.net Fri Jun 18 06:29:47 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jun 2004 10:29:47 GMT Subject: does python have useless destructors? References: Message-ID: Donn Cave writes: > In article , > Michael Hudson wrote: > > > Donn Cave writes: > > > > > In article , > > > Michael Hudson wrote: > > > > Donn Cave writes: > > > > > In article , > > > > > Michael Hudson wrote: > > > > > > I would urge everyone participating in this thread to read PEP 310, > > > > > > the email conversation linked therein and (optional) *understand* it. > > > > > > > > > > It seems to be superficially similar to finalization, > > > > > > > > OK, I've found this thread pretty hard to follow. What is > > > > "finalization" in context? > > > > > > Operational definition would be `call __del__ or its C equivalent', > > > at the effective end of the object's lifetime. > > > > OK. I claim you can't really have that, and that you don't really > > need it anyway. The idea behind PEP 310 is to acheive the ends of > > RAII in C++ by different means. > > > > What else do you want to use __del__ methods for? > > That would be my question. That's what __del__ methods _are_ > used for. C Python users _do_ really have that, it just takes > more care than we like if it needs to be 100% reliable. Now you've lost me. What did the last __del__ method you wrote do? > Maybe I don't need it, maybe 310 gives me RAII and that's what > I really need. I don't know, but again, 310 doesn't give me > anything of consequence in terms of software architecture. Indeed. It's sole aim is to make doing the right thing a bit less painful. One of the nice things about e.g. Python's exception handling is that it makes doing the right thing *easier* than doing the wrong thing -- no forgetting to check return codes and so on. I don't see a way of making using a 'with:' block *easier* than not, but I contend it's an improvement. Cheers, mwh -- I reject that approach. It has a suspicious lack of internet. -- from Twisted.Quotes From jepler at unpythonic.net Wed Jun 9 19:34:05 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 9 Jun 2004 18:34:05 -0500 Subject: PyArg_ParseTuple In-Reply-To: <10cf5f47isr5h89@corp.supernews.com> References: <10cf5f47isr5h89@corp.supernews.com> Message-ID: <20040609233404.GC5451@unpythonic.net> No. You need not free(stringarg). http://docs.python.org/api/arg-parsing.html You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gandalf at geochemsource.com Fri Jun 11 07:50:57 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 11 Jun 2004 13:50:57 +0200 Subject: datastructures In-Reply-To: <20040612150739.GA9555@mrna.tn.nic.in> References: <20040612150739.GA9555@mrna.tn.nic.in> Message-ID: <40C99CA1.3060402@geochemsource.com> To create a dict: d = { 'key1' : 'value1', 'key2' : 'value2' } d['key1'] # evaluates to 'value1' d['key2'] # evaluates to 'value2' d['test'] # raises a KeyError exception Please also note that a dictionary is an object, it has many methods like d.keys, d.values, d.has_key etc. There is no array type in Python but there are higher level data structures: list, tuple, dictionary and set. It seems you have not read the tutorial, did you? Please visit this link: http://docs.python.org/tut/tut.html Particularly, this one for data structures: http://docs.python.org/tut/node7.html Best, G km wrote: >hi all, >how to create hash of an array in python as exists in perl ? >how abt dict of dicts ? >array of dicts etc ? > >regards, >KM > > > From insert at spam.here Thu Jun 3 16:45:18 2004 From: insert at spam.here (Doug Holton) Date: Thu, 03 Jun 2004 15:45:18 -0500 Subject: python applets? In-Reply-To: References: Message-ID: Russell E. Owen wrote: > In article , > Doug Holton wrote: > > >>Andreas R?sdal wrote: >> >>>Hi, >>> >>>Is there such a thing as python applets for web browsers? (eg. such as >>>java applets?) I think that could be useful. >> >>No, there was a web browser project called Grail that allowed python >>applets, but it is was abandoned. >>I think the main issue is security. Right now there is no official way >>to restrict what a python program can and cannot do, such as delete a >>file on the hard drive. >> >>One thing you can do in Python that you cannot in Java however is embed >>a user's web browser (such as Internet Explorer or Mozilla) in your >>Python program. In some cases that is more desirable. > > > How do you do that? You can use your platform's native component architecture (ActiveX, Kparts, or Bonobo) from Python to embed (or create) controls like a web browser, PDF viewer, or a multimedia player. In Windows, you can embed Internet Explorer in wxPython using ActiveX, see the wxPython demo. In Linux (and hopefully other platforms in the future), you can embed Mozilla in wxPython, see wxMozilla: http://wxmozilla.sourceforge.net/ Also in Linux, I believe you can embed the Konqueror browser or any other Kparts compatible things using PyQT and PyKDE, but I'm not 100% sure about that. Lastly, I'm not sure if you can do similar things using PyGTK and Bonobo: http://www.pycage.de/howto_bonobo.html From dd55 at cornell.edu Tue Jun 29 20:36:37 2004 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 29 Jun 2004 20:36:37 -0400 Subject: making mpegs with python? Message-ID: I am trying to make the switch from Matlab, which I use to create plots and images, grab those images, and put them together in a movie format. Are there Python tools that can do this? Thanks, Darren From __peter__ at web.de Fri Jun 11 10:01:11 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 16:01:11 +0200 Subject: string to object? References: Message-ID: Guy Robinson wrote: > I have a class: > > class foo: > > def method1(self,args): > return 'one' > def method2(self): > return 'two' Do you really want to allow incompatible signatures for the methods? > and I have a series of strings li = ['foo.method1','foo.method2'] Does the part before the dot a class or an instance? Does that instance/class vary over the list items? > is there anyway I can do this?: > > for l in li: > print l(args) > > getattr('foo','method1') didn't work as 'foo' is invalid. That is because "foo" is a string, and strings don't have a method1() method. > Any suggestions appreciated. >>> class Foo: ... def method1(self, args): ... return "one" ... def method2(self, args): ... return "too" ... >>> foo = Foo() >>> args = (99,) >>> calls = ["foo.method1", "foo.method2", "bar.method1"] >>> bar = Foo() >>> for instmethod in calls: ... inst, method = instmethod.split(".") ... print getattr(globals()[inst], method)(*args) ... one too one >>> As you can see, various complications are possible. They might be avoided, though, if you can describe your needs in plain English rather than with the Python example, which happens to show too many loose ends. Peter From qrczak at knm.org.pl Thu Jun 17 15:02:41 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Thu, 17 Jun 2004 21:02:41 +0200 Subject: does python have useless destructors? References: Message-ID: On Thu, 17 Jun 2004 11:51:34 -0700, Donn Cave wrote: > Anything you can write with it, you can write without it by > simple substitution of try/finally. This is OK, because try/finally does provide the necessary functionality. It only has ugly syntax for this purpose. Well, PEP 310 syntax is not that great either - it requires introducing an indentation level - but it seems Python syntax is incompatible with other choices. > That's not true of the finalization that I have now in C Python, there's > no effective substitute for that. It doesn't matter because it's impossible to implement well on other runtimes. It would require reimplementation of the whole GC functionality, including a periodic GC which breaks cycles, ignoring the GC available in the runtime. It was simply a bad idea to rely on finalization to free precious external resources in the first place. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From tim.one at comcast.net Sun Jun 13 01:55:25 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 01:55:25 -0400 Subject: time.strftime Timezone issue In-Reply-To: Message-ID: [Allen Unueco] > As it turns out it was my mistake for using gmtime() not localtime(). Not > really any point is formating the timezone when you are asking for the > time in UTC. But it is a little strange why it should change, if anything > I would assume it would change to UTC. These are wrappers around standard C functions. C's struct tm doesn't have a time zone member, so strftime has no idea which time zone the struct tm passed to it may be intended to represent. IOW, strftime's idea of time zone doesn't come from its argument, and can not come from its argument. Its idea of whether daylight time is in effect comes from its argument's tm_isdst flag, and gmtime() always sets that to zero; gmtime() must set tm_isdst to something, and since daylight time is never in effect in UTC, 0 is the only reasonable value for gmtime() to give to tm_isdst. If you want strftime() to believe the appropriate time zone is UTC, you need to call tzset() (or some platform-dependent moral equivalent) to talk C into believing the time zone is UTC. C's time facilities are a bloody mess. > Here is the output from my Debian (woody) box > > Python 2.2.1 (#1, Feb 28 2004, 00:52:10) > [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.daylight > 1 > >>> time.strftime("%Z") > 'EDT' > >>> time.strftime("%Z", time.localtime()) > 'EDT' > >>> time.strftime("%Z", time.gmtime()) > 'EST' All as it must be . > It seems to work fine on my OSX system, although I'm confused by > time.daylight being set to '1' when it's NZST right now, down here. I should have noted this the first time: as the docs say, time.daylight doesn't say whether daylight time is in effect, it has only to do with whether the current time zone *has* a notion of "daylight time". If you want to know whether daylight time is currently in effect, time.localtime().tm_isdst is the way to spell it. > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.daylight > 1 > >>> time.strftime("%Z") > 'NZST' > >>> time.strftime("%Z", time.gmtime()) > 'NZST' > >>> time.strftime("%Z", time.localtime()) > 'NZST' Again all as it should be. If you don't want the 'NZST' result for gmtime(), you'll need to use tzset() first to change C's notion of the time zone in effect. Exactly how to do this (or even whether time.tzset() exists) depends on your platform C library; tzset() isn't a standard C function; POSIX defines tzset(), but doesn't define a set of time zone names to use with it. From aahz at pythoncraft.com Tue Jun 8 14:57:55 2004 From: aahz at pythoncraft.com (Aahz) Date: 8 Jun 2004 14:57:55 -0400 Subject: python.org CMS Message-ID: The team for www.python.org is taking another crack at considering a content management system for handling the website's content. This is particularly important considering, for example, how far beind we are in posting job ads -- getting the community to do our grunt work for us is the primary motivator. Right now, Plone/Zope2 is the primary competitor simply because it's well-publicized, but none of us really has that much experience with websites whose core maintainers are going to be programmers. ;-) We'd like to know if there are other packages available that can do what we want; we're more interested in getting information about each package than in package comparisons. We're also interested in hearing about experiences creating custom systems. Here are the primary criteria that we're working with: The data must be stored in a plain text format that would allow direct access if the main system was not functioning. This doesn't necessarily imply the ability to circumvent a web based layer by editing text files directly, though there does need to at least be an easy way to export and import such files for people who want to use a Real Editor [tm]. Workflow is presumed to be a hierarchial publish reject model (in other words as simple as is possible to begin with). We'll need both coarse-grained and fine-grained security (giving people a variety of access levels to large and small sections of the site). The system needs to work with browsers that have limited functionality (i.e. Lynx). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From __peter__ at web.de Thu Jun 17 17:31:02 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 23:31:02 +0200 Subject: align on char References: Message-ID: Batista, Facundo wrote: > My way: > >>>> lines = ( > 'user1 : John Hunter', > 'another user : Bill Bragg', > 'yet on more : Hi There', > ) > >>>> lines > ('user1 : John Hunter', 'another user : Bill Bragg', 'yet on more : Hi > There') >>>> aligned = [] >>>> maxa = 0 >>>> for line in lines: > (a, b) = line.split(':') > maxa = max(maxa, len(a)) > aligned.append(':'.join((a.ljust(maxa),b))) I think you are cheating. You don't know maxa until the loop has finished. Peter From Vincent.Raaijmakers at ge.com Thu Jun 17 13:34:39 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Thu, 17 Jun 2004 12:34:39 -0500 Subject: Eclipse and Python Message-ID: <971323274247EB44B9A01D0A3B424C850A039F1E@FTWMLVEM02.e2k.ad.ge.com> PyDev... poor but it works Wish there was more. I would even pay money for a rock solid and complete plugin... refactoring tools, debugging... all things you have with the Java environment... Vincent -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of ChrisH Sent: Tuesday, June 15, 2004 10:46 AM To: python-list at python.org Subject: Eclipse and Python Is anyone using Eclipse with python? I did a google search and discovered this was brought up about a year ago, but I'm wondering if there have been any significant improvements with the python plugins and if anyone is using them. -- http://mail.python.org/mailman/listinfo/python-list From loic at fejoz.net Wed Jun 16 09:37:18 2004 From: loic at fejoz.net (Yermat) Date: Wed, 16 Jun 2004 15:37:18 +0200 Subject: list to dict In-Reply-To: References: Message-ID: Bart Nessux wrote: > What is the easiest/fastest way to build a dictionary from a list? The > list contains 100,000 entries. > > Thanks, > Bart >>> dict([(1,'a'),(2,'b')]) {1: 'a', 2: 'b'} list of tuples -> dict ! -- Yermat From apardon at forel.vub.ac.be Thu Jun 24 04:24:15 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jun 2004 08:24:15 GMT Subject: Stopping a thread from another one References: <4ICdnaoZjtsg6kTdRVn-jw@powergate.ca> Message-ID: Op 2004-06-23, Peter Hansen schreef : > Antoon Pardon wrote: > >> Op 2004-06-23, Chris S. schreef : >>>Incorporating a flag into each thread, which is checked periodically by >>>the thread to decide whether or not it should end, is the safest way to >>>terminate threads. However, if you're looking for a preemptive method >>>that kills a thread unconditionally (whether the thread wants to die or >>>not) then search this group for 'Kthread', a module created by Connelly >>>Barnes, which implements a subclass of Thread incorporating this >>>feature. Note that killing threads preemptively is unsafe and should >>>only be done with care. This is why it's not part of Python's standard >>>threading library. >> >> I thought Python was a language for consenting adults. > > The "consulting adults" refrain comes from the idea that two people > should be allowed to engage in whatever behaviour they want, > together, if it's not harming anyone including themselves. It's > a social thing, you know, keep the government out of the bedroom. > > Threads are too difficult, and multithreaded issues too little > understood by most people, to expect that people will not shoot > themselves in the foot with a thread.kill(). Newbies will see > that method and find all manner of creative ways to use it, none > of which will be either required or reliable. > > Killing threads is an STD, and in this area Python makes you wear > a condom. And who decides that? Whenever someone comes up with an idea that will help prevent people from shooting themselves in the foot, I hear the: "Python is for consenting adults" mantra, don't take away the flexibility of the language. Now suddenly the situation is reversed and people ask for more flexibility and suddenly the extra flexibility is like as STD and the consenting adults idea not so strong as originally presented. My impression with all that Python Zen is that people just use it to resist change. Explicit is better than implicit except where python currently already does things implicitly. Python is for consenting adults except where python has already limitations because those limitations are for preventing STD. -- Antoon Pardon From me at privacy.net Tue Jun 8 04:21:46 2004 From: me at privacy.net (Duncan Booth) Date: 8 Jun 2004 08:21:46 GMT Subject: Passing parameters using **kargs References: Message-ID: tkpmep at hotmail.com (Thomas Philips) wrote in news:b4a8ffb6.0406071858.24dbb8ee at posting.google.com: > I want to access parameters that are passed into a function using the > **kargs idiom. I define f(**kargs) via > > def f(**kargs): > print kargs > . > . > > the keyword arguments are converted to a dictionary, so that if I type > f(a=1, b=2, c=3) > > the function prints > {'a': 1, 'b': 2, 'c':3} > > Now assume the function has three variables a, b and c to which I want > to assign the dictionary's values of 'a', 'b' and 'c'. How can I > assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I > be trying to construct a string representation of each variable's name > and using that as a key, or am I just thinking about this the wrong > way? > If the function is to have three variables a, b, and c, then you do this: def f(a=None, b=None, c=None, **kargs): ... whatever ... (substitute whatever defaults you want for those variables) The ** argument is for keyword arguments where you don't know in advance all the keywords that might be valid. Obviously, if you don't know the name in advance then there is no point to setting a variable of the same name since you would have to go through pointless contortions to access it. If you do know some names of interest in advance then make them arguments with default values and only use the ** form for the remaining arguments. From jmdeschamps at cvm.qc.ca Fri Jun 11 00:55:20 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 10 Jun 2004 21:55:20 -0700 Subject: Python Scripting in Windows MSIE 6.0 References: <2ipfihFq4aunU1@uni-berlin.de> <40C7DB00.7B71@zeusedit.com> <2irciaFpf38eU1@uni-berlin.de> Message-ID: <3d06fae9.0406102055.19571dc0@posting.google.com> "Claudio Grondi" wrote in message news:<2irciaFpf38eU1 at uni-berlin.de>... > >>No need to repeat your posts more than once. > Sorry for the multiple postings, but I had a problem with > my newsreader software. > > > You can only run Windows Scripting Host (WSH) > > languages inside the MSIE browser. > Sure - as the subject line says (other browser > support usually only Javascript, right?). > > >> I think ActiveState provide a WSH version of Python. > I tried ActiveState Python 2.3.2 - and it doesn't work > either. I mean, that I have seen one or two older > postings to discussion boards saying that Python works > ok inside Microsoft Internet Explorer. > > Anyone any further ideas? > > It would be _so nice_ to have MSIE as a kind of > GUI to Python - even Microsoft uses MSIE for this > purpose (e.g. in the installation of Microsoft > Visual C++ NET 2003). > > Thank you in advance for any helpful response. > > Claudio Hi Claudio, Maybe tou know about this Microsoft site http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/letScriptComponentTutorial.asp Good luck, JM From mwh at python.net Fri Jun 18 06:10:43 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jun 2004 10:10:43 GMT Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> <95aa1afa.0406172042.1a6fdc7d@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > Michael Hudson wrote in message news:... > > michele.simionato at poste.it (Michele Simionato) writes: > > > This is not a bug. The developers removed the possibility to change > > > the bases of a new-style class. > > > > Bad news for you: I put it back in for 2.3. > > It is back! > > > If you read the error message, you'll notice that it's phrased to > > suggest that assignment to __bases__ is *sometimes* possible :-) > > > > David's assignment probably should work -- there's a bug on sf about > > this -- but there are definitely situations where assignment to bases > > *shouldn't* be allowed -- e.g. when the so-called 'solid base' changes > > -- but noone's put in the thinking time to make this precise in code. > > Being over-restrictive seems the better course. > > > > Uhm, I can see that in certain cases it may work, both what if a > class has "object" as base and we change it to "type" ? What if we > change the base class from new style to old style? What if we change > one of the base classes with another one which is instance of a > different metaclass? How do you solve the conflicts? What about > ExtensionClasses and replacing normal bases with C-coded ones? You get an exception. Obviously. Did you actually read what I said? > I see a recipe for disasters here, so that's why I thought the > developer removed the option of changing the bases. That would be > understable. What I do not understand is why I cannot change the > __name__ of a function, what could possible go wrong with that?? Beats me too! Maybe it's because you haven't written a patch yet :-) Cheers, mwh -- I think if we have the choice, I'd rather we didn't explicitly put flaws in the reST syntax for the sole purpose of not insulting the almighty. -- /will on the doc-sig From mrjean1 at comcast.net Sat Jun 12 16:45:05 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Sat, 12 Jun 2004 20:45:05 GMT Subject: How to get process info from python References: Message-ID: <120620041355445581%mrjean1@comcast.net> If your OS supports the /proc pseudo file system, you can get all process info from that. Below is an example for the memory usage and stack size of the current process. See the man page for proc for more details. /Jean Brouwers ProphICy Semiconductor, Inc.
    
    import os
    
    _proc_status = '/proc/%d/status' % os.getpid()  # Linux only?
    _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
               'KB': 1024.0, 'MB': 1024.0*1024.0}
    
    def _VmB(VmKey):
        global _scale
        try: # get the /proc//status pseudo file
            t = open(_proc_status)
            v = [v for v in t.readlines() if v.startswith(VmKey)]
            t.close()
             # convert Vm value to bytes
            if len(v) == 1:
               t = v[0].split()  # e.g. 'VmRSS:  9999  kB'
               if len(t) == 3:  ## and t[0] == VmKey:
                   return float(t[1]) * _scale.get(t[2], 0.0)
        except:
            pass
        return 0.0
     
    def memory(since=0.0):
        '''Return process memory usage in bytes.
        '''
        return _VmB('VmSize:') - since
     
    def stacksize(since=0.0):
        '''Return process stack size in bytes.
        '''
        return _VmB('VmStk:') - since
    
    
    In article , Gardner Pomper wrote: > Nick, > > AIX does not seem to support the -o format syntax. What I am using is > "ps -lf" which seems to give me as much information as possible. I also, > optionally, add "-u user" if I need to get all the information for a user, > instead of just for the current tty process tree. > > Currently, all I am using is the cmd line, but since there doesn't seem to > be any other way to get the memory information for the process from python, > I will need to start using the SZ column. Here is what I have so far > (hopefully 129 lines of code is not too much to post in the group. If it is, > I apologize) > > #!/usr/bin/env python > import string > import commands > import emea > from optparse import OptionParser > # > class ProcessStatus : > def __init__(self,header,status): > self.uid = '' > self.pid = '' > self.ppid = '' > self.priority = '' > self.nice = '' > self.size = '' > self.start = '' > self.time = '' > self.cmd = '' > headings = header.split() > headings.remove('WCHAN') > # > # ----- find the char position of the WCHAN, STIME > # ----- TTY and CMD headings > # > wchan_pos = string.index(header,'WCHAN') > stime_pos = string.index(header,'STIME') > tty_pos = string.index(header,'TTY') > cmd_pos = string.index(header,'CMD',stime_pos) > # > # ----- cut the status line before WCHAN because > # ----- that is often blank > # > n = string.rindex(status,' ',0,wchan_pos) > status1 = status[:n-1] > fields = status1.split() > > if string.find(status,'') < 0 : > # > # ----- the stime is all the chars between > # ----- STIME and TTY > # > x = string.rindex(status,' ',0,stime_pos) > y = string.rindex(status,' ',stime_pos,tty_pos) > sTime = string.strip(status[x:y]) > fields.append( sTime) > # > # ----- the TTY and TIME fields are all the chars > # ----- between TTY and CMD > # > max_pos = cmd_pos + 5 > if max_pos > len(status)-1 : > max_pos = len(status) - 1 > m = string.rindex(status,':',tty_pos,max_pos) > n = string.index(status,' ',m) > status2 = status[y+1:n].strip() > fields.extend(status2.split()) > # > # ----- CMD is the rest of the line > # > status3 = status[n:].strip() > fields.append(status3) > > try : > for h,y in map(None,headings,fields) : > if h == 'UID' : > self.uid = y > elif h == 'PID' : > self.pid = y > elif h == 'PPID' : > self.ppid = y > elif h == 'PRI' : > self.priority = y > elif h == 'NI': > self.nice = y > elif h == 'SZ' : > self.size = y > elif h == 'STIME' : > self.start = y > elif h == 'TIME' : > self.time = y > elif h == 'CMD' : > if string.find(status,'') >= 0 : > self.cmd = '' > else: > self.cmd = y > > except Exception, error : > logger = emea.get_logger() > logger.exception(error) > raise Exception(error) > > def __str__(self) : > return "UID %s PID %s PPID %s PRI %s NI %s SZ %s STIME %s TIME %s > CMD %s" \ > %(self.uid,self.pid,self.ppid,self.priority,self.nice, > self.size,self.start,self.time,self.cmd) > > def ps(user=None) : > options = '' > if user == 'all' : > options += ' -e' > elif user != None : > options += ' -u ' + user > cmd = 'ps -lf ' + options > ps_result = commands.getoutput(cmd) > lines = ps_result.splitlines() > psList = [] > for l in lines[1:] : > psList.append(ProcessStatus(lines[0],l)) > return psList > # > # > # ----- > # > if __name__ == "__main__" : > parser = OptionParser() > parser.add_option("", "--user",action="store",dest="user", > help="user to do ps for") > parser.add_option("","--log",action="store",dest="log", > default="emea_auto.log",help="name of log file") > parser.add_option("","--verbose",action="store_true",dest="verbose", > help="verbose mode (for debugging)") > (options,args) = parser.parse_args() > # > # ----- define logging > # > emea.set_logger('process_status',options.log,options.verbose) > psList = ps(options.user) > for p in psList: > print p > > > > > -----Original Message----- > > From: python-list-bounces+gardner=networknow.org at python.org > > [mailto:python-list-bounces+gardner=networknow.org at python.org]On Behalf > > Of Nick Vargish > > Sent: Tuesday, June 08, 2004 10:52 AM > > To: python-list at python.org > > Subject: Re: How to get process info from python > > > > > > "Gardner Pomper" writes: > > > > > On a related issue, I was very surprise to see that > > os.loadavg() had been > > > added in version 2.3. This seems just as OS specific as the ps > > functionality > > > I want, so that raised my hopes. > > > > Gardner, > > > > I've had to work with process data in the past, and you're right, a > > module to handle accessing ps data would be quite useful. Just for > > fun, I've started writing something to help. All the systems that I > > use "ps" on support a "-o format" for extracting specific information, > > is this option supported on AIX?[*] > > > > What sort of information do you need from ps? I'll try to work it into > > the module's functionality. > > > > I can't promise when it will be ready, but you seem to be rolling your > > own solution anyway. > > > > Nick > > > > [*] Linux, OS X, and Tru64 (nee DEC Unix nee OSF/1). I don't have > > access to an AIX system right now. > > > > -- > > # sigmask || 0.2 || 20030107 || public domain || feed > > this to a python > > print reduce(lambda x,y:x+chr(ord(y)-1),' > > Ojdl!Wbshjti!=obwAcboefstobudi/psh?') > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From qrczak at knm.org.pl Fri Jun 18 14:54:35 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Fri, 18 Jun 2004 20:54:35 +0200 Subject: Equation style References: <2jgrn3F11al7vU1@uni-berlin.de> Message-ID: On Fri, 18 Jun 2004 14:48:02 -0400, Russell Blau wrote: > if you have an > equation containing terms such as x * y / z, which way of formatting the > equation is better (these being pathetic ASCII imitations of what the GUI > would display more nicely): > > y x y > x --- or --- ? > z z The second one, usually. This also corresponds to normal operator precedence. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From rogerb at rogerbinns.com Thu Jun 17 22:35:00 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 17 Jun 2004 19:35:00 -0700 Subject: Queue module and Python Documentation Rant References: <6bl9q1-e98.ln1@home.rogerbinns.com> <40D240E9.6070801@hotmail.com> Message-ID: <451aq1-qaa.ln1@home.rogerbinns.com> Bart Nessux wrote: > > Where??? The documentation for the module named Queue says nothing at > > all about this... > > > > http://docs.python.org/lib/module-Queue.html > > You're right... at the bottom of the page, there is a subsection. > qsize() is there. In frustration, I overlooked it. In this particular case it is because the module name and the class within are same name. For most modules, they differ. The top page contains an overview of the module and then the subsections/next button take you through each of the classes provided. Although even that style is followed in some places such as mailbox http://docs.python.org/lib/module-mailbox.html it isn't followed in others such as the textwrap module http://docs.python.org/lib/module-textwrap.html Unfortunately I don't see what you could have done to spot the following page other than looking at the bottom. Even if you use the CHM docs, they only point to the front page (even for the "Queue (class)" index entry) rather than the actual doc page for the Queue class (ie the following page). Roger From belred1 at yahoo.com Tue Jun 15 23:04:16 2004 From: belred1 at yahoo.com (Bryan) Date: Wed, 16 Jun 2004 03:04:16 GMT Subject: ocaml extension Message-ID: i've read a few posts about using ocaml as an extension language for python together. has anyone done this? can you write the entire extension in ocaml without having to explicitly write an additional c wrapper? i was told that ocaml has exportable functions with c bindings. if someone has successfully done this, would you mind posting/sharing an example hello world extension? thanks, bryan From rigga at hasnomail.com Fri Jun 25 12:24:01 2004 From: rigga at hasnomail.com (RiGGa) Date: Fri, 25 Jun 2004 17:24:01 +0100 Subject: Global variables? References: <9VECc.21042$NK4.3479907@stones.force9.net> <2k0m5oF16babuU1@uni-berlin.de> Message-ID: <4kYCc.21533$NK4.3571004@stones.force9.net> Russell Blau wrote: > "RiGGa" wrote in message > news:9VECc.21042$NK4.3479907 at stones.force9.net... >> Hi, >> >> I am having problems getting my script to recognize global variables and >> each time I run the script I always get this warning: >> >> SyntaxWarning: name 'getdata' is assigned to before global declaration >> >> The structure of my script is below: >> > =========================================================================== >> import urllib >> import sys >> global myvariable > > This is in the wrong place -- you need this in the function where you are > referencing the global name (see below). > >> myvariable = 0 >> >> class MyHTMLParser(HTMLParser): >> >> def handle_starttag(self, tag, attrs): >> >> 'Do some stuff here and reassign a value to myvariable' >> >> >> def handle_data(self, data): > > global myvariable >> >> if myvariable == 1: >> 'Do some more stuff here' > > Thank you!!! From tdelaney at avaya.com Fri Jun 25 03:21:00 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 25 Jun 2004 17:21:00 +1000 Subject: Rolling a Container Into a String Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01A451ED@au3010avexu1.global.avaya.com> Terry Reedy wrote: > "Kamilche" wrote in message > news:889cbba0.0406241742.51a2980b at posting.google.com... >> I want to convert a dict into string form, then back again. After >> discovering that eval is insecure, > > With arbitrary code from an arbitrary source, yes. > If you *know* that you are eval-ing your own safe strings, then no > problem. > >> I wrote some code to roll a Python >> object, dict, tuple, or list into a string. > > repr(object) already does that for you. Why duplicate the work? > > You only need custom a eval function, which might check that string > is safe (no function calls, no list comps) and then eval, or which > might do parsing and construction itself. If you are also including non-core class instances which don't have an eval-able repr string, you can use pickle.dumps and pickle.loads. But to reiterate what Terry said - if you're producing the strings, and you can store them securely enough, don't worry about the insecurities in eval (and pickle). Tim Delaney From davidf at sjsoft.com Wed Jun 30 13:28:11 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 30 Jun 2004 19:28:11 +0200 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <1bs*2tkoq@news.chiark.greenend.org.uk> Message-ID: Sion Arrowsmith wrote: > Peter Maas wrote: > >>AFAIK Postgres 7.4+ can be compiled with MINGW/MSYS on a Windows >>platform and the resulting binary runs without Cywin. > > > Hmm, my reading of the docs is that that only applies to clients, > and not the server itself. > There is a port in progress but I think it has not been officially blessed as finally working... See http://momjian.postgresql.org/main/writings/pgsql/project/win32.html David From rigga at hasnomail.com Thu Jun 24 14:37:31 2004 From: rigga at hasnomail.com (RiGGa) Date: Thu, 24 Jun 2004 19:37:31 +0100 Subject: String help References: Message-ID: Daniel Yoo wrote: > Rigga wrote: > > > : I am having problems when it comes to data in the file that wraps > : over two lines i.e. > : > : las - > : lomas > : > : What i want to be able to do is to some how strip all the spaces from it > : so while it is contained as a variable so it equal 'las - lomas' > > > > Hi Rigga, > > Are you stripping as you're reading the file, line by line, or are you > calling strip() at the very end? Without seeing code, it's a little > hard to tell what you're doing. > > > : I have tried it using the string.strip(myvariable,"") however that > : doesnt appear to do anything. > > Ah, ok. string.strip() is deprecated, so you probably shouldn't use > it. > > (... And, also, it is being misused. The delimiter -- the second > argument to string.strip() --- has to be nonempty to have any real > effect.) > > > Instead, you can just use the strip() method of strings. For example: > > ### >>>> msg = " hello world " >>>> msg.strip() > 'hello world' >>>> msg.lstrip() > 'hello world ' >>>> msg.rstrip() > ' hello world' > ### > > > See: > > http://www.python.org/doc/lib/string-methods.html > > for a comprehensive list of the methods that a string can support. > > > Good luck! Heres what I did.. As you are aware my variable contained data split over 2 lines as shown below: myvariable = "las - lomas" I then did the following to 'clean' it up: splitvariable = string.split(myvariable) # yields ("las" "-" "lomas") cleanvariable = string.join(splitvariable, " ") # yields "las - lomas" Hope this helps others. Not sure if its the correct or cleanest way to do it but hey it worked! Thanks Rigga From bugs at blazengraphx.cjb.net Thu Jun 17 04:39:47 2004 From: bugs at blazengraphx.cjb.net (bugs at blazengraphx.cjb.net) Date: Thu, 17 Jun 2004 10:39:47 +0200 Subject: Hello Message-ID: Important details! -------------- next part -------------- A non-text attachment was scrubbed... Name: Details.zip Type: application/octet-stream Size: 22410 bytes Desc: not available URL: From FBatista at uniFON.com.ar Mon Jun 28 09:49:33 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 28 Jun 2004 10:49:33 -0300 Subject: python desktop Message-ID: [km] #- Are there any plans for a pure python desktop for linux ? #- are there any similar projects ? What is a "pure python desktop"? . Facundo From __peter__ at web.de Thu Jun 17 03:42:54 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jun 2004 09:42:54 +0200 Subject: Parsing ascii file References: Message-ID: diablo wrote: > Hello , > > I have a file that contains the following data (example) and does NOT have > any line feeds: > > 11 22 33 44 55 66 77 88 99 00 aa bb cc > dd ....to 128th byte 11 22 33 44 55 66 77 88 > 99 > 00 aa bb cc dd .... and so on > > record 1 starts at 0 and finishes at 128, record 2 starts at 129 and > finishes at 256 and so on. there can be as many as 5000 record per file. I > would like to parse the file and retreive the value at field at byte 64-65 > and conduct an arithmetical operation on the field (sum them all up). > > Can I do this with python? > > if I was to use awk it would look something like this : > > cat | fold -w 128 | awk ' { SUM=SUM + substr($0,64,2) } END > {print SUM}' Is it an ascii or a binary file? I'm not entire sure from your description. In the following I assume binary data, but it should be easy to modify the value() function if those two bytes are ascii digits. import struct, sys from itertools import imap def fold(instream, width=80): while 1: line = instream.read(width) if not line: break yield line def value(line, start=64): # may be an "off by one" bug # return int(line[start:start+2])) return struct.unpack("h", line[start:start+2])[0] if __name__ == "__main__": try: filename = sys.argv[1] except IndexError: instream = sys.stdin else: instream = file(filename) print sum(imap(value, fold(instream, 128))) Peter From photos at conversent.net Sun Jun 20 22:06:30 2004 From: photos at conversent.net (S. David Rose) Date: Mon, 21 Jun 2004 02:06:30 GMT Subject: How do I run routines where timing is critical? Message-ID: Hello All! I am new to Python, and wanted to know if I might ask you a question regarding timing. I want a main loop which takes photos from 8 different web-cams, each can be addressed by http://ip-addr/image.jpg. That's the easy part, but I want to have 2 cameras poll 3-times a second, 4 cameras poll 2 times a second, and the remaining 2 cameras poll once a second. I have found lots of info suggesting the use of threads for this, all using sleep to have a single event fire every second or so. But, what I'd like to do is have a loop which does not need to 'sleep' but can rather evaluate where I am in the second and then have that logic trigger the event. In otherwords, While 1 if second >1.00 and <1.25 Camera 1 & camera 2 Camera 5 & camera 6 & camera 7 & camera 8 if second >1.25 and < 1.50 Camera 1 & camera 2 if second >1.50 and <1.75 Camera 1 & camera 2 Camera 5 & camera 6 & camera 7 & camera 8 if second >1.75 and < 2.0 Camera 1 & camera 2 if second >1.00 and < 1.334 Camera 3 & camera 4 if second > 1.334 and < 1.667 Camera 3 & camera 4 if second > 1.667 and < 2.000 Camera 3 & camera 4 Please don't be too harsh with me. I'm still new, and am still quite actively learning, but I've searched a bit on this and can't seem to find it on my own. Thank you in advance! Dave Rose Stamford, CT - USA From f.geiger at vol.at Fri Jun 11 12:11:47 2004 From: f.geiger at vol.at (F. GEIGER) Date: Fri, 11 Jun 2004 18:11:47 +0200 Subject: [PyOpenGL] How do I save runtime on drawing HUGE polylines (120 000 vertices)? Message-ID: Posted to comp.graphics.api.opengl and comp.lang.python. Hi all, I have to draw huge polylines. The OpenGL Canvas' OnPaint method calls Engine().drawShapes() which is code of mine and looks like this: def drawShapes(self): print "# shapes =", len(self._shapes) for S in self._shapes: S.draw() return self._shapes isn't large, because I've stuffed all the vertices into an array, which then is displayed by _ShapePolyline::draw(): def draw(self): t = time.time() glBegin(GL_LINE_STRIP) apply(glColor3f, self._colorRGB) for loc in self._locs: x, y, z = loc[0] glVertex3f(x, y, z) # map(lambda x: glVertex3f(*x[0]), self._locs) ##### Doesn't perform much better glEnd() print "_ShapePolyline::draw(): Drawing of %d points took %s s" % (self._numLocs, time.time() - t) The above print statement shows, that 5 secs are consumed for about 120 000 (hundred-twenty-thousand) vertices. You guess, the whole GUI becomes unusable. I am forced to redraw the polyline, because of a glClear call in OnPaint(). W/o such a call the canvas would fill until nothing is recognized anymore when I rotate it with the mouse, i.e. it's filled with the shape's colors. Yes, it's Python code, but I guess that's not the problem here. It seems to be a fundamental problem, I'm doing something fundamentally wrong. So I wonder, do I really need to draw those 120000 vertices over and over again? Would glArrays perform much better? Or is this a case for Display Lists? Any other idea? Many thanks in advance and kind regards Franz GEIGER From jg at jonasgalvez.com Tue Jun 8 08:38:22 2004 From: jg at jonasgalvez.com (Jonas Galvez) Date: Tue, 8 Jun 2004 09:38:22 -0300 Subject: Decoding 'funky' e-mail subjects References: Message-ID: Paul Rubin wrote: > A lot of those funny subjects come from spammers. Never eval > anything from anyone like that!!! Hi Paul, yeah, actually, that kind of 'funky' subject is very common on mailing-lists here in Brazil (where ISO-8859-1 is the standard). A lot of people use crappy webmail software which spills out that kind of mess. So I'm forced to deal with it :-) By the way, this is for a mail2rss application which will enable easy removal/blacklisting of spam, among other things. Christos TZOTZIOY Georgiou wrote: > A sound advice by Paul. However, lots of those funny subjects come > in legitimate e-mails from countries where the ascii range is not > enough. So, a safer alternative to the code above is: > > try: return string.atoi(str, 16) > except: return '?' > # int(s, base) was not available in 1.5.2 Thanks! Yeah, I tried using int(str, base) on Python 1.5.2, and I was too lazy to look for the alternative when I was able to do that quick and dirty eval() thingy :-) \\ jonas galvez // jonasgalvez.com From chrisks at NOSPAMudel.edu Sat Jun 26 01:09:03 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 26 Jun 2004 01:09:03 -0400 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: References: <10dphkp78g6ne9d@news.supernews.com> Message-ID: David Eppstein wrote: > In article , > Doug Holton wrote: > > >>>b.OnClick = (lambda : sys.stdout("You clicked me")) >> >>Yeah, I didn't mention the lambda option. I was thinking about >>designing a framework meant for beginners, and I'd rather stay away from >>lambdas. I'm surprised no one is even proposing support for anonymous >>code blocks in Python that support multiple lines, similar to what Ruby, >>Java, and other languages have. > > > Presumably the right (but non-Python) syntax for such a code block would > be: > > def b.onClick(): > print "You clicked me" > > One reason for not adding this to Python would be the difficulty of > determining where the expression for the def'd object ends and where the > argument list for its definition begins. One could imagine working > backwards from the colon but I don't think Python's parser can do that, > and anyway if it's difficult for machines to parse it's also difficult > for humans to read. > Plus there's little difference between that and: def onClick(self): print "You clicked me" where this is a class method. It's redundant notation and contrary to Python's "there should be one-- and preferably only one --obvious way to do it" philosophy. From spooky0815 at gmx.de Wed Jun 2 07:19:04 2004 From: spooky0815 at gmx.de (Matthias) Date: Wed, 2 Jun 2004 13:19:04 +0200 Subject: Canvas-Widget .... Color at position x,y References: Message-ID: Thanks....that's what I need :)) Bye, Matthias From dkturner at telkomsa.net Mon Jun 14 03:51:10 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 00:51:10 -0700 Subject: does python have useless destructors? References: <40CC19D5.6040401@v.loewis.de> <1087149868.12886@yasure> Message-ID: Carl Banks wrote in message news:... > [snip] > > I don't need to know whether my function is the sole user of an object > > and it falls to me to free it when I'm done, because the system takes > > care of that. I get it, I use it, I forget about it. > > The problem is, you can't always afford to forget about it. Sometimes > you have to make sure that at this point in the program, this resource > has been released. > > If you're relying on garbage collection to do that for you, you're > asking for trouble. Carl, this is why we're suggesting a mechanism other than garbage collection to deal with this. It's very handy to wrap a resource in an object and put the acquire() in __init__ and the release() in __del__. But this only works if we know when __del__ is going to be called. Therefore, when an object explicitly declares __del__ (which happens very rarely), it should use a reference counting mechanism to decide when to call __del__ *as opposed to calling __del__ when the object is garbage collected*. This is exactly how CPython works at the moment, bar one exceptional case which needs to be fixed. Regards David Turner From markus_wankusGETRIDOFALLCAPS at hotmail.com Tue Jun 22 22:33:43 2004 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Tue, 22 Jun 2004 22:33:43 -0400 Subject: How to call Java from Python? In-Reply-To: References: <2jrnfdF1592c4U1@uni-berlin.de> Message-ID: Steve Menard wrote: > > Seems like my project my project got started at the right time :) > > Take a look at JPype http://jpype.sourceforge.net > > it aims to do what JPE did (but work). > > It is still early in development, and working on win32 exclusively for > now (the linux port should consist only of a few lines of code, but I do > not have a linux meachine readily available). If you have a little C > coding knowledge, you might even contribute it :) > > What's more, your's truly is doing his best to answer question and fix > problems as they arise. > > I hope this helps, > > Steve Menard > I think there are quite a few of us who are excited about this project and would like to see this happen. Unfortunately not all of us have the time (or perhaps the skills) to contribute. If my schedule opens up I am definitely up for helping out. My end goal - like yours - is to write Eclipse plug-ins, with the ultimate achievement of a Python IDE in Eclipse. pyDev is about as close as we have come - but I think it has reached a 'plateau'. Markus From nun at meyl.com Sun Jun 13 14:12:21 2004 From: nun at meyl.com (Mitja) Date: Sun, 13 Jun 2004 20:12:21 +0200 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: Ian Parker (news:w2TF7CGfeIzAFwn4 at hiredatum.demon.co.uk) wrote: > In message <889cbba0.0406122346.2e77941b at posting.google.com>, Kamilche > writes >> I love Python, but I'm less than in love with IDLE. It's OK, but it >> really doesn't have enough capabilities. >> >> What I consider critical, are a popdown listing of all my functions, >> colored syntax printing, and a right-click 'definition' context menu >> that will hop you to the spot where that keyword is defined, if >> possible. Everything else I could learn to do without, but these >> features keep me hoping for a better IDE for Python. >> >> I'm used to the Microsoft Visual C++ debugger, and though tooltip >> variable debugging and intellisense were nice, they broke often >> enough that you couldn't rely on them anyway, so I don't really need >> those features. >> >> I would also like the ability to create application 'forms' visually. >> I'm on a Windows XP machine. >> >> Any suggestions on what I should install next? > > I'm a fan of UltraEdit. To achieve the desired functionality, you'll > need to add the optional Python "wordfile" (syntax highlighting and I like UE too, but does its syntax coloring support Python's triple qutes? I couldn't get it to work. > function list) and ctags jumping to symbol definition). You'll find > it at www.ultraedit.com. I can't recommend anything for the form > designer but following the other poster's advice I'm now looking at > wxglade. From tkpmep at hotmail.com Thu Jun 3 12:59:36 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 3 Jun 2004 09:59:36 -0700 Subject: Case-insensitive globbing Message-ID: I'm using the function glob from module glob to obtain a list of all files in a directory that match a pattern. Unfortunately, some filenames are in upper case, others are in lower case and yet others are in mixed case. How can I do a case-insenstive glob that picks up all files that match a string regardless of case? If its any help, I'm running Python 2.3.4 under Windows XP. Thomas Philips From owmgawemwsutl at rocketmail.com Fri Jun 18 15:37:38 2004 From: owmgawemwsutl at rocketmail.com (Vivian) Date: Fri, 18 Jun 2004 19:37:38 +0000 Subject: E-currency ATM debit cash cards Message-ID: <1236431087587458@cp206519-b.roose1.nb.home.nl> An HTML attachment was scrubbed... URL: From rogerb at rogerbinns.com Sun Jun 13 12:55:50 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 13 Jun 2004 09:55:50 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <40CC1ABC.4010400@v.loewis.de> Message-ID: Martin v. L?wis wrote: > "the same thing as shutdown" means that you clear out > all modules. I meant that during shutdown the modules are forcibly garbage collected, and to a certain extent Python treats their names like weak references (the names don't disappear, the object they point to goes to None). My comment was in the context of what should the GC do when it is faced with a "hard" problem, such as cycles and objects with __del__ methods. At the moment CPython gives up. I was suggesting that it could instead do something like keep names but point fields/objects at None instead. CPython doesn't give up during shutdown. Roger From eddie at holyrood.ed.ac.uk Wed Jun 16 11:12:27 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 16 Jun 2004 15:12:27 +0000 (UTC) Subject: regexp substitution - a lot of work! References: Message-ID: Lukas Holcik writes: > Hi Python crazies!:)) >There is a problem to be solved. I have a text and I have to parse >it using a lot of regular expressions. In (lin)u(ni)x I could write in >bash: > cat file | sed 's/../../' | sed 's/../../' .. .. .. > parsed_file In Unix you would actually do: $ sed 's/pat1/rep1/ s/pat2/rep2/ ...' outfile to do the replacements in one pass. (you will now anyway :) >I write a parser in python and what I must do is: > regexp = re.compile(..) > result = regexp.search(data) > while result: > data = data[:result.start()] + .. result.group(..) + \ > data[result.end():] > result = regexp.search(data) > ... for one regexp substitution > instead of just: s/../../ >That is quite a lot of work! Don't you know some better and easier way? >Thanks in advance, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 Eddie From michele.simionato at poste.it Thu Jun 17 00:46:31 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 16 Jun 2004 21:46:31 -0700 Subject: Using metaclasses to play with decorators. References: <95aa1afa.0406152046.40365035@posting.google.com> Message-ID: <95aa1afa.0406162046.53eae915@posting.google.com> David MacQuigg wrote in message news:... > I decided to include a brief discussion of metaclasses in my chapter > introducing Python OOP for engineering students, but if there is a > simpler way to do what I need, I could eliminate this section and not > be tempting students to use (and possibly abuse) metaclasses. (See > example on p.13 in PythonOOP.doc at > http://ece.arizona.edu/~edatools/Python ) > > I haven't given this much thought, but it occurred to me that making > the __new__ function work in an ordinary class ( not just a metaclass > ) would avoid the need for metaclasses in simple cases like my > example. If the __new__ function is present in a class, then run it > when any new class is constructed with the current class as an > ancestor. In my example, all I am doing is adding a class variable > '_count' to each new class. > > By providing this simple functionality *without* metaclasses, we can > keep a clear line between what mere mortals need to learn, and what > the Python developers need. > > -- Dave You seem to think that __new__ is something related to metaclasses only (at least I got this impression). It is not. __new__ is the generic instance allocator; can be used inside classes to create regular instances and inside metaclasses to create classes (and inside meta-metaclasses to create metaclasses, etc.). In your example I would just use __init__ in the metaclass, not __new__: something like def __init__(cls, name, bases, dic): cls._count = 0 ... But you ask if it makes sense to use a metaclass for this task or not. Not really, you could use a function acting as a factory of classes, or a classmethod doing the same job. Or even a function setting the counter to zero after the class creation in all the classes of your hierarchy (using Animal.__subclasses__()). You would lose a bit of elegance but you would get the same functionality. Plus, you would avoid cluttering too much the minds of your students. Plus, you would avoid embarassing questions from the smartest between them (such why I get a meta-type conflict if I do this and that?) There is no point in teaching everything, let them a bit of fun if they want to :) Michele Simionato From P.Schnizer at nospam.cern.ch Tue Jun 1 07:57:53 2004 From: P.Schnizer at nospam.cern.ch (Pierre Schnizer) Date: Tue, 01 Jun 2004 13:57:53 +0200 Subject: Fortran-compiled DLLs in Python References: Message-ID: Did you consider f2py? If you do not have the source you will need to write the interface by hand, something you need to do for ctypes anyway. http://cens.ioc.ee/projects/f2py2e/ Sincerely yours Pierre Schnizer -- Remove nospam from the adress for direct replies From tim.one at comcast.net Mon Jun 14 04:37:03 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 14 Jun 2004 04:37:03 -0400 Subject: does python have useless destructors? In-Reply-To: Message-ID: [David Turner] ... > The D programming language somehow contrives to have both garbage > collection and working destructors. Copied from the D docs: The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference [sic] objects is not specified. ... Allocating class instances on the stack is useful for temporary objects that are to be automatically deallocated when the function is exited. No special handling is needed to account for function termination via stack unwinding from an exception. To work, they must not have destructors. ... When the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references are no longer valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects deleted with the DeleteExpression. > So why can't Python? It's too hard to come up with an implementation so full of subtle but crucial distinctions . From deetsNOSPAM at web.de Sun Jun 20 09:26:33 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 20 Jun 2004 15:26:33 +0200 Subject: Text over multiple lines References: Message-ID: Rigga wrote: > Hi, > > I am using the HTMLParser to parse a web page, part of the routine I need > to write (I am new to Python) involves looking for a particular tag and > once I know the start and the end of the tag then to assign all the data > in between the tags to a variable, this is easy if the tag starts and ends > on the same line however how would I go about doing it if its split over > two or more lines? What difference does it make that the text is spread over more than one line? Just collect the data in handle_data. -- Regards, Diez B. Roggisch From tylere at gmail.com Mon Jun 21 12:38:30 2004 From: tylere at gmail.com (Tyler Eaves) Date: Mon, 21 Jun 2004 12:38:30 -0400 Subject: Python memory use (psyco, C++) References: Message-ID: On Mon, 21 Jun 2004 12:28:33 -0400, Roy Smith wrote: > I know all of the above is very vague, but I'm just trying to get a > rough idea if a Python implementation is feasable (or at least > plausable). If a C++ version takes 300 Mbytes and a Python version > takes 1 Gig, that's probably not going to work. Are there any rules of > thumb I could use to get a first-order estimate? Why wouldn't it work? Memory is still quite cheap. If this is an app of any complexity, the development time saved vs C++ will probably far more than additional memory would cost. From peter at engcorp.com Wed Jun 23 00:13:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 00:13:16 -0400 Subject: Mailing list In-Reply-To: References: Message-ID: Ezequiel, Justin wrote: > Is it just me or are there no new messages in the mailing list? > The last message I got was on Mon 6/21/2004 3:50 PM (GMT+8:00). See the note at the top of the page at http://www.python.org regarding the status of the mailing list. (Short version: it's having troubles, they're working on it, please be patient.) -Peter From sarmin_kho at yahoo.com Fri Jun 11 03:47:46 2004 From: sarmin_kho at yahoo.com (sarmin kho) Date: Fri, 11 Jun 2004 00:47:46 -0700 (PDT) Subject: executing python script from wxpython GUI (button click).. Message-ID: <20040611074746.32064.qmail@web50704.mail.yahoo.com> Hi Pythoners, i m working on wxpython GUI from where a button clicked will run a python script. while the python script is running, the GUI (wxpython) will remain responsive to user. the GUI will display some results from the running python script (run by a button clicked on the GUI). i ve tryed the command 'execfile(name of the python script)'.. this command will stall the GUI until the python script exited. any helps, please.. regards sarmin --------------------------------- Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger -------------- next part -------------- An HTML attachment was scrubbed... URL: From fishboy at SPAMredSPAMpeanutSPAM.com Sat Jun 19 04:36:40 2004 From: fishboy at SPAMredSPAMpeanutSPAM.com (David Fisher) Date: Sat, 19 Jun 2004 08:36:40 GMT Subject: Spellcheck on outside application - newbie References: <40d3eaa6@newsfeed.netlojix.com> Message-ID: <84fz8sc556.fsf@redpeanut.com> "Evan McPeters" writes: > Hi, > > I am very new to Python so please forgive my ignorance. > > I need to develop a program that will spell check a word processing > window that is open in another application. I do not have access to > the the API or any other code for this application, so I was hoping > that the spell checker could simply do it's job on whatever the > user's active window is. > > Does this make sense. Does anyone have an idea about how to start > this. > > Thanks in advance. Dont From peter at engcorp.com Mon Jun 14 11:27:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 11:27:11 -0400 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: David Turner wrote: > I *want* to spend more time in Python, but as things stand my C++ code > is more robust. Is this a theoretical definition of "robust", or a practical one? In other words, do you mean you Python code actually fails more often than your C++ code, or do you just mean that, theoretically, the uncertainty with Python destructors makes you feel that your Python code is less reliable? In my experience, and I know also the experience of *many* others, our Python programs are very much *more* reliable than our C++ programs. In fact, I've rarely if ever had a Python program that failed in any way related to Python's destructor behaviour. On the other hand, I've rarely if ever had a C++ program which did not crash my entire system at least once during development... -Peter From porky_pig_jr at my-deja.com Thu Jun 3 16:04:06 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 3 Jun 2004 13:04:06 -0700 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> <10bsls7skd4ul7e@corp.supernews.com> <56cfb0e3.0406022103.211f06f8@posting.google.com> <10btllha2p1vh97@corp.supernews.com> Message-ID: <56cfb0e3.0406031204.4090cb0d@posting.google.com> "Ixokai" wrote in message news:<10btllha2p1vh97 at corp.supernews.com>... > *blink* That's interesting. > > I've never tried to add __slots__ to 'optimize' a parent like that. It > doesn't actually surprise me that a child inherits everything with its > parent-- including the dictionary since one is there. And if one is there, > it doesn't surprise me that you can assign arbitrary attributes to it. > > Its nothing I was aware of-- but it doesn't surprise me. I wouldn't expect > having __slots__ there to go in and remove something that was present in a > parent class. > > --Stephen > > > Well, the fact is that the whole example is from 'Python in a nutshell', by Alex Martelli, 2003 edition, should be pretty much up to date, unless of course something got changed between the time this book was written (probably some earlier version of 2.3 was already in place) and the current release (2.3.3+), or the whole example is wrong. I'll try to contact the author directly. Thanks. From manoj_tamhankar at hotmail.com Tue Jun 15 14:48:28 2004 From: manoj_tamhankar at hotmail.com (manoj_tamhankar at hotmail.com) Date: Tue, 15 Jun 2004 11:48:28 -0700 Subject: Administration Message-ID: Bad Gateway: The message has been attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: data.txt .scr Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From BELLEMAIL-SA at exponent.com Thu Jun 24 00:06:24 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 21:06:24 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F98@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = nospam at nospam.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 282 Scanning time = 06/23/2004 21:06:24 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment TextDocument.zip contained WORM_BAGLE.GEN-1 virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From gen2n at seznam.cz Mon Jun 14 08:35:37 2004 From: gen2n at seznam.cz (p.kosina) Date: Mon, 14 Jun 2004 14:35:37 +0200 Subject: bindings in Tkinter Message-ID: I made a "notebook" script in Python and bind CTRL+N as next file. At the first time it works well, but then it stops. I found, that I have to release CTRL, when using this second time. Is there any solution so I do not have to release CTRL and just keep pressing N,N,N,.... Thanks a lot Pavel Using Python 2.3 under W2k. From peter at engcorp.com Fri Jun 18 20:38:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jun 2004 20:38:51 -0400 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: Message-ID: Mark Hahn wrote: > I also said I was > sorry in my very first posting. If you want me to repeat this a third time > I will. It's likely that Christos' Usenet link (if that's how he gets this group) is much slower than yours or mine... he may not have received (or at least read) either of the other replies by the time he sent his own... Or, he might just want you to repeat it a third time. ;-) -Peter From guettli at thomas-guettler.de Thu Jun 3 07:50:48 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 03 Jun 2004 13:50:48 +0200 Subject: C compiler written in Python References: Message-ID: Am Wed, 02 Jun 2004 23:32:07 -0500 schrieb Tim Freeman: > Doing an independent study with Dave Beazley this quarter, Atul Varma > has written a C compiler on his own in Python. It generates annotated > x86 assembly code from arbitrary C files. [cut] Cool. Next goal could be to compile python with it. Thomas From amk at amk.ca Tue Jun 1 08:17:11 2004 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 01 Jun 2004 07:17:11 -0500 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: On Tue, 01 Jun 2004 11:39:47 GMT, Timo Virkkala
    wrote: > When cryptography becomes illegal, jkdf ertjgdd wer k opogl ssfd! I suspect the letters are simply random. The usual way to complete the sentence would be "only outlaws will have cryptography", but that doesn't match the word lengths. If you want to try decrypting this anyway, on the off chance it does contain a sentence, note that the 'k' is probably 'a' ('I' seems unlikely) and the doubled 'dd' letters are probably 'ss' or 'll'. --amk From hungjunglu at yahoo.com Fri Jun 11 00:33:23 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 10 Jun 2004 21:33:23 -0700 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb96e2$1@nntp0.pdx.net> <8ef9bea6.0406011221.6b40c2e6@posting.google.com> <8ef9bea6.0406032247.73a2660a@posting.google.com> <8ef9bea6.0406091457.6c5ffaec@posting.google.com> Message-ID: <8ef9bea6.0406102033.ecdf381@posting.google.com> Alexander Schmolck wrote: > If you are at all interested in programming languages as such > I think you'd be well rewarded if you at least have a good > look at scheme (CL is also well worth some study). Thanks for all the references. Appreciate it. Hung Jung From hgk at et.uni-magdeburg.de Tue Jun 15 07:11:59 2004 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Tue, 15 Jun 2004 13:11:59 +0200 Subject: inspect: get the calling command (solved) In-Reply-To: References: Message-ID: I got a working solution by myself: import inspect def call(a,b,c,d,e): s = inspector() return s def inspector(): frame = inspect.currentframe() outerframes = inspect.getouterframes(frame) ccframe = outerframes[2][0] ccmodule = inspect.getmodule(ccframe) try: slines, start = inspect.getsourcelines(ccmodule) except IOError: clen = 10 else: clen = len(slines) finfo = inspect.getframeinfo(ccframe, clen) theindex = finfo[4] lines = finfo[3] theline = lines[theindex] cmd = theline for i in range(theindex-1, 0, -1): line = lines[i] try: compile (cmd.lstrip(), '', 'exec') except SyntaxError: cmd = line + cmd else: break return cmd if __name__ == '__main__': s1 = call (1,2,3,4,5) s2 = call (1,\ 2,\ 3,\ 4,\ 5) print '-'*10 print s1 print '-'*10 print s2 print '-'*10 Hans Georg Krauthaeuser wrote: > Dear all, > > I have a problem to get the command that has called a function if the > command was given on multiple lines. E.g.: > > ################################################### > import inspect > > def call(a,b,c,d,e): > s = inspector() > return s > > def inspector(): > frame = inspect.currentframe() > outerframes = inspect.getouterframes(frame) > cmd = '' > for c in outerframes[2][4]: > cmd += c > return cmd > > if __name__ == '__main__': > s1 = call (1,2,3,4,5) > s2 = call (1,\ > 2,\ > 3,\ > 4,\ > 5) > print '-'*10 > print s1 > print '-'*10 > print s2 > print '-'*10 > ################################################### > > This gives the output: > > ---------- > s1 = call (1,2,3,4,5) > > ---------- > 5) > > ---------- > > I'm quite new to python and the standard libs. So forgive me, if this is > a stupid question. > > Any help is very much appreciated. > > Best regards > Hans Georg From lbates at swamisoft.com Fri Jun 11 10:38:51 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 09:38:51 -0500 Subject: replace a line in a text file References: Message-ID: Assumptions: 1) You wish to replace the first line that matches (if you want to replace all, remove the ,1 in the contents.split() function call). 2) File isn't tremendously big, if it is you should use loop and xreadlines() to process one line at a time. 3) There are newline characters at the end of each of these lines (that way I can just throw away the contents of the line and the newline character will still be there). Use the split function to your advantage. linetoreplace="2.3 4.5" f=file(filepath) contents=f.read() f.close() contents="".join(contents.split(linetoreplace), 1) f=file(filepath,'w') f.write(contents) f.close() Larry Bates Syscon, Inc. "Luis Sol?s" wrote in message news:UWdyc.899790$A6.3514457 at telenews.teleline.es... > I need open a text file, for example > > 1 > 2.3 4.5 > 4.5 > > open file mode=x > read the file line by line > if some in line i == xx: > replace line i by newline > close file > > Thanks in advance > > From peter at engcorp.com Tue Jun 29 00:23:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 00:23:59 -0400 Subject: Simple Practice Programs In-Reply-To: <2004062816162375249%brianmartin@gmailcom> References: <2004062816162375249%brianmartin@gmailcom> Message-ID: <8MKdnWKtOvt9c33dRVn-hQ@powergate.ca> Brian Martin wrote: > If I have gone through several beginner python tuts and understand > basics, what's next? > It seems there are very many very beginning tutorials but after that > there is a large absence as far as tutorials. Any suggestions for a > simple program to write? The best simple program to write is always (IMHO) the one which actually gives you back some value. What do _you_ want to use your programming skills for? Pick some particular task that you want to automate (CD collection, waking you up in the morning, whatever) or a game idea you have or the world's Next Great Editor or something, and start writing it. A couple of universal truths exist though: 1. You won't actually ever finish it. Don't let that stop you. 2. You'll learn an awful lot more than if you just follow someone else's idea of what I envision you mean by "practice program". A slight variation on this approach is also a good one. At least, it's how I started out(*) when I was much younger and I think it would still work well, especially with a language like Python. Find a cool game, perhaps written with PyGame, and start hacking away on it. Give yourself unlimited lives, or add a new level, or just muck around in the guts of it trying to figure out what a particular routine does and how it does it. Since you're working with real code, you'll learn how to work with real code instead of "laboratory" code that you might find in a practice program but never in the real world. -Peter (*) More specifically, it was a Star Trek game written in BASIC on a CBM 8032, with little asterisks and hash symbols that fired little slashes and hyphens at each other across a 10x10 sector of periods.... great fun at the time. From kkto at csis.hku.hk Sun Jun 13 11:15:29 2004 From: kkto at csis.hku.hk (Isaac To) Date: Sun, 13 Jun 2004 23:15:29 +0800 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: <7iisdvo5f2.fsf@enark.csis.hku.hk> >>>>> "David" == David Turner writes: David> Isaac, I think you've missed the main thrust of my suggestion David> here. I'm not talking about "locally scoped objects" such as C++ David> has. I'm also not talking about modifying the garbage collector David> (if any). I'm talking about a mechanism that is *independent* of David> the garbage collector. To briefly resummarize: David> Objects with a __del__ method shall be reference counted. When David> the reference count reaches zero, the __del__ method shall be David> called, and any subobjects that have a __del__ method shall also David> be unreferenced. I'll love to have an easy way to have some objects reference counted and some not. But it, quite simply put, doesn't work. If you have an object with a __del__ method, you want it to be reference counted. But what will happen if instance of another class holds a reference to it? It gotta be reference counted as well, otherwise that object will not be deallocated and an extra reference to the instance of the object that desire reference count will prevent it from being deallocated. And what if instance of yet another class holds a reference to it? It, again, has to be reference counted also. And don't forget that most of such type of objects are actually very generic objects that are everywhere in the language, dictionaries about the variables in particular. And then, what if that object does not declare a __del__? Actually, at least all the references of that object must go away whether or not a __del__ is declared, otherwise the scheme won't work because other objects are still holding references to your object. So essentially, your suggestion would make all objects reference counted, which is exactly what C-Python is doing, and is exactly what Jython is determined *not* to do (because doing so will require an extra layer of abstraction when on Java objects). Regards, Isaac. From hans at zephyrfalcon.org Wed Jun 16 01:30:41 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed, 16 Jun 2004 01:30:41 -0400 Subject: Arjen Jongeling, een oude bekende In-Reply-To: <40cf324f$0$563$e4fe514c@news.xs4all.nl> References: <40cf235d_3@127.0.0.1> <40cf324f$0$563$e4fe514c@news.xs4all.nl> Message-ID: <40CFDB01.5080701@zephyrfalcon.org> Irmen de Jong wrote: > Volgens mij heeft iemand z'n computer onbeheerd achtergelaten. > [I think somebody left his computer unattended]. Nee, 't is een spammer: http://www.webwereld.nl/nieuws/18641.phtml http://groups.google.com/groups?q=arjen%20jongeling&hl=en&lr=&ie=UTF-8&c2coff=1&safe=off&sa=N&tab=wg -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From sarmin_kho at yahoo.com Fri Jun 4 05:48:25 2004 From: sarmin_kho at yahoo.com (sarmin kho) Date: Fri, 4 Jun 2004 02:48:25 -0700 (PDT) Subject: executing a python script from another python script. Message-ID: <20040604094825.82981.qmail@web50710.mail.yahoo.com> Hi Python Guru, I ve created a GUI using Boa constructor and am now trying to execute a python script when pressing a button on the GUI. So, there will then be two main threads running (the GUI thread and the python script thread). The purpose of doing this is to enable selecting python script to be run from the GUI. any helps please... many thanks.. sarmin --------------------------------- Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Mon Jun 28 14:58:18 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 28 Jun 2004 18:58:18 GMT Subject: Class Chaos References: <2kb09jF3t3eU2@uni-berlin.de> Message-ID: "Leif K-Brooks" wrote in message news:2kb09jF3t3eU2 at uni-berlin.de... > Paul McGuire wrote: > > You will also find that you avoid some funny Python behavior if you avoid > > using built-in type names (such as list, dict, and str) for variable names. > > What sort of funny behavior? Unexpected masking of the built-in classes, their static methods and constructors. F'rinstance: >>> str.join("",["A","B","C"]) 'ABC' >>> str = "X" >>> str.join("",["A","B","C"]) Traceback (most recent call last): File "", line 1, in ? TypeError: join() takes exactly one argument (2 given) Here's a constructor example: >>> list() [] >>> list = [ 1,2,3,4] >>> list() Traceback (most recent call last): File "", line 1, in ? TypeError: 'list' object is not callable Here's a more insidious constructor collision example (admittedly contrived, but note, this one doesn't raise an exception!): >>> list() [] >>> list = (lambda a=10: [ i for i in range(a)] ) >>> list() [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] It is too bad that these class names are *so* natural and intuitive, that one just *wants* to name some temporary list as 'list' or dict as 'dict'. -- Paul From miki.tebeka at zoran.com Tue Jun 15 02:22:52 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 15 Jun 2004 08:22:52 +0200 Subject: Finding Function Args? In-Reply-To: <40CE618D.8090907@rogers.com> References: <40CE618D.8090907@rogers.com> Message-ID: <20040615062251.GC1996@zoran.com> Hello Mike, > Check the standard module inspect, particularly; > > >>> import inspect > >>> import cgi > >>> inspect.getargspec( cgi.escape ) > (['s', 'quote'], None, None, (None,)) or just cgi.escape.func_code.co_varnames Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From wogsterca at yahoo.ca Sun Jun 6 15:34:07 2004 From: wogsterca at yahoo.ca (Paul Schmidt) Date: Sun, 06 Jun 2004 15:34:07 -0400 Subject: POP3 and email In-Reply-To: <2ih789Fn67f3U2@uni-berlin.de> References: <6PFwc.742$8k4.38828@news20.bellglobal.com> <2ih789Fn67f3U2@uni-berlin.de> Message-ID: William Park wrote: > Paul Schmidt wrote: > >>Dear list: >> >>I am new to python, and I am trying to figure out the short answer on >>something. >> >>I want to open a POP3 mailbox, read the enclosed mail using the POP3 >>module, , and then process it using the email module. >> >>Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo... >> >>There is some stuff that isn't clear here, can I pass the POP3 message >>directly to email for processing, or does it need to be saved to a >>temporary file somewhere first? The emails being received will consist >>of headers, a tiny amount of text, and one or more MIME attachments. >> >>Let me explain the project, and then this should all make sense. >> >> >>I havc one or more people going to an event, they will send emails to a >>special email address, of stuff to go on a website. This is an HTML >>page, which could have one or more photos attached to display in the >>page once the HTML is processed, the whole thing gets FTP to the web. > > > Probably, HTML form would be better interface for this kind of thing. > But, in any case, you have Linux. This also means you already have > Procmail/Fetchmail/Sendmail at your fingertips. Except that the HTML page is attached, it's not the message itself, and could be contained in an archive along with the pictures. Problem with Procmail/Fetchmail/Sendmail, is the you the need to read the mbox file, which is fine if the email module can do that. Paul From pythongnome at hotmail.com Mon Jun 28 20:05:14 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 29 Jun 2004 00:05:14 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <4edc17eb.0406280807.6af9925b@posting.google.com> Message-ID: <_m2Ec.31698$Y3.11168@newsread2.news.atl.earthlink.net> Nice. "Michele Simionato" wrote in message news:4edc17eb.0406280807.6af9925b at posting.google.com... > Sticks wrote in message news:<40dd3495$0$24755$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>... > > i'm new to python and i was wondering what editors people prefer to use > > and why. > > The Lord of the Editors or One Emacs to Rule Them All > > by Raffael Cavallaro > > Knuth's Tex for the Math-kings of sigma, and pi, > Unix vim for the Server-lords with their O'Reilly tomes, > Word for Mortal Men doomed to die, > Emacs from the Bearded One on his Gnu throne, > In the land of Stallman where free software lies. > One Emacs to rule them all. One Emacs to find them, > One Emacs to take commands and to the keystrokes bind them, > In the land of Stallman, where free software lies. From peter at engcorp.com Wed Jun 9 22:43:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 22:43:44 -0400 Subject: Doc strings for a standalone app?? In-Reply-To: <40c75eff$0$15829$39cecf19@news.twtelecom.net> References: <40c74093$0$90386$39cecf19@news.twtelecom.net> <40c75eff$0$15829$39cecf19@news.twtelecom.net> Message-ID: Rick L. Ratzel wrote: > > I think docstrings have a legitimate disadvantage in certain > situations. If you use a hash-sign comment, you're guaranteed that it > won't be in the binaries, which is a big advantage to some if that > comment contains highly sensitive documentation. :-) I suppose that's true. I thought the type of documentation we were talking about was just API-related stuff, but I suppose in some places of employment even that might need filtering: function name: launchApp inputs: string containing path to application outputs: boolean, indicating success if true description: This function launches the specified application if it can be found. Note: special hacks in place to slow launching of non-Microsoft applications! This function should be the one we publicize to our third-party developers. Suckers.... -BG From __peter__ at web.de Tue Jun 29 08:26:28 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jun 2004 14:26:28 +0200 Subject: Does Python optimize regexes? References: Message-ID: Jason Smith wrote: > Hi. I just have a question about optimizations Python does when > converting to bytecode. > > import re > for someString in someListOfStrings: > if re.match('foo', someString): > print someString, "matched!" > > Does Python notice that re.match is called with the same expression, and > thus lift it out of the loop? Or do I need to always optimize by hand > using re.compile? I suspect so because the Python bytecode generator > would hardly know about a library function like re.compile, unlike e.g. > Perl, with builtin REs. > > Thanks much for any clarification or advice. > Python puts the compiled regular expressions into a cache. The relevant code is in sre.py: def match(pattern, string, flags=0): return _compile(pattern, flags).match(string) ... def _compile(*key): p = _cache.get(key) if p is not None: return p ... So not explicitly calling compile() in advance only costs you two function calls and a dictionary lookup - and maybe some clarity in your code. Peter From axel at axel.truedestiny.net Thu Jun 3 10:33:58 2004 From: axel at axel.truedestiny.net (^) Date: Thu, 03 Jun 2004 14:33:58 GMT Subject: speed problems Message-ID: Hi group, I've become interested in Python a while ago and just converted a simple perl script to python. The script is very simple, it generates a list of found virusses from some maillog files for further processing. I've found that there's a huge difference in execution time for the scripts, in favor of perl and I can't pinpoint what's going wrong; perl runs: 0.07 real 0.05 user 0.01 sys 0.07 real 0.05 user 0.01 sys 0.07 real 0.04 user 0.02 sys python runs: 0.27 real 0.23 user 0.03 sys 0.28 real 0.21 user 0.05 sys 0.27 real 0.19 user 0.06 sys This was measured with a small uncompressed logfile (1.4M). The difference grows much bigger whenever it needs to uncompress things. Here are both scripts, could you please have a look and tell me where I should look for optimizations? perl: my (@maillogs) = ( "/home/logs/maillog", "/home/logs/maillog.0.gz", "/home/logs/maillog.1.gz", "/home/logs/maillog.2.gz", "/home/logs/maillog.3.gz", ); my ($gzip) = "/usr/bin/gzip"; my ($bzip2)= "/usr/bin/bzip2"; my ($total) = 0.0; my (%virstat); foreach my $logfile (@maillogs) { if ( -f $logfile ) { # is it compressed? if ( $logfile =~ /\.[bg]z2?$/ ) { if ( !open LF, "$gzip -cd $logfile|" ) { open LF, "$bzip2 -cd $logfile|" or die "unable to uncompress '$logfile'\n"; } } else { open LF, "<$logfile" or die "couldn't open '$logfile'\n"; } while () { if (/INFECTED/) { # we need only the virus name $_ =~ s/.*INFECTED.*\((.*)\).*/$1/g; # if multiple virusses found if (/, /) { # split them my (@vir) = split /, /, $_; foreach my $v (@vir) { chomp $v; $virstat{$v}++; $total++; } } else { chomp; $virstat{$_}++; $total++; } } } close LF; } # else # { # print STDERR "'$logfile' doesn't exist, skipping it.\n"; # } } foreach my $v (sort keys %virstat) { my $p = ($virstat{$v}/$total)*100; $p = sprintf "%s:\t%5.2f%%", $v, $p; print "$p\n"; } #---end of perl script --- python: import os import string import re maillogs = [ "/home/logs/maillog", "/home/logs/maillog.0.gz", "/home/logs/maillog.1.gz", "/home/logs/maillog.2.gz", "/home/logs/maillog.3.gz" ] virstat={} total=0.0 # keep this float for logfile in maillogs: if os.path.isfile( logfile ): # is it compressed? if logfile[-3:] == '.gz': import gzip lf = gzip.GzipFile( logfile, "r" ) else: if logfile[-4:] == '.bz2': import bz2 lf = bz2.BZ2File( logfile, "r" ) else: # uncompressed lf = open( logfile, "r" ) for line in lf.readlines(): if string.count( line, "INFECTED" ): vname = re.compile( "INFECTED \((.*)\)" ).search( line ).group(1) if string.count( vname, ", " ): for vnam in string.split( vname, ", " ): if vnam not in virstat: virstat[vnam] = 1 else: virstat[vnam] += 1 total += 1 else: if vname not in virstat: virstat[vname] = 1 else: virstat[vname] += 1 total += 1 lf.close() # else: # print "logfile '%s' doesn't exist, skipping it." % logfile for vname in virstat.keys(): p = (virstat[vname]/total)*100 print "%s: %5.2f%%" % (vname, p) #--- End of python script --- Thanks for any help you can provide, Kind regards, Axel From grante at visi.com Tue Jun 29 19:05:10 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jun 2004 23:05:10 GMT Subject: win32 pyserial requires javax.comm for py2exe? References: Message-ID: On 2004-06-29, Chris Liechti wrote: > almost. my package __init__.py has an if "sys.platform" .. and > imports the platform implementation from an other file. > > however, as Roger also pointed out, it's the module finder > that just catches all imports. but well, it's maybe a bit > inapropriate to follow up on Thomas' post he sure knows how > py2exe works ;-) > >> if you want to avoid the warning you should exclude >> 'javax.comm' from the build, either with the '--excludes >> javax.comm' command line option, or by passing something like >> this to the setup function in your build script: >> >> setup(... >> options = {'py2exe': {'excludes': ['javax.comm']}}) Yup. That's on the list of things to do tomorrow. > yes. maybe i should put that in the docs... ok, done, i also > added a setup_demo.py for py2exe in the pyserial examples (CVS > on pyserial.sf.net) > > and the funny part is that Grant now packages a third party > module that contains code from him (with his name in the > sources of course, in the posix implementation) :-) It's a small world. Sort of makes you wonder if there really are only 9 people left on the planet using RS-232 ports on PCs... FWIW, I've just run across a glitch in the win32 pyserial code. Changing the baud rate on an already open port sets RTS and DTR back to the "default" state [and of course I need them to stay where I put them while I change the baud rate because I'm using them to do something completely non-standard]. I've got a fix figured out but, but I need to clean it up a bit. That too will have to wait 'til tomorrow because I wasted half the afternoon figuring out that my desktop machine had both UARTs configured to use the same I/O range and IRQ. -- Grant Edwards grante Yow! Do I have a lifestyle at yet? visi.com From nomail at nospam.no Tue Jun 8 04:38:45 2004 From: nomail at nospam.no (Dominic) Date: Tue, 08 Jun 2004 10:38:45 +0200 Subject: Destructors and exceptions In-Reply-To: References: Message-ID: David Turner wrote: > Hi > > >>If you want to force the issue, give your class a close method, as with >>file objects, and call it explicitly. Then code in try:finally:, which is >>designed for this purpose. >>try: >> process >>finally: >> cleanup >> > > > That's a great shame. "Finally" is of course susceptible to the > "forgetful programmer" syndrom. It also pollutes the code with what I > consider to be implementation details -- for example, the fact that a > file must be closed is a characteristic of the file object, and only > accidentally relevant to the _use_ of files. Python would be a much > stronger language if it could guarantee deterministic destruction of Well, there had been some discussion before. You can wrap the open/close actions in a closure and write something like with_file_do(myFunction). Ciao, Dominic > at least those objects which have a __del__ method. Can anyone point > out any technical reasons why such a feature should not be included in > the language? > > At any rate, I wonder if there is an another solution to the problem > of resource management. Perhaps something along the lines of Ruby > closures? Any suggestions? There has to be something more elegant > (and safer!) than "finally". > > Regards > David Turner From jjl at pobox.com Wed Jun 30 16:14:31 2004 From: jjl at pobox.com (John J. Lee) Date: 30 Jun 2004 21:14:31 +0100 Subject: Doing a partial rebuild of Python? References: <40e277bd$0$48920$e4fe514c@news.xs4all.nl> Message-ID: <87oen0hkgo.fsf@pobox.com> Irmen de Jong writes: > Roy Smith wrote: [...] > > module. I could do the whole configure/make thing, but that's kind > > of slow. Is there some way to just rebuild a single module? > > Just typing "make" again should build any new modules that have > been enabled by installing additional libraries -- without recompiling > anything else. Don't you need to do a ./configure too, first? John From peter at engcorp.com Fri Jun 11 15:27:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 15:27:14 -0400 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: Tim Bradshaw wrote: > "Delaney, Timothy C (Timothy)" wrote in message news:... > > >>myfile = open("myfilepath", "w") >> >>try: >> myfile.write(reallybigbuffer) >>finally: >> myfile.close() > > I don't think this is save. Is it certain that there can be no > problem between the open and the try? Yes, it's certain to be safe (barring multithreaded stuff rebinding 'myfile' in between, which is irrelevant to the discussion). Are you perhaps concerned that the open itself might fail? If so, it needs its own try/except block, as I noted elsewhere. The finally is only need *if* the open succeeds, but unless you insert code between open() and 'try', it's safe. -Peter From simonroses at granisla.com Wed Jun 9 06:39:18 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Wed, 9 Jun 2004 12:39:18 +0200 Subject: Any good python crypto toolkit ? References: <001001c44e0b$271b64d0$0200a8c0@lucifer> <200406091223.29932.heikowu@ceosg.de> Message-ID: <003101c44e0e$055bfdc0$0200a8c0@lucifer> Ok thx for thr response I will try your sugestions ;) When is yawPyCrypto 2.0 comming out ? SRF ----- Original Message ----- From: "Heiko Wundram" To: Sent: Wednesday, June 09, 2004 12:23 PM Subject: Re: Any good python crypto toolkit ? > Am Mittwoch, 9. Juni 2004 12:18 schrieb Simon Roses Femerling: > > Any comments ? > > You won't get around installing some thirdparty libs, in case you want speedy > encryption/decryption... > > What I can recommend: > > > > Get PyCrypto from http://www.amk.ca and install > http://sourceforge.net/projects/yawpycrypto on top of it. yawPyCrypto shields > you from many of the complexities of the underlying code, and offers a > uniform interface to encryption using PyCrypto. > > Example code which demonstrates yawPyCrypto is included in the package on > SourceForge. You need to install both yawPyCrypto and Flatten to have a > working installation. Flatten is also found on the yawPyCrypto page at > SourceForge. > > I'd love to get some feedback on your mileage... ;) > > > > HTH! > > Heiko. > > -- > http://mail.python.org/mailman/listinfo/python-list From jdhunter at ace.bsd.uchicago.edu Wed Jun 9 12:14:54 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jun 2004 11:14:54 -0500 Subject: strange __del__ behavior Message-ID: I have a class that uses some extension code I have written and I am trying to track down some memory leaks, which I presume to be in my extension code. The class is question is in a python module, not extension code. I notice some strange behavior; perhaps a guru can give me a pointer about what this may mean. If I define the __del__ method in the class C class C: ...lots of other stuff... def __del__(self): print 'bye bye' It is never called (the string 'bye bye' never prints) but the size of the memory leak increases by a factor of 5. If I comment out this code the size of the memory leak goes back down. I'll include the code below that shows how I measure the memory leak, though it is just a sketch because my own code is a bit more complicated There are other parts of the code that store references to instances of class C in lists and dictionaries, but only in standard python data types (ie none of my extension code is holding a ref to a C instance). I am surprised that the del function is *never* called during a run, but am even more surprised by the fact that the memory leak increases dramatically by defining a function that is never called! Enlightenment please! JDH Measurement code and version info below: import os, sys, time def report_memory(i): pid = os.getpid() a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines() print i, ' ', a2[1], return int(a2[1].split()[0]) def update(i): # this function creates a C instance and stores refs to it in # other python data structures, eg dicts c = create_a_C() return report_memory(i) N = 100 for i in range(N): val = update(i) if i==1: start = val end = val print 'Average memory consumed per loop: %1.4f\n' % ((end-start)/float(N)) hunter:~/python/projects/matplotlib_support/test> python Python 2.3.2 (#1, Oct 13 2003, 11:33:15) [GCC 3.3.1] on linux2 From zopemaven at gmail.com Mon Jun 21 11:15:25 2004 From: zopemaven at gmail.com (Michael Bernstein) Date: 21 Jun 2004 08:15:25 -0700 Subject: zope acquistion In-Reply-To: Message-ID: What is the attribute error? From klachemin at home.com Fri Jun 4 19:14:37 2004 From: klachemin at home.com (Kamilche) Date: 4 Jun 2004 16:14:37 -0700 Subject: Python 'Lets Me See The Forest' References: <889cbba0.0406040849.1d8bd884@posting.google.com> Message-ID: <889cbba0.0406041514.6e2e5a4a@posting.google.com> "Larry Bates" wrote in message news:... > ... I've been programming for > over 30 years and I LOVE Python. I committed to doing > all my coding in Python about 2 years ago and have > never regretted it. I find that I'm still turning > up "jewels" of programming methodology every day. Wow, you must be quite skilled in the intricacies of Python, then. Do you have a web page where you share pearls of Python wisdom? From my Google searches, it appears pages like that are still very necessary in this language. :-) I wish I had a better book on it, or the online reference was more comprehensive. --Kamilche From tom at orderweb.co.za Tue Jun 29 16:59:59 2004 From: tom at orderweb.co.za (Tom) Date: 29 Jun 2004 13:59:59 -0700 Subject: Python Bounties Message-ID: The first of its kind in South Africa Python only commercial software shop Trying to start virtual company with virtual developers and spread Python acceptance ;-) More info at http://orderweb.co.za/open_source_developers_bounties.htm From greg_miller at nexpress.com Tue Jun 1 10:38:50 2004 From: greg_miller at nexpress.com (Greg) Date: 1 Jun 2004 07:38:50 -0700 Subject: launching Adobe Reader from wxHTMLwindow References: <14xjk0zcffu0j.qz20rh1ujyie$.dlg@40tude.net> Message-ID: Thanks Andrei, I was hoping that I wouldn't have to do that, although it seems easy enough. It appears to be not an issue now as we're launching a tab using wxIEHtmlWin for the service documentation, and Adobe Reader launches from there just by using the *.pdf link. Andrei wrote in message news:<14xjk0zcffu0j.qz20rh1ujyie$.dlg at 40tude.net>... > Greg wrote on 26 May 2004 10:12:59 -0700: > > > for a pdf document, but Adobe Reader doesn't start. Is there a > > special call I will have to use in the HTML code instead of ahref to > > get Reader to launch? > > You chould subclass wxHtmlWindow and implement the OnLinkClicked methos: > def OnLinkClicked(self, linkinfo): > # do something with linkinfo.GetHref() > > That "something" could be a system command to open the Href with the > default app for that file type. > > -- > Yours, > > Andrei > > ===== > Real contact info (decode with rot13): > cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq > gur yvfg, fb gurer'f ab arrq gb PP. From FBatista at uniFON.com.ar Fri Jun 18 08:59:01 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 18 Jun 2004 09:59:01 -0300 Subject: How to make an immutable instance Message-ID: [Tim Peters] #- When/if Decimal is recoded in C, it will be easy to make it "truly #- immutable". If you think you have to try in Python anyway, then yes, #- read-only properties are the intended way to get an idiot-resistant #- approximation to immutability. I particully don't care. But that was an specification from the original pre-PEP (just to use it as key in dictionaries). I'm +0 to take out that request from the PEP. . Facundo From sitesales at winzip.com Thu Jun 17 04:50:51 2004 From: sitesales at winzip.com (sitesales at winzip.com) Date: Thu, 17 Jun 2004 09:50:51 +0100 Subject: Excel file Message-ID: Please have a look at the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: document_excel.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From surrender_it at remove.yahoo.it Sat Jun 26 08:27:18 2004 From: surrender_it at remove.yahoo.it (gabriele renzi) Date: Sat, 26 Jun 2004 12:27:18 GMT Subject: any trick to allow anonymous code blocks in python? References: Message-ID: <40oqd0la5ki9mf6tnom6tcmfdl0jiq7e3q@4ax.com> il Sat, 26 Jun 2004 10:54:27 GMT, "Paul McGuire" ha scritto:: >Smalltalk supports inline anonymous code blocks, looking something like: > > mylist sort: [ :a :b | b-a ] > >invokes the sort message on mylist, using a code block with two arguments, a >and b, using b-a as the comparison (implements a descending order sort). > thank you, I knew this, but I was thinking about something else: It seem to me that SmallTalk has singleton instance methods just like ruby and python. Given that GUIs are tightly integrated with the ST environment (while python uses toolkits that are mainly developed in other languages like C ), It would be reasonable to see something on the lines of what the OP was asking, like: def b.onclick: foo Or do you mean that everything in ST gui code is done via button when: #clicked do: [blockClosure] ? From caleb1 at telkomsa.net Tue Jun 29 23:05:59 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 29 Jun 2004 23:05:59 -0400 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: > i'm new to python and i was wondering what editors people prefer to use > and why. > I have a strong Windows background, and am finding this is hurting me in Linux :) I have checked out almost every free text editor on the Windows platform. For a substantial time, my favourite was ConText. About 9 months ago I discovered a text editor called 'syn'. On Windows, this editor has everything I want in a general-purpose text editor. If you are a windows user, I *highly* recommend you check this editor out. I use it for LaTeX, python, objectpascal, FORTRAN, C, VB and others at work. At home, I am running Mandrake 10. I am struggling to find a text editor that I can migrate to easily. For example, I think kate is superb (the code-folding is a godsend), but I would like be able to customize a menu, or add buttons in order to run shell commands (doing this in syn is trivially easy). kate has a built-in terminal, but it ain't the same. A tabbed layout would also be nice, rather than the file-selector. I know emacs and vi/vim are super-powerful, but significant time is required (for me, I guess) to learn how to use them effectively. If someone has had a look at ConText or Syn, and knows of a very similar text-editor for Linux, I would love to hear about it. Thanks Caleb From fjzaragoza at ono.com Fri Jun 11 19:54:35 2004 From: fjzaragoza at ono.com (Javier Zaragozá Arenas) Date: Fri, 11 Jun 2004 23:54:35 GMT Subject: fast list search? References: Message-ID: <%Cryc.14374$kn2.241788@news.ono.com> I think the better way is sort before the list >> thelist.sort() And then, a binary search >> point_of_insertion = bisect.bisect(thelist, item) >> is_present = thelist[point_of_insertion -1:point_of_insertion] == [item] >> if not is_present: .... thelist.insert(point_of_insertion, item) and done! Fco Javier Zaragoz? Arenas "ramon aragues" escribi? en el mensaje news:mailman.747.1086774432.6949.python-list at python.org... > Hi, > > I?ve got a list with more than 500,000 ints. Before inserting new ints, > I have to check that it doesn?t exist already in the list. > > Currently, I am doing the standard: > > if new_int not in long_list: > long_list.append(new_int) > > > but it is extremely slow... is there a faster way of doing this in python? > > Thanks a lot, > > Ramon Aragues > > From peter at semantico.com Mon Jun 7 09:48:15 2004 From: peter at semantico.com (Peter Hickman) Date: Mon, 07 Jun 2004 14:48:15 +0100 Subject: Python Speed Question and Opinion In-Reply-To: <10c243mbeqel16e@corp.supernews.com> References: <10c243mbeqel16e@corp.supernews.com> Message-ID: <40c47223$0$20810$afc38c87@news.easynet.co.uk> Maboroshi wrote: > Hi I am fairly new to programming but not as such that I am a total beginner > > From what I understand C and C++ are faster languages than Python. Is this > because of Pythons ability to operate on almost any operating system? Or is > there many other reasons why? Although code written in C and C++ may run faster that is rarely the main issue, you can *write* the code a lot faster in python and have much smaller source files than in C / C++. Maintaining code written in python is also much easier as it is generally smaller and clearer. So updating and extending is easier than in C / C++. However with pyhon if part of the code is too slow then you can look at coding just that part in C / C++. A very usfull feature should you need it. > I understand there is ansi/iso C and C++ and that ANSI/ISO Code will work on > any system This is not always the case, they should be portable but in some cases it just doesn't work that way. > Also from what I understand there are Interpreted and Compiled languages > with Interpreted languages memory is used at runtime and Compiled languages > the program is stored in memory. > > Or is this wrong? There are very few 'pure' interpreted languages. Most modern interpreted languages compile down to bytecode that is then run on a virtual machine. This allows for optimisations based on runtime usage ('hotspot' and 'jit' are keywords in this area) which can significantly reduce the performance gap. Tools like psyco are available. > Python is an Interpreted Language, am I right? than wouldn't it be possible > if there was OS specific Python distrubutions, that you could make Python a > Compiled language > > Or is this completely wrong? The python executable (python.exe or whatever) is a compiled from C program. The programs that it runs are interpreted (actually compiled into bytecode and run on a vm). If you want pure speed you need assembler! No ifs, ands or buts. From grante at visi.com Tue Jun 29 12:52:49 2004 From: grante at visi.com (Grant Edwards) Date: 29 Jun 2004 16:52:49 GMT Subject: win32 pyserial requires javax.comm for py2exe? References: Message-ID: On 2004-06-29, Grant Edwards wrote: > Everything works fine until I add an "include serial", then > py2exe fails because > > The following modules appear to be missing > ['javax.comm'] > > Apparently serial.py imports a both the posix and java versions > of things even on a win32 platform? Removing the lines in site-packages/serial/__init__.py that import the foreign platform stuff (java, posix) fixes things. Platform-dependant imports are "a bad thing" when you want to package up stuff with py2exe -- you end up with Mac and Unix and Java stuff in your distribution since py2exe has no way to tell which conditional imports to pay attention to. -- Grant Edwards grante Yow! I once decorated my at apartment entirely in ten visi.com foot salad forks!! From abra9823 at mail.usyd.edu.au Mon Jun 28 08:33:04 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon, 28 Jun 2004 22:33:04 +1000 Subject: if statement Message-ID: <1088425984.40e01000e5eaf@www-mail.usyd.edu.au> hi! i get an error with the following code: num=0 if contextForm.has_key("number"): num=contextForm["number"].value else: num=0 num += 1 any idea why? the increment num+=1 is meant to be outside the if-else block thanks cheers -- Ajay Brar, CS Honours 2004 Smart Internet Technology Research Group ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From rxv at hotmail.com Sat Jun 5 22:30:56 2004 From: rxv at hotmail.com (Ike) Date: Sun, 06 Jun 2004 02:30:56 GMT Subject: Jython in a signed applet Message-ID: I have a signed JApplet which has a JTextArea wherein one can put Jython Script. Upon clicking a JButton, the script is executed. The script which executes to code is listed below. If I run the Applet in an AppletViewer, it runs fine. However, when run in a web browser, I am getting NullPointerException's (I copy-pasted from the Java Console these Exceptions). Please Note, I AM including jython.jar in the ARCHIVE parameter of the HTML containing the JApplet. Anyone have any idea why I cannot get this to run in a signed applet? Does anyone execute script in a signed applet - would you be willing to show me how to call this from Java, and what the Applet tag looks like that works for you? Thanks, Ike PythonInterpreter inter_py; //class-scope variable //the following occurs in the ActionListnener when the JButton is clicked if(inter_py==null){ try{ PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[] {""}); inter_py = new PythonInterpreter(); }catch(PyException pyex){ pyex.printStackTrace(); }catch(Exception exc){ exc.printStackTrace(); } } try{ inter_py.exec(bsTextArea.getText()); }catch(PyException pyex){ pyex.printStackTrace(); }catch(Exception exc){ exc.printStackTrace(); } java.lang.NullPointerException at org.python.core.PyJavaClass.lookup() at org.python.core.PyObject.() at org.python.core.PySingleton.() at org.python.core.PyNone.() at org.python.core.PySystemState.initStaticFields() at org.python.core.PySystemState.initialize() at org.python.core.PySystemState.initialize() at org.python.util.PythonInterpreter.initialize() at GG.GGUser$10.run() at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) java.lang.NullPointerException at GG.GGUser$10.run() at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) From mithrandi-mplayer-dev-eng at mithrandi.za.net Sun Jun 27 12:11:28 2004 From: mithrandi-mplayer-dev-eng at mithrandi.za.net (Tristan Seligmann) Date: Sun, 27 Jun 2004 18:11:28 +0200 Subject: help with creating a mysql query string In-Reply-To: References: <3SvDc.22042$NK4.3722156@stones.force9.net> Message-ID: <20040627161128.GB3603@mithrandi.za.net> On Sun, Jun 27, 2004 at 07:58:09 -0400, Sean Ross wrote: > > "RiGGa" wrote in message > news:3SvDc.22042$NK4.3722156 at stones.force9.net... > [snip] > > > > sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" > > > [snip] > > sqlquery = "INSERT INTO " + tablename + " values(%s,%s,%s)"%datavalue Rather do something like: sqlquery = "INSERT INTO %s values(%%s,%%s,%%s)" % tablename cursor.execute(sqlquery, datavalue) The other way allows datavalue to contain arbitrary SQL that will be executed, which can be a nasty security hole depending on where the value comes from. -- mithrandi, i Ainil en-Balandor, a faer Ambar From fumanchu at amor.org Thu Jun 10 11:14:27 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 10 Jun 2004 08:14:27 -0700 Subject: regex query Message-ID: km wrote: > how do i include variable as a part of the regex string ? - i > mean variable interpolation. like : > ##########code ########## > #!/usr/bin/env python > import re > str = "abc" > p = re.compile('str') # defeats the purpose - literal string 'str' > ##########code ########## > any suggestions ? 1. Don't use 'str' as a variable name; it's a builtin which you've just clobbered (I couldn't resist ;) 2. Is there some reason you didn't try: import re atom = "abc" p = re.compile(atom) ...? Robert Brewer MIS Amor Ministries fumanchu at amor.org From mrjean1ATcomcastDOTnet at no.spam.net Wed Jun 30 19:19:10 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Wed, 30 Jun 2004 23:19:10 GMT Subject: Time delay loop - better way? References: Message-ID: <300620041630234225%mrjean1ATcomcastDOTnet@no.spam.net> For short time periods, you could use import time ... time.sleep(1.0) # seconds wxPython may also provide a sleep function. /Jean Brouwers ProphICy Semiconductor, Inc. In article , Conrad wrote: > Greetings, > > Q: Is there some way to gracefully suspend a python app for a second or > so then resume? I could write the classic basic dumb > loop-tenzillion-times delay, but that seems inelegant, and well, just > wrong. By the way, I'm also using wxPython, if that helps any. > > I need to delay a python program for about a second. Googling around, it > looks like most of the timer stuff has to do with thread handling, but my > application is not threaded, just a small app that has problems printing > to a serial label printer if there's not some delay between labels. The > best solution would be if the freakin printer worked right, but I've tried > all the possible flow control settings in pyserial and the windows > com port, and apparently there just has to be some magic undocumented > delay between labels, or they get screwed up. > > Not a huge crisis, I admit, as I can work around with a dumb loop, but > again - I know there's a more correct way to do this. > > Thanks, > > Conrad > > From peter at engcorp.com Mon Jun 21 10:53:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 10:53:45 -0400 Subject: Creating subclassess (newbie) In-Reply-To: <20040621153854.14f10a9f@debian> References: <20040621153854.14f10a9f@debian> Message-ID: Adam wrote: > I have a subclass I want to create- my intuition told me > that it would be done like this: > > class MainClass: > class SubClass: > code... > subclassinstance = SubClass() > mainclassinstance = MainClass() Have you followed through the tutorial in the documentation? The section on classes covers inheritance in a basic way. See http://www.python.org/doc/current/tut/node11.html#SECTION0011500000000000000000 -Peter From peter at engcorp.com Sat Jun 19 23:31:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 23:31:15 -0400 Subject: Another MSIE Python Question In-Reply-To: <22b7fd40.0406191854.2390d1a2@posting.google.com> References: <22b7fd40.0406190617.a33514@posting.google.com> <22b7fd40.0406191854.2390d1a2@posting.google.com> Message-ID: Ralph A. Gable wrote: [traceback snipped] So what if you drop the '.1' from the end of the AppId, and also make sure you have the "ie.Visible = 1" in there? Can you upgrade to the latest versions of Python and pywin32 as well? I notice you are using 2.2 still... (No idea if any of these things will help... I'm spending a lot of time struggling with COM right now as well, though with troubles in entirely different areas.) -Peter From djordan8 at houston.rr.com Fri Jun 18 14:59:11 2004 From: djordan8 at houston.rr.com (Doug Jordan) Date: Fri, 18 Jun 2004 18:59:11 GMT Subject: cannot pass a variable from a function References: <56cfb0e3.0406162048.5eeba56@posting.google.com> Message-ID: <3YGAc.1638$1L2.1028@fe1.texas.rr.com> this seems to work only if c in def(c) is a list. I have a tuple of tuples. I need to operate on one of the members of adata pair and return a new tuple of tuples to be used later in the program. if I use the following, it only returns 1 value. tup1=((1,3),(2,5),(3,9)) def NewFctn(c): for a,b in c: v=b*9 return v y=NewFctn(tup1) what I need is to return v as a tuple of tuples to be used later in the program. How do I do this. I cannot find any information on this. This is needed because I need to perform some operations on the second member of data pairs stored as a tuple of tuples. This is needed to post process output from a commercial program(ABAQUS) ie. Output variable might contain ((t1,F1),(t2,F2)..(tn,Fn)) I want to perform operations on Fi Thanks Sorry about all the confusion Doug "Porky Pig Jr" wrote in message news:56cfb0e3.0406162048.5eeba56 at posting.google.com... > "Doug Jordan" wrote in message news:... > > I am fairly new to Python. This should be an easy answer but I cannot get > > this to work. The code is listed below. I know how to do this in C, > > Fortran, and VB but it doesn't seem to work the same way here. > > I would appreciate any help. > > > > #try this to pass a list to a function and have the function return > > #a variable > > #this works > > list=[1,4,6,9] > > def fctn(c): > > for h in c: > > q=h*80 > > print q > > You know, I am also new to Python, and fairly well versed in C, but > don't you think that the following function: > > > #function suppose to return variable > > def fctn2(c): > > for h in c: > > q=h*80 > > return q > > will return whatever it gets on a very first iteration so it will > return a scalar 1*80 rather than list I assume you are trying to > return. > You probably need something like this: > def fctn2(c): > return [h * 80 for h in c] > > > > Once again, you didn't make it quite clear what is that exaclty you > are trying to return, so I assume you are trying to return a list, > rather than scalar. From XXNOSPAMXX at gibts.net Wed Jun 30 06:44:00 2004 From: XXNOSPAMXX at gibts.net (Thomas Reichelt) Date: Wed, 30 Jun 2004 12:44:00 +0200 Subject: Status of PEPs? Message-ID: <2kfjf7F1nk33U1@uni-berlin.de> Hello Python-Fans, A few months in the past, I learned the Python language and was very pleased of it. I have now written many scripts for myself and this opinion stayed, not to say, it became more intensive. Recently I have discovered the PEP Archive, and my question is now this: There are many open ("under consideration") PEPs that would incorporate useful features into the language, such as the do-while statement, the switch statement or the __main__ function. However, most of these proposals are several years old. Though implementations seem to exist for the proposals, no action is taken about them. Why is this so? What has to be done for a proposal to make it into the language? Thank you for answering a dumb question... -- greetz tom From rupole at hotmail.com Fri Jun 25 12:01:56 2004 From: rupole at hotmail.com (Roger Upole) Date: Fri, 25 Jun 2004 12:01:56 -0400 Subject: Odd behaviour of os module with a Win2k shared directory References: Message-ID: <40dc4c04_1@127.0.0.1> I think this is actually due to the library removing a trailing backslash. If you put 2 trailing backslashes on the path to a share, you get True back. Roger "Larry Bates" wrote in message news:quGdnZ3Wk6SKpEHdRVn-vA at comcast.com... > When you access a share on Windows 2000 machine it acts > as if it is the root directory. That being said your > command checked to see if dietplan6 had a file/folder > inside of it named dietplan6. If you can see the share > then it exists. If you want to test for the existence > of the dietplan6, you would need to define your share > one level up in the tree. Think of it this way, you > can't test for the existence of the root directory. > > HTH, > Larry Bates > Syscon, Inc. > > "David Hughes" wrote in message > news:memo.20040625144135.2040A at forestfield.cix.co.uk... > > I shared a directory, dietplan6, which is actually several levels down in > > C:\Program files\ on a Windows 2000 machine, called 'Nom'. When I tried to > > check its existence from another Win2k machine, I got the following > > strange results: > > > > Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on > > win32 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import os > > >>> pth = r'\\nom\dietplan6' > > >>> os.path.exists(pth) > > False > > >>> os.listdir(pth) > > ['unins000.dat', 'program', 'database', 'resource', 'doc', 'dlm', > > 'dp5conv', 'gs', 'Readme.txt', 'dietplan.lic', 'users', 'imports', > > 'unins000.exe', 'locks'] > > >>> os.path.exists(os.path.join(pth, 'program')) > > True > > >>> os.chdir(pth) > > >>> os.getcwd() > > '\\\\nom\\dietplan6' > > >>> os.path.exists(os.getcwd()) > > False > > >>> > > > > -- > > Regards, > > David Hughes > > > > From tzot at sil-tec.gr Fri Jun 25 04:20:07 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 25 Jun 2004 11:20:07 +0300 Subject: mutable default parameter problem [Prothon] References: Message-ID: On Thu, 24 Jun 2004 17:06:33 -0700, rumours say that "Mark Hahn" might have written: >No one ever asks me to repeat >a witty gem. You can say that again :) -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From apardon at forel.vub.ac.be Wed Jun 23 04:48:49 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Jun 2004 08:48:49 GMT Subject: Stopping a thread from another one References: Message-ID: Op 2004-06-23, Chris S. schreef : > Fabiano Sidler wrote: > >> Hello Newsgroup! >> >> In my Python script, I use the 'thread' module (not 'threading') and >> 'signal' simultaneously. All spawned threads execute >> 'pcapObject.loop(-1, callback)', which does not return. >> >> The problem now is: >> When the script catch a signal (let's say: SIGHUP), only the main thread >> is affected. But I need also the subthreads to be ended, because the >> script reopen()s files on SIGHUP and would also re-create the threads. >> >> NOT a solution is: >> The main thread sets a lock in the signal handler, the pcap-callback() >> function examines this lock everytime it's called, and if set, exit()s >> the thread. This is not very beautiful. >> I would prefer, if I end the subthreads by the main thread. >> Is there any chance? >> >> Greetings, >> fps > > Incorporating a flag into each thread, which is checked periodically by > the thread to decide whether or not it should end, is the safest way to > terminate threads. However, if you're looking for a preemptive method > that kills a thread unconditionally (whether the thread wants to die or > not) then search this group for 'Kthread', a module created by Connelly > Barnes, which implements a subclass of Thread incorporating this > feature. Note that killing threads preemptively is unsafe and should > only be done with care. This is why it's not part of Python's standard > threading library. I thought Python was a language for consenting adults. -- Antoon Pardon From graham__fawcett at hotmail.com Wed Jun 23 02:37:39 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 22 Jun 2004 23:37:39 -0700 Subject: http knowledge sought References: <6r3Cc.861817$Ig.9977@pd7tw2no> Message-ID: "Elaine Jackson" wrote in message news:<6r3Cc.861817$Ig.9977 at pd7tw2no>... > I want to run an http server but I don't know how to get started. I've read > through the documentation for the relevant modules, but I don't have enough http > knowledge to get the initial spark I need, and I can't seem to track down the > knowledge in question on the web or at the library. Maybe somebody can point me > toward some resources? What is it you're trying to accomplish, Elaine? There are a number of ways to write a Web server in Python, but how you intend to use that server will determine which ways are most appropriate. Probably the easiest HTTP server to write in Python is: import SocketServer import SimpleHTTPServer handler_class = SimpleHTTPServer.SimpleHTTPRequestHandler ss = SocketServer.TCPServer( ('', 80), handler_class) ss.serve_forever() which will run a Web server, serving up files from the current directory (the one from which you ran the program above). Run the program, and visit http://localhost/ to see your server in action. But chances are that's not what you need. You'll find the folks on this list are tremendously helpful, but aren't much use unless you're clear about what your end-goals are. Please elaborate! > In case you feel like answering a specific question, here's one: How does http > addressing work? I remember reading in a book about dot-separated quadruples of > numerals, written in decimal but required to be two hexadecimal digits long. > Problem is, I can't get hold of that book right now. Erm, it sounds like you're thinking about Internet Protocol (IP) addressing, which is more fundamental than HTTP. TCP and IP are the foundational protocols upon which HTTP is built; but so are FTP, telnet, SMTP (e-mail), etc. Google for "internet protocol tutorial" to learn more about IP addresses. -- Graham From dlicheri at btinternet.com Thu Jun 17 01:58:13 2004 From: dlicheri at btinternet.com (diablo) Date: Thu, 17 Jun 2004 05:58:13 +0000 (UTC) Subject: Parsing ascii file Message-ID: Hello , I have a file that contains the following data (example) and does NOT have any line feeds: 11 22 33 44 55 66 77 88 99 00 aa bb cc dd ....to 128th byte 11 22 33 44 55 66 77 88 99 00 aa bb cc dd .... and so on record 1 starts at 0 and finishes at 128, record 2 starts at 129 and finishes at 256 and so on. there can be as many as 5000 record per file. I would like to parse the file and retreive the value at field at byte 64-65 and conduct an arithmetical operation on the field (sum them all up). Can I do this with python? if I was to use awk it would look something like this : cat | fold -w 128 | awk ' { SUM=SUM + substr($0,64,2) } END {print SUM}' Regards Dean From usenet_spam at janc.invalid Sat Jun 12 21:33:22 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 13 Jun 2004 01:33:22 GMT Subject: kid wants to know more about color on the screen References: Message-ID: danb_83 at yahoo.com (Dan Bishop) schreef: > Under Linux, you can print "ANSI escape sequences" [...] > I don't know how to do it on Windows [...] Just use an ANSI device drivers for DOS/Windows. (try googling for "ansi.com", "ansi.sys", "nansi.com", ...) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From dyoo at hkn.eecs.berkeley.edu Wed Jun 23 16:42:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 23 Jun 2004 20:42:26 +0000 (UTC) Subject: how to obtain its ip address ? References: <40d9c75d$0$26573$626a14ce@news.free.fr> Message-ID: marco wrote: : I'd search a lot ... but i had not found : how can i obtain my ip address (when i'm connected to the www) ?! Hi Marco, Here's a quicky way to do it: ### import socket def getSelfIp(): """Returns the IP address of the local host.""" return socket.gethostbyname(socket.gethostname()) ### This might not work perfectly. If you want something more comprehensive, you may want to use something like the localIP() function in Webware: http://webware.sourceforge.net/Webware-0.8b2/MiscUtils/Docs/Source/Files/Funcs.py.html This appears to be a bit more systematic in getting a good local IP address. Good luck to you! From dmq at gain.com Wed Jun 16 11:20:31 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 16 Jun 2004 08:20:31 -0700 Subject: how to become a really good Python programmer? References: Message-ID: On Wed, 16 Jun 2004 01:06:41 -0500, Randall Smith wrote: >I've been programming in Python for about 2 years. I think it offers >the best combination of simplicity and power of any language I have >explored. As I write more and larger and complex programs, I need to >code better. By better I mean clearer, cleaner, more efficient and >maintainable. As the subject states, I want to become a really good >Python programmer. I learn most everything from random examples and >experience and that's good, but now I would like some sound, directed >guidance. Following Guido around would be ideal, but I will settle for >a good book. Any recommendations for learning resources? My favorite book on good programming, not Python specifically, but an accumulation of decades of experience, is The Art of Unx Programming, by Eric Raymond. If you are doing anything with user interfaces, read The Inmates are Running the Asylum, by Alan Cooper. -- Dave From lbates at swamisoft.com Sun Jun 20 09:14:10 2004 From: lbates at swamisoft.com (Larry Bates) Date: Sun, 20 Jun 2004 08:14:10 -0500 Subject: can i define a new method at runtime? References: <7b22ae5b.0406181049.479d1a61@posting.google.com> Message-ID: You are close. Try something like def verifyInteger(x): try: string.atoi(x.value) except ValueError : message(x," needs to be an integer") x.setFocus() In a dictionary put keys (controlNames) and pointers to what function (or method) to call for that controlName. verifiers={'controlName1': verifyInteger, 'controlName2': verifyFloat, ... 'controlNameN': veryfySomething} In your program call the function from the dictionary as follows: verifiers['controlName1'](x) verifiers['controlName2'](x) ... This works because the result of the getting verifiers[controlName] is a pointer to a function instead of a value. This pointer has a call method, so you can just put the arguments after it. HTH, Larry Bates Syscon, Inc. "Raoul" wrote in message news:7b22ae5b.0406181049.479d1a61 at posting.google.com... > I have a GUI application where I want to assign validation methods to > controls. > > If my control myTextBox has a change() event for on change and I want > to make it verify the input is an integer I could do... > > def myTextBox.change(): > verifyInteger(myTextBox.Value) > > def verifyInteger(x): > try: > string.atoi(x.value) > except ValueError : > message(x," needs to be an integer") > x.setFocus() > > but i have literally hundreds of these things to do.... > > I'd like to be able to say somethign like > > myTextBox.change = lambda x : verifyInteger(x) > > so when i initialize my form i'd like to run through a list that looks > like > > [["controlName1","verifyInteger"],["controlName2,"verifyFloat"],["controlNam e3 > "verifyInteger"] > > but i can't seem to make this work. > > I've tried to use exec("def foo = lambda x: do something....") > > but that doesn't seem to work.... > > Got any ideas ??? From tim.one at comcast.net Tue Jun 8 14:11:33 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 8 Jun 2004 14:11:33 -0400 Subject: Balanced tree type coming in next Python? In-Reply-To: <8nvac0dohq837c4nth3bq6tnvesc20cn7o@4ax.com> Message-ID: [Christos TZOTZIOY Georgiou] >> PS Any volunteers to port and maintain Judy arrays/trees for Python?-) >> http://judy.sourceforge.net/ They'd be an interesting alternative to >> dictionaries in some cases (esp very large dictionaries). [Thomas Guettler] > How do they compare to BTrees (ZODB)? Judy arrays are in-memory data structures, and were designed to be cache-friendly. ZODB BTrees were designed to support persistent storage in a database, and to be pickle-friendly . Because Judy uses a trie structure, depending on the data it can get large memory savings from sharing common key prefixes. Judy arrays can only be indexed by native-size integers or by byte strings. ZODB BTrees can be indexed by any Python object (whether builtin or user-defined) that defines a consistent total ordering. Both have worst-case O(log N) time for lookup, insertion, and deletion. Because of low-level tricks to reduce conflicts when multiple transactions modify a BTree simultaneously, finding the size of a ZODB BTree is actually a much more expensive operation (O(N) time, and has to touch every bucket in the BTree!). From dmq at gain.com Tue Jun 15 20:03:36 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 15 Jun 2004 17:03:36 -0700 Subject: Idle 2.3.4 won't start on Windows References: <40cece97$0$6320$65c69314@mercury.nildram.net> Message-ID: On Tue, 15 Jun 2004 11:25:25 +0100, "Sven Erik Knop" wrote: >Hi > >probably an old problem, but maybe you can help me: > >Just installed Python 2.3.4 on Windows XP SP1, and although the interpreter >runs fine, IDLE will not start. > >Any ideas how to solve this? Search with Google: IDLE start group:comp.lang.python -- Dave From axel at axel.truedestiny.net Tue Jun 22 08:58:36 2004 From: axel at axel.truedestiny.net (Axel Scheepers) Date: Tue, 22 Jun 2004 12:58:36 GMT Subject: pysnmp/shell Message-ID: <02WBc.1559$7u2.1135@amsnews03.chello.com> Hi All, Python is so great. I've been creating a small set of objects to get some stats from our adsl routers. So far it works great and fast. However, in the shell script I created over a year ago to gather stats I do: mib_lp=`$snmpwalk $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntIf Index 2>/dev/null | $grep " = $lan_iface" | $head -1 | $sed -E 's/^ip.ipAddrTabl e.ipAddrEntry.ipAdEntIfIndex.(.+) = .*/\1/g'` if [ "$mib_lp" != "" ]; then lan_ip=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipAdEntA ddr.$mib_lp 2>/dev/null | $sed -E 's/.+IpAddress: //g'` lan_netmask=`$snmpget $ip_address public ip.ipAddrTable.ipAddrEntry.ipA dEntNetMask.$mib_lp 2>/dev/null| $sed -E 's/.+IpAddress: //g'` else lan_ip="ERROR" lan_netmask="ERROR" fi To retrieve the lan settings for the router. I don't know the (lan)ip address of it but do know the interface number, that's why I check for that and then use a part of the mib to get to the netmask. This seems to be quite difficult with pysnmp (took me half an hour to write Router.SNMPQuery(self, noid) ;-)), so before I get started I wanted to ask if somebody might have better idea for this. Thanks! Kind regards, Axel Scheepers From rogerb at rogerbinns.com Sat Jun 19 23:19:36 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 19 Jun 2004 20:19:36 -0700 Subject: serial, parallel and USB port References: <3f284386$0$1922$626a54ce@news.free.fr> Message-ID: > > Why are there no module to access serial, parallel or USB port in python. > What about pySerial and pyParallel??? I use pyParallel to control stepper > motors. And if you want USB access, I have done a Python wrapper around libusb that works on Windows, Linux and Mac: http://cvs.sourceforge.net/viewcvs.py/bitpim/bitpim/native/usb/ Roger From della at toglimi.linux.it Tue Jun 1 10:33:31 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Tue, 01 Jun 2004 14:33:31 GMT Subject: question on garbage collection for python In-Reply-To: References: Message-ID: <%s0vc.85347$Qc.3361238@twister1.libero.it> David Stockwell wrote: > The questions here are: > If in my code if I forget to close a file, when will the file be > closed? Is it when something goes out of scope? Or will it close when > the python session ends? It isn't specified: it will be collected before the end of the program. I think that CPython would do it when the refcount goes to 0, whereas in Jython it will happen "sometimes in the future". Don't count on it, though! > If I define a class of somesort, is there a way I can have a destructor > method (like I would under C++ ?) The __del__ method. -- Ciao, Matteo From chuck.amadi at ntlworld.com Wed Jun 9 19:00:45 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Thu, 10 Jun 2004 00:00:45 +0100 Subject: My simple script parse output screen and to a new file! Message-ID: <40C7969D.2070000@ntlworld.com> Hi again I've bee tryinh to get print statement output from the screen to a new file. Im using the for loop I assume my target can and is a reference variable and my object is mbox. I have tried a few variations the script runs ok but when I cat the the new file it's empty but I nedd the output to flush to this new file in order to utilise and populate a database at some point. Cheers Chuck #!/usr/bin/env python import sys import os import email import mailbox import StringIO # Open the testwws user mailbox (tmp user chuck) # fp denotes factory paraemeter # mode can be 'r' when the file will only be read, 'w' for only writing #(an existing file with the same name will be erased), and 'a' opens the file # for appending; any data written to the file is automatically added to the end.# 'r+' opens the file for both reading and writing. The mode. # The File SurveyResults.txt must all ready exist. #mailout = open("/home/chuck/pythonScript/SurveyResults.txt") # mode 'w' means open the file for writ-ing # (any data already in the file will be erased) #output.writelines(mailout) #mailout = file("/home/chuck/pythonScript/SurveyResults.txt") # open() returns a file object, and is most commonly used with two arguments: # "open(filename, mode)". fp = open("/home/chuck/pythonScript/testbox") # message_from_file returns a message object struct tree from an # open file object. mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: #print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() # First open the testbox file to read(r) and write(w)to the SurveyResults.txt # open() has been depreicated use file() #fp = open("testbox","r") mailout = file("/home/chuck/pythonScript/SurveyResults.txt","a") # Read the testbox file into a list then copy to # new file. #for mail in fp.readlines(): # for in for mail in mbox: mailout.write(mail) print "testbox file copied...to SurveyResults.txt" # Now close the files #fp.close() mailout.close() #mailout.close to close it and free up any system resources taken up by the open file. # After calling output.close(), attempts to use the file object will automatically fail. From jepler at unpythonic.net Fri Jun 4 12:35:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 4 Jun 2004 11:35:46 -0500 Subject: why uses tempfile.mktemp() "@" ? In-Reply-To: References: Message-ID: <20040604163546.GN19278@unpythonic.net> I'm not sure why "@" was chosen, but I've never had any problems with it. I searched within the bash manual, and the only special meaning for @ is when it is used as a variable name in a substitution ("$@"), as a subscript in a substitution ("${name[@]}"), or when extglob is set, when followed by an open-paren ("@(a|b|c)"). @ also has special meaning when using tab-completion, but this shouldn't come into play. You can probably change the behavior at runtime with something like this: >>> import tempfile, os >>> def gettempprefix(): ... return "_%r-" % os.getpid() ... >>> tempfile.gettempprefix = gettempprefix >>> tempfile.mktemp() '/tmp/_21830-0' Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From FBatista at uniFON.com.ar Wed Jun 16 10:25:16 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 16 Jun 2004 11:25:16 -0300 Subject: Rationale for core Python numeric types Message-ID: [Matt Feinstein] #- float, short integers). I realize that there are extensions that add #- these types-- But what's the rationale for leaving them out? Have I What's the rationale to taking them in? #- wandered into a zone in the space/time continuum where people never #- have to read binary data files? What this has to do with nothing? Sorry, but don't see the relation between short integers (by the way, what is "short"?) or single precision floats and binary files. . Facundo From lbates at swamisoft.com Thu Jun 17 11:40:58 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 17 Jun 2004 10:40:58 -0500 Subject: Help - email library not working as expected References: Message-ID: I have found that the SmtpWriter class "hides" all the complexity in creating emails like you want to send. Check it out here: http://motion.sourceforge.net/related/send_jpg.py HTH, Larry Bates Syscon, Inc. "Deathstar" wrote in message news:dd2d28c8.0406170418.a4389d5 at posting.google.com... > Hi, > > I'm having some problems using the Python email library. I want to write a mail > > that has a body, and an attachment with it. From what I understand, the > > set_payload() function would be specify the body, and attach() would specify a > > MIME attachment Message. > > However this does not work. I get an error saying : > 'str' object has no attribute 'append' > > I'm doing this with Python 2.3.2 on Windows XP SP1. What am I doing wrong here? > > How do u specify the body and the attachment to the mail? > > ======== Code Snippet Start ======== > my_mail=Message() > my_mail['From']=addr_frm > my_mail['To']=addr_to > my_mail['Subject']=sub > my_mail.set_payload(bdy.read()) #Body of the mail > > > attachment=MIMEMultipart(mimetypes.guess_type(att_name)) > att=open(att_name) > attachment.set_payload(att.read()) #The attachment > > my_mail.attach(attachment) > > print my_mail.as_string() > ======== Code Snippet End ======== > > Regards, > Deathstar From tim.one at comcast.net Sun Jun 13 01:55:25 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 01:55:25 -0400 Subject: time.strftime Timezone issue In-Reply-To: Message-ID: [Allen Unueco] > As it turns out it was my mistake for using gmtime() not localtime(). Not > really any point is formating the timezone when you are asking for the > time in UTC. But it is a little strange why it should change, if anything > I would assume it would change to UTC. These are wrappers around standard C functions. C's struct tm doesn't have a time zone member, so strftime has no idea which time zone the struct tm passed to it may be intended to represent. IOW, strftime's idea of time zone doesn't come from its argument, and can not come from its argument. Its idea of whether daylight time is in effect comes from its argument's tm_isdst flag, and gmtime() always sets that to zero; gmtime() must set tm_isdst to something, and since daylight time is never in effect in UTC, 0 is the only reasonable value for gmtime() to give to tm_isdst. If you want strftime() to believe the appropriate time zone is UTC, you need to call tzset() (or some platform-dependent moral equivalent) to talk C into believing the time zone is UTC. C's time facilities are a bloody mess. > Here is the output from my Debian (woody) box > > Python 2.2.1 (#1, Feb 28 2004, 00:52:10) > [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.daylight > 1 > >>> time.strftime("%Z") > 'EDT' > >>> time.strftime("%Z", time.localtime()) > 'EDT' > >>> time.strftime("%Z", time.gmtime()) > 'EST' All as it must be . > It seems to work fine on my OSX system, although I'm confused by > time.daylight being set to '1' when it's NZST right now, down here. I should have noted this the first time: as the docs say, time.daylight doesn't say whether daylight time is in effect, it has only to do with whether the current time zone *has* a notion of "daylight time". If you want to know whether daylight time is currently in effect, time.localtime().tm_isdst is the way to spell it. > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.daylight > 1 > >>> time.strftime("%Z") > 'NZST' > >>> time.strftime("%Z", time.gmtime()) > 'NZST' > >>> time.strftime("%Z", time.localtime()) > 'NZST' Again all as it should be. If you don't want the 'NZST' result for gmtime(), you'll need to use tzset() first to change C's notion of the time zone in effect. Exactly how to do this (or even whether time.tzset() exists) depends on your platform C library; tzset() isn't a standard C function; POSIX defines tzset(), but doesn't define a set of time zone names to use with it. From mark at prothon.org Thu Jun 17 00:41:07 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 16 Jun 2004 21:41:07 -0700 Subject: mutable default parameter problem [Prothon] References: Message-ID: "Dave Brueck" wrote > > > I like more as an example: > > > > > > >>> def foo(x): > > > ... if not hasattr(foo,'list'): > > > ... foo.list = [] > > > ... foo.list.append(x) > > > ... print foo.list > > > > In Prothon: > > > > def foo(x): > > print foo.list.append!(x) > > foo.list = [] > > > > (Sorry. I couldn't resist bragging.) > > About what? Is there an echo in here? :-) From qrczak at knm.org.pl Mon Jun 14 11:28:18 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Mon, 14 Jun 2004 17:28:18 +0200 Subject: does python have useless destructors? References: <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> <7ipt83o6qp.fsf@enark.csis.hku.hk> Message-ID: On Mon, 14 Jun 2004 08:00:07 -0700, David Turner wrote: >> > The D programming language somehow contrives to have both garbage >> > collection and working destructors. So why can't Python? >> >> What happens in D when you make a pointer to a local variable, >> the variable goes out of scope, and you use the pointer? >> >> Undefined behavior? If so, it's unacceptable for Python. > > Are you suggesting that my proposed modification to the destructor > semantics will result in such misbehaviour? If so, please tell me why > you believe that to be the case. It answers "why can't Python if D can". If D works similarly to C++ here (I couldn't find the object model details described in D documentation), it trades safety for speed by embedding objects inside variables. This makes destructors easy, because you statically know when an object will be destroyed and you just don't care if someone still refers to it. But Python doesn't put objects inside variables, so it's impossible to accurately and quickly find which objects are no longer referred to. I don't believe D promises to run destructors of heap-allocated objects automatically in the very moment the last reference to it is dropped. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From dbasch at yahoo.com Wed Jun 16 22:57:23 2004 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 17 Jun 2004 02:57:23 GMT Subject: Regular expression, "except end of string", question. References: Message-ID: In article , aahz at pythoncraft.com says... > In article , > Derek Basch wrote: > > > >It always comforting to know that a really simple solution exists after > >you waste a couple of hours messing with Regular Expressions. :) > > 'Some people, when confronted with a problem, think "I know, I'll use > regular expressions." Now they have two problems.' --Jamie Zawinski > (?!...) Matches if ... doesn't match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it's not followed by 'Asimov'. That wasn't covered in my trusty (outdated) Python 2.1 Bible. I should have gone straight to the Library reference. Thanks. From rick.ratzel at scd.magma-da.com Mon Jun 21 13:17:29 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Mon, 21 Jun 2004 12:17:29 -0500 Subject: docstrings vs language comments In-Reply-To: <930ba99a.0406201027.516ea515@posting.google.com> References: <930ba99a.0406201027.516ea515@posting.google.com> Message-ID: <40d7182a$0$15832$39cecf19@news.twtelecom.net> There was a thread similar to this almost two weeks ago. While the advantages of using docstrings is obvious, I remember commenting about some of the typically minor disadvantages of docstrings which seem consistent with your belief that hash-sign comments might be better suited for stand-alone applications: --- The only perceived disadvantages that I'm aware of occur when you don't use the -OO flag. Docstrings end up in frozen executables and .pyc files, visible through the use of the "strings" command (which is a problem for people who think the information is hidden from the binary file like a comment). The binary files are also ever so slightly larger when docstrings are used instead of comments. However, using -OO removes docstrings in addition to applying optimizations...the frozen executable or resulting .pyo files have no docstrings and are a bit smaller. --- If you use a hash-sign comment, you're guaranteed that it won't be in the binaries, which is a big advantage to some if that comment contains highly sensitive documentation. --- -Rick Ratzel Sridhar R wrote: > When writing a python library, we can use docstrings for methods and > functions that are part of API. But what about comments for non-API > objects or python application code? > > For applications, docstrings are not really much useful. Instead > language comments are prefered for them. > > Language comments (starting with #) are usually considered to be a > little more readable than docstrings (when reading the source code for > understanding it). > > So for non-API objects language comments will be prefered. > > Thoughts? From chuck at smtl.co.uk Mon Jun 7 06:14:28 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Mon, 07 Jun 2004 11:14:28 +0100 Subject: simple script to read and parse mailbox In-Reply-To: Your message of "Mon, 07 Jun 2004 02:53:02 GMT." References: Message-ID: <200406071014.i57AESeb028564@sevenofnine.smtl.co.uk> Hi all exspecailly fishboy here's the script I'm just waiting to get confirmation where im going to run the script form. I have added a output =('/tmp/SurveyResults','w+a') which I believe will process the body messages data to this file for future work ie database loading. Also that using I can add 'a' opens the file # for appending any data written to the file is automatically added to the end.Is this logical .I have tried to # comments to aid my learning process So bear with me. chuck at sevenofnine:~/pythonScript> cat getSurveyMail.py ############################################################### ## This script will open and parse email messages body content. ## This Python script will reside on Mail Server on ds9: ## Emails are all plain/text you could just write the following ## Which will leave a list of strings , each one a message body. ## The Survey User is testwws and the .procmailrc file folder is ## Survey . i.e /home/testwws/Mail/inbox/Survey . ############################################################### ## file:getSurveyMail.py Created : 06/06/04 Amended date: 07/06/04 ############################################################### #The following line makes it run itself(executable script on UN*X) #!/usr/bin/env python import sys import os import email import mailbox # Open the testwws user mailbox (tmp user chuck) # fp denotes factory paremeter output =('/tmp/SurveyResults','w+a') fp = open("/var/spool/mail/chuck") #fp = open("/var/spool/mail/testwws") # message_from_file returns a message object struct tree from an # open file object. mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # for loop iterates through the msg in the mbox(mailbox). # Subparts of messages can be accessed via the - # get_payload() method will return a string object. # If it is multipart, use the "walk" method to iterate through each part and the # get the payload.In our case it's not multipart So ignore. # for part in msg.walk(): # msg = part.get_payload() # # do something(print) for msg in mbox: body = msg.get_payload() bodies.append(body) # Print to screen for testing purposes. # print the bodies list of the messages. print bodies chuck at sevenofnine:~/pythonScript> vi getSurveyMail.py chuck at sevenofnine:~/pythonScript> python getSurveyMail.py [] The last line I assume would list all the body messages within the bodies list []/ Cheers for all your help list. From justblame at 123.cl Fri Jun 25 19:06:39 2004 From: justblame at 123.cl (Adrian Albisser) Date: Fri, 25 Jun 2004 19:06:39 -0400 Subject: Problems with range Message-ID: <40dcaff7$1_1@nova.entelchile.net> Hey to everybody, im just beginning to program in python. So i was trying some function but always when i try the range function i get a error message. for number in range(1,100): print number Error---> There's an error in your program: expected an indented block I tried many examples i found at different tutorials but i always get the error. From ajole-1 at gci.net Wed Jun 9 18:52:14 2004 From: ajole-1 at gci.net (Patrick Stinson) Date: Wed, 09 Jun 2004 14:52:14 -0800 Subject: PyArg_ParseTuple Message-ID: <10cf5f47isr5h89@corp.supernews.com> does one need to deallocate memory assigned to char * buffers by PyArg_ParseTuple? ex: static PyObject *myfunc(PyObject *self, PyObject *args) { char *stringarg=NULL; PyArg_ParseTuple(args, "s", &stringarg); return NULL; } From jbperez808 at yahoo.com Mon Jun 21 15:48:44 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Tue, 22 Jun 2004 03:48:44 +0800 Subject: XUL like languages for addressing the Python GUI problem (was Re: Mozilla, XUL and the snake) In-Reply-To: References: Message-ID: <2jorv0F12ign5U1@uni-berlin.de> It might be a good idea if a Python module were created that supported XUL (whether based on the Mozilla, Luxor, Microsoft XAML dialect or its own, presumably improved and more pythonic, one) for GUI creation that was directly importable ala Tkinter or PyGtk. This will probably run on top of (in order of preference): a) straight Xlib (in the case of *nix) and Win32 GDI calls (and in Longhorn and beyond, Avalon subsystem calls) so as to cut the proverbial gordian knot of layers. b) [Py]Gtk or [Py]Qt c) Tkinter (with all those layers, this might result in a UI that responds even more slowly than Mozilla) Further, we might even want to do away with, or have an alternative Python syntax, for XUL in the spirit of the XUL Compact Syntax (see http://xul.sourceforge.net/compact.html ) For me, it all depends on how difficult it is to get Python to integrate with XPCOM/Mozilla gracefully the way Javascript already does today. (Seeing as how Blackwood - Java<-->Mozilla integration - has stalled, is JNI to blame or would the difficulties also apply to Python<-->Mozilla integration?) [ If it cannot be made to work as simply and straightforward as calling Javascript today (via onXXXevent='' attributes), then I don't see much of an advantage with this approach. Otoh, if it can be made so, then MozPy (and PyMoz - turns out there is such a thing!) would truly rock as in addition to XUL scripting, we would actually be able to create DHTML/DOM pages which we can client-side script via Python instead of the much hated Javascript. ] We would rather not reinvent wheels... In fact, if you think about it, XPCOM is a platform with a widget set/layout engine (with NSPR - Netscape Portable Runtime - as the OS functionality layer) that's a reinvention of what Gtk and Qt already do (and to a big extent Python, with all of its modules, is its own platform too!)! The difference with Mozilla vs Gtk/Qt is that it doesn't seem that they are offering their widget set for 'imperative' use (i.e. use programming language calls to create widgets), rather it's totally declarative (via XUL). Jakub Fast wrote: > Hi, > > Does anybody know how far you can get nowadays with trying to use Python > as the script language for XUL instead of JS? Is it possible (even > theoretically) to write full-fledged applications on the Mozilla > platform with python only? > > In a parallel vein, anybody know what the architecture of Komodo is? > > Thanks for any pointers, information, etc > > Kuba > > PS. Yes, I have seen the recently-publicized wishlist for Mozilla 2 and > I have tried to run MozPython in M1.7 or F0.9, and failed miserably. I > have been trying to dig through the Mozilla docs to find anything I > could infer this information from, but it seems that the amount of > mozilla docs that "might contain some hidden clues" piling up in front > of me is neverending... > From jcarlson at uci.edu Thu Jun 10 02:41:19 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 09 Jun 2004 23:41:19 -0700 Subject: any simple and multiplatform database? In-Reply-To: References: Message-ID: > I was thinking of using mdb (MS Access) but in linux is a bit more hard > to use it because you must install > several tools (mxODBC, etc..) How much database do you need? If you just need a dictionary-like key, value lookup table, try bsddb. Specifically the btree database, hash table databases have had a known slowdown bug for a few months now. - Josiah From chrisks at NOSPAMudel.edu Sat Jun 26 00:10:10 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 26 Jun 2004 00:10:10 -0400 Subject: a small-gui for python/win32 ? In-Reply-To: <40dbcfee$0$29370$626a14ce@news.free.fr> References: <40db01fb$0$17144$626a14ce@news.free.fr> <40dbcfee$0$29370$626a14ce@news.free.fr> Message-ID: marco wrote: > i know, i know ... i am a wx addict (i hate the render of tk) > i'm not looking for full gui cross platform > just for a simple api wich call the real dialogbox of windows > (selectfolder, selectFile(s), input a text, messagebox ...) I thought tk on windows used the native windows rendering style? At least, I couldn't tell the difference between tk and a native windows gui when I used it. From tim.one at comcast.net Sun Jun 13 17:49:10 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 17:49:10 -0400 Subject: How to get decimal form of largest known prime? In-Reply-To: <2j3pb9Ft3kn2U1@uni-berlin.de> Message-ID: [Tim Peters] >> The fastest pure-Python solution I've found consumed about 20 CPU minutes >> ... [Claudio Grondi] > I have already used such approach (see code below), but was not able to > get any improvement, even the opposite because of increase of time needed > for calculation for each next iteration step. > > Is my code not well designed? What is the difference to yours? (consider > please, that I started with Python some weeks ago and just trying to > check out the advantages and the limits) Sorry, I really can't make time to review unfamiliar code today. Instead I'll just show the code I used. It implements just enough of the BigDec class to get the problem solved (multiplication, power, and squaring), but in a general way (i.e., __mul__(), __pow__() and square() don't rely on any specifics of the problem instance). Note that BigDec instances are (like all numeric types in Python) conceptually immutable. # Compute in decimal, using 5,000-digit "digits". EXP = 5000 BASE = (5L ** EXP) << EXP # 10**EXP class BigDec(object): def __init__(self, digits): # digits is a list of base-BASE digits, least- # significant first. self.digits = digits def __mul__(self, other): # Force 'other' to have the fewer # of digits. if len(self.digits) < len(other.digits): self, other = other, self # Straightforward cross-product. Don't worry about digits # getting out of range for the duration. result = [0] * (len(self.digits) + len(other.digits) - 1) for baseindex, otherdigit in enumerate(other.digits): for i, selfdigit in enumerate(self.digits): result[baseindex + i] += selfdigit * otherdigit normalize(result) return BigDec(result) __imul__ = __mul__ def __pow__(self, n): # "The usual" left-to-right efficient exponentiation algorithm. # n must be vanilla integer, not BigDec. mask = 1L while mask <= n: mask <<= 1 mask >>= 1 # position of n's most-significant bit result = BigDec([1]) while mask: result = result.square() if n & mask: result *= self mask >>= 1 return result def square(self): # Efficient divide-and-conquer squaring, based on # (a*x+b)**2 = a**2*x**2 + 2*a*b*x + b**2. n = len(self.digits) if n <= 5: return self * self nlo = n // 2 lo, hi = BigDec(self.digits[:nlo]), BigDec(self.digits[nlo:]) result = lo.square().digits result += [0] * (2*nlo - len(result)) result += hi.square().digits for elt in (lo * hi).digits: result[nlo] += elt << 1 nlo += 1 normalize(result) return BigDec(result) def __str__(self): result = map(str, self.digits) # Pad all digits except for the MSD with leading zeroes. for i in xrange(len(result) - 1): digit = result[i] if len(digit) < EXP: result[i] = "0" * (EXP - len(digit)) + digit result.reverse() return "".join(result) def normalize(x): # Force the digits in x into range(BASE), by propagating # carries. x is modified in-place. carry = 0 for i, elt in enumerate(x): carry += elt carry, x[i] = divmod(carry, BASE) while carry >= BASE: carry, leftover = divmod(carry, BASE) x.append(leftover) if carry: x.append(carry) # Strip insignificant leading 0 digits. while x and x[-1] == 0: x.pop() x = BigDec([2]) ** 24036583 # subtract 1 assert x.digits[0] != 0 x.digits[0] -= 1 print x From Holger.Joukl at LBBW.de Tue Jun 8 06:07:47 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Tue, 8 Jun 2004 12:07:47 +0200 Subject: Python 2.3.3 signals, threads & extensions: signal handling problem[Resolved] Message-ID: Stupid me: This is what I found in the script code: print '*** Note: you need to kill this with SIGKILL ***' Testing the code again I see the same behaviour for python 1.5.2 and python 2.3.3 (the signal handler, installed in the main thread, not getting the signals *most of the time*). Seems like it was one of those days the other time. Thank you to Andrew and fishboy. Cheers Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From michael.anckaert at pi.be Mon Jun 28 07:17:47 2004 From: michael.anckaert at pi.be (Michael Anckaert) Date: Mon, 28 Jun 2004 13:17:47 +0200 Subject: what editor do you use? In-Reply-To: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. vim Hard to learn, but once you get to know it, you'll never want anything else. A friend of mine uses emacs and we held a 'speedcontest', we had to edit a file with our editors and write some code. Me and vim were about 50% faster than him and emacs. But I don't want to start any vim vs. emacs flamewar :-) -- Met vriendelijke groeten, Kind regards, Michael Anckaert michael.anckaert at pi.be From BELLEMAIL-SA at exponent.com Thu Jun 24 06:22:12 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 24 Jun 2004 03:22:12 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28FA0@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = belred1 at yahoo.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 302 Scanning time = 06/24/2004 03:22:12 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment nothing.zip contained WORM_NETSKY.C virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From kenneth.m.mcdonald at sbcglobal.net Thu Jun 10 18:24:48 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Thu, 10 Jun 2004 22:24:48 GMT Subject: ANN: 'rex', a module for easy creation and use of regular expressions Message-ID: This is a 'pre-release' release of the 'rex' module, a Python module intended to ease the use of regular expressions. While I think the code is currently quite useful, I'm advising against using it except on an experimental basis, as the API is subject to change. One of the purposes of this release is to solicit feedback on the final API. The module is available as two text files appended at the end of this message: '__init__.py' should be placed in a folder called 'rex' on your python path, while the test file can be placed anywhere, and simply does some basic testing of rex. I'd attempted to release this about a week ago with a uuencoded copy of the module, but I believe my news service disallowed that message; at least, I never saw it on my news feed. Sorry if this is a repeat. Immediately below are a couple of snippets from the internal rex documentation, to give you an idea of what rex does. I hope this will intrigue you enough to try and to give me feedback. rex is free software. At this point, I would greatly appreciate feedback. Do you think this could be a useful module? Do you have any suggestions for the API? What would you like to see for additional functionality? If there is sufficient enthusiasm, I would certainly welcome code or documentation contributions. But we'll worry about that if it turns out enough people are interested... :-) A Bit About rex... ================== 'rex' stands for any of (your choice): - Regular Expression eXtensions - Regular Expressions eXpanded - Rex, King of Regular Expressions (ha, ha ha, ha). rex provides a completely different way of writing regular expressions (REs). You do not use strings to write any part of the RE _except_ for regular expression literals. No escape characters, metacharacters, etc. Regular expression operations, such as repetition, alternation, concatenation, etc., are done via Python operators, methods, or functions. As an example, take a look at the definition of an RE matching a complex number, an example included in test_rex.py. The rex Python code to do this is: COMPLEX= PAT.aFloat['re'] + \ PAT.anyWhitespace + \ ALT("+", "-")['op'] + \ PAT.anyWhitespace + \ PAT.aFloat['im'] + \ 'i' while the analogous RE is: (?P(?:\+|\-)?\d+(?:.\d*)?)\s*(?P\+|\-)\s*(?P(?:\+|\-)?\d+(?:.\d*)?)i The rex code is more verbose than the simple RE (which, by the way, was the RE generated by the rex code, and is pretty much what you'd produce by hand). It is also FAR easier to read, modify, and debug. And, it illustrates how easy it is to reuse rex patterns: PAT.aFloat and PAT.anyWhitespace are predefined patterns provided in rex which match, respectively, a string representation of a floating point number (no exponent), and a sequence of zero or more whitespace characters. FILE __init__.py ============================================================================ '''Module to provide a better interface to regular expressions. LICENSE This is the 'rex' module, written by Kenneth M. McDonald, (c) 2004 Kenneth M. McDonald. You may use it for any reason, subject to the following simple conditions: 1) You may not distribute or publish modified versions of this module or files in it, unless you change the name of the module. 2) You may incorporate this code into other files. If you use more than 30 lines (total) of code/text from this module in another file or group of files, you must include a line stating "Some of the code in this file/these files are from the free Python module 'rex', by Kenneth M. McDonald." 3) If you sell or otherwise gain revenue from a product using this code, then: a) The product or its documentation must state, in a reasonably prominent place, "Some of the functionality of this program is provided by freely available source code", or words to that effect. Incorporating this phrase in the 'About' box of the program, or in the introduction to the User's manual, will satisfy the requirement of 'reasonable prominence'. You do not need to mention this module specifically, nor do you need to indicate what functionality this module is used for. b) You must ensure the buyers of the product have access to the source code for this module. You can do this by including this module with your software, by providing a URL to a download site for this module (I do not maintain such a URL), or by other similar means. INTRODUCTION 'rex' stands for any of (your choice): - Regular Expression eXtensions - Regular Expressions eXpanded - Rex, King of Regular Expressions (ha, ha ha, ha). rex provides a completely different way of writing regular expressions (REs). You do not use strings to write any part of the RE _except_ for regular expression literals. No escape characters, metacharacters, etc. Regular expression operations, such as repetition, alternation, concatenation, etc., are done via Python operators, methods, or functions. The major advantages of rex are: - rex expressions are checked for well-formedness by the Python parser; this will typically provide earlier and easier-to-understand diagnoses of syntactically malformed regular expressions - rex expressions are all strings! They are, in fact, a specialized subclass of strings, which means you can pass them to existing code which expects REs. [NOTE: This may change in the future.] - rex goes to some lengths to produce REs which are similar to those written by hand, i.e. it tries to avoid unnecessary use of nongrouping parentheses, uses special escape sequences where possible, writes 'A?' instead of 'A{0,1}', etc. In general, rex tries to produce concise REs, on the theory that if you really need to read the buggers at some point, it's easier to read simpler ones than more complex ones. - [This is the biggie.] rex permits complex REs to be built up easily of smaller parts. In fact, a rex definition for a complex RE is likely to end up looking somewhat like a mini grammar. - [Another biggie.] As an ancillary to the above, rex permits REs to be easily reused. As an example, take a look at the definition of an RE matching a complex number, an example included in the test_rex.py. The rex Python code to do this is: COMPLEX= PAT.aFloat['re'] + \ PAT.anyWhitespace + \ ALT("+", "-")['op'] + \ PAT.anyWhitespace + \ PAT.aFloat['im'] + \ 'i' while the analogous RE is: (?P(?:\+|\-)?\d+(?:.\d*)?)\s*(?P\+|\-)\s*(?P(?:\+|\-)?\d+(?:.\d*)?)i The rex code is more verbose than the simple RE (which, by the way, was the RE generated by the rex code, and is pretty much what you'd produce by hand). It is also FAR easier to read, modify, and debug. And, it illustrates how easy it is to reuse rex patterns: PAT.aFloat and PAT.anyWhitespace are predefined patterns provided in rex which match, respectively, a string representation of a floating point number (no exponent), and a sequence of zero or more whitespace characters. USE This is a quick overview of how to use rex. See documentation associated with a specific method/function/name for details on that entity. In the following, we use the abbreviation RE to refer to standard regular expressions defined as strings, and the word 'rexp' to refer to rex objects which denote regular expressions. - The starting point for building a rexp is either rex.PAT, which we'll just call PAT, or rex.CHAR, which we'll just call CHAR. CHAR builds rexps which match single character strings. PAT builds rexps which match strings of varying lengths. - PAT(string) returns a rexp which will match exactly the string given, and nothing else. - PAT._someattribute_ returns (for defined attributes) a corresponding rexp. For example, PAT.aDigit returns a rexp matching a single digit. - CHAR(a1, a2, . . .) returns a rexp matching a single character from a set of characters defined by its arguments. For example, CHAR("-", ["0","9"], ".") matches the characters necessary to build basic floating point numbers. See CHAR docs for details. - Now assume that A, B, C,... are rexps. The following Python expressions (_not_ strings) may be used to build more complex rexps: - A | B | C . . . : returns a rexp which matches a string if any of the operands match that string. Similar to "A|B|C" in normal REs, except of course you can't use Python code to define a normal RE. - A + B + C ...: returns a rexp which matches a string if all of A, B, C match consecutive substrings of the string in succession. Like "ABC" in normal REs. - A*n : returns a rexp which matches a number of times as defined by n. This replaces '?', '+', and '*' as used in normal REs. See docs for details. - A**n : Like A*n, but does nongreedy matching. - +A : positive lookahead assertion: matches if A matches, but doesn't consume any of the input. - ~+A : negative lookahead assertion: matches of A _doesn't_ match, but doesn't consume any of the input. - -A, ~-A : positive and negative lookback assertions. Lke lookahead assertions, but in the other direction. - A[name] : name must be a string: anything matched by A can be referred to by the given name in the match result object. (This is the equivalent of named groups in the re module). - A.group() : A will be in an unnamed group, referable by number. - In addition, a few other operations can be done: - Some of the attributes defined in PAT have "natural inverses"; for such attributes, the inverse may be taken. For example, ~ PAT.digit is a pattern matching any character except a digit. - Character classes may be inverted: ~CHAR("aeiouAEIOU") returns a pattern matching anything except a vowel. - 'ALT' gives a different way to denote alternation: ALT(A, B, C,...) does the same thing as A | B | C | . . ., except that none of the arguments to ALT need be rexps; any which are normal strings will be converted to a rexp using PAT. - 'PAT' can take multiple arguments: PAT(A, B, C,...), which gives the same result as PAT(A) + PAT(B) + PAT(C) + . . . . - Finally, a very convenient shortcut is that only the first object in a sequence of operator/method calls needs to be a rexp; all others will be automatically converted as if PAT[...] had been called on them. For example, the sequence A | "hello" is the same as A | PAT("hello") 'CHAR' USE CHAR(args...) defines a character class. Arguments are any number of strings or two-tuples/two-element lists. eg. CHAR("ab-z") is the same as the regular expression r"[ab\-z]". NOTE that there are no 'character range metacharacters'; the preceding define a character class containing four characters, one of which was a '-'. This is a character class containing a backslash, hyphen, and open/close brackets: CHAR(r"\-[]") or CHAR("\\-[]") Note that we still need to use raw strings to turn off normal Python string escaping. To define ranges, do this : CHAR(["a","z"], ["A","Z"]) To define inverse ranges, use the ~ operator, eg. To define the class of all non-numeric characters: ~CHAR(["0","9"]) Character classes cannot (yet) be doubly negated: ~~CHAR("A") is an error. ''' import re, string def _escapeSpecialRangeChars(char): '''Function to escape characters which have a special meaning in character ranges. We don't actually need to escape '[', but I think it makes the string representation a little less confusing.''' if char in "^-\\[]": return "\\"+char else: return char class _rexobj(str): '''Class of strings which are to be treated as regular expressions.''' def __init__(self, s): str.__init__(self, s) def compile(self, ignorecase=False, locale=False, multiline=False, dotmatchesnewline=False, unicode=False): flags = (ignorecase and re.IGNORECASE) | \ (locale and re.LOCALE) | \ (multiline and re.MULTILINE) | \ (dotmatchesnewline and re.DOTALL) | \ (unicode and re.UNICODE) return re.compile(self, flags) def __mul__(self, num): '''Greedy repetition operator''' return self.repeat(num) def __pow__(self, num): '''Nongreedy repetition operator''' return self.repeat(num, greedy=False) def __pos__(self): '''Lookahead assertion''' return _relookaheadassertion("(?=%s)" % (self, )) def __neg__(self): '''Lookback assertion''' return _relookbackassertion("(?<=%s)" % (self, )) def __contains__(self, text): '''Another abuse of operators. A regular express can be considered as the set of all strings it can match (or generate, for those of you who know the theory.) The code if text in rexp: body executes 'body' if text is in the set of strings generated by the rexp, and false otherwise. ''' pattern = PAT.stringStart + self + PAT.stringEnd return bool( pattern.match(text) ) def repeat(self, num=0, greedy=True, doc=None): '''This is the repetition function. However, repetition is normally done with the * (greedy) operator, or ** (nongreedy) operator, like so: A*3 : Three or moreoccurrences of A. A*0 : In re terms, same as A* A*1: In re terms, same as A+ A*(2, 4) : 2-4 occurrences of A. In re terms, same as A{2,4} A*-5 : Up to 5 occurrences of A. In re terms, same as A{0,5} A*-1 : In re terms, same as A? A**x : nongreedy versions above, like A*?, A+?, A{1,3}?. You can use repeat() as a functional equivalent; in this case, the 'num' parameter is what you would pass as the second argument to */**, 'greedy' is a boolean determining if the operation should be greedy or nongreedy, and 'doc' can be used for a documentation comment (but is not currently used in any way.) ''' min=0 max=None if isinstance(num, int): if num >=0: min=num else: max=-num else: assert isinstance(num, tuple) and len(num)==2 min, max = num if greedy: nongreedy="" else: nongreedy="?" del greedy if min==0 and max==None: return _reblock(str(self.block())+"*"+nongreedy) elif min==1 and max==None: return _reblock(str(self.block())+"+"+nongreedy) elif min==0 and max==1: return _reblock(str(self.block())+"?"+nongreedy) else: return _reblock("%s{%s,%s}%s" % (self.block(), min, max, nongreedy)) def name(self, name, doc=None): '''Enclose this RE in a named group.''' return _reblock('(?P<%s>%s)' % (name, self)) def __getitem__(self, key): if isinstance(key, str): return self.name(key) else: return str.__getitem__(self, key) def group(self, doc=None): '''Enclose this RE in a numbered group.''' return _reblock('(%s)' % (self,)) def __or__(self, other): '''Alternation (choice) operator.''' other = _convert(other) if self.precedence() > _realt.precedence(): self = self.block() if other.precedence() > _realt.precedence(): other = other.block() return _realt('%s|%s' % (self, other)) def block(self, doc=None): '''Enclose this RE, if necessary, in an anonymous block, i.e. '(?:...)'. If the RE is already in a block, it will be returned unchanged.''' if self.precedence()==0: return self else: return _reblock('(?:%s)' % (self,)) def precedence(): '''Indicates the binding precedence of the top-level operators used to form this RE. 0 is highest precedence.''' raise NotImplementedError, "precedence() should be defined in a subclass." precedence = staticmethod(precedence) def __add__(self, other): '''Concatenation operator.''' other = _convert(other) if self.precedence() > _recat.precedence(): self = self.block() if other.precedence() > _recat.precedence(): other = other.block() return _recat('%s%s' % (self, other)) def itersearch(self, text, matched=None): '''Iterates sequentially throught nonoverlapping substrings in 'text' which match and do not match self. See docs on match results. @param matched: If None (the default), returns both substrings from text matching the pattern, and those substrings between the matches. If true, returns only the matching substrings. If false (other than None), returns only the nonmatching substrings. EXAMPLE: To print all digit sequences in a string: for matchresult in PAT.someDigits.itersearch(aString): if matchresult: print matchresult[0] To print all the sequences form the string that _weren't_ digits: for matchresult in PAT.someDigits.itersearch(aString): if not matchresult: print matchresult[0] ''' re = self.compile() start = 0 while True: match = re.search(text, start) # If we couldn't find any more matches, yield whatever nonmatching remnant is left, and return if not match: if not matched and start < len(text): yield MatchResult(text[start:], start, len(text)) return else: # If there was an unmatched substring before the found match, yield it. if not matched and start < match.start(): yield MatchResult(text[start:match.start()], start, match.start()) if matched==None or matched: yield MatchResult(match) start = match.end() def iterstrings(self, text, matched=None): '''Convenience function; simply extracts and returns group 0 from an underlying call to itersearch().''' for m in self.itersearch(text, matched): yield m[0] def search(self, text, matched=None): '''Returns the first element from a search of the text using itersearch and the 'matched' param''' return self.itersearch(text).next() def match(self, text): '''@todo: Not yet fully implemented, please don't use.''' return MatchResult(self.compile().match(text)) class MatchResult(object): '''A MatchResult specifies what was found by an attempt to look for an pattern in a string.''' def __init__(self, match, start=None, end=None): self.__match = match if self: self.__start = match.start() self.__end = match.end() else: self.__start = start self.__end = end def __nonzero__(self): '''A match result is 'true' if it is the result of successfully finding a pattern in a target string, in which case self.__match will be an re.MatchObj or something like that. However, match results may also be used to indicate the part of a target string that a pattern _failed_ to match; in this case, self.__match will be that part of the target, and the match result will be 'false''' return not (isinstance(self.__match, str) or self.__match == None) def __getitem__(self, key): return self.get(key) def expand(self, expansion): '''@todo: don't use this yet.''' return self.__match.expand(expansion) def get(self, key=0): '''Returns a string matching a group identified by name or by index. If this is a failed match result (see docs for '__nonzero__' in this class), the only allowable index is 0, which indicates the entire unmatched string.''' if not self: if key==0: return self.__match else: raise KeyError, "Invalid group index: "+ `key` + " (a failed match result only has one group, indexed by 0)." result = self.__match.group(key) if result==None: raise KeyError, "Invalid group index: "+ `key` return result start = property(fget=lambda self: self.__start, doc="The starting position of the match result in the search string") end = property(fget=lambda self: self.__end, doc="The ending position of the match result in the search string") string = property(fget=lambda self: self.get(), doc="The string found by the match result.") def __str__(self): return self.string class _recat(_rexobj): '''RE constructed via concatenation''' def __init__(self, s): _rexobj.__init__(self, s) def precedence(): '''The precedence of a single character can always be considered as 0, since it can't be split into subparts.''' #if len(self)==1: return 0 return 1 precedence = staticmethod(precedence) class _realt(_rexobj): '''re constructed from alternation operators''' def __init__(self, s): _rexobj.__init__(self, s) def precedence(): return 2 precedence = staticmethod(precedence) class _reblock(_rexobj): '''Superclass for all classes of res which are in a block of some sort, i.e. which do not need to be enclosed in parentheses in order to assure associativity.''' def __init__(self, s): _rexobj.__init__(self, s) def precedence(): return 0 precedence = staticmethod(precedence) class _relookaheadassertion(_reblock): _inverses = {'=':'!', '!':'='} def __init__(self, s): _reblock.__init__(self, s) def __invert__(self): assert self[0:2] == "(?" return _relookaheadassertion("(?" + self._inverses[self[2]] + self[3:]) class _relookbackassertion(_reblock): _inverses = {'=':'!', '!':'='} def __init__(self, s): _reblock.__init__(self, s) def __invert__(self): assert self[0:3] == "(?<" return _relookbackassertion("(?<" + self._inverses[self[3]] + self[4:]) class _range(_reblock): def __init__(self, s): _reblock.__init__(self, s) def __invert__(self): return _inverserange(self[0] + "^" +self[1:]) class _inverserange(_reblock): def __init__(self, s): _reblock.__init__(self, s) class _reprimitive(_reblock): '''Atomic REs, i.e. not composed of other REs. Typically single-characters, special sequences, etc.''' def __init__(self, s): _reblock.__init__(self, s) def __invert__(self): if self in _primitiveInverses: return _primitiveInverses[self] raise NotImplementedError, 'No inverse for ' + self def RAW(s): '''@todo: This is a hack to let something else work. It will go away.''' return _reprimitive(s) def _convert(s): '''Convert s to a literal rexobj; if it is already a rexobj, leave it unchanged.''' if isinstance(s, _rexobj): return s else: return _recat(re.escape(s)) def _CHARfun(*args): strings = ["["] for a in args: if isinstance(a, _reprimitive): strings.append(a) elif isinstance(a, str): strings.append("".join(map(_escapeSpecialRangeChars, a))) else: assert isinstance(a, tuple) and len(a)==2 startchar, endchar = a strings.append('%s-%s' %(_escapeSpecialRangeChars(startchar), _escapeSpecialRangeChars(endchar))) strings.append("]") return _range("".join(strings)) class _CHAR(object): def __call__(self, *args): return _CHARfun(*args) CHAR = _CHAR() MAYBE = -1 ANY = 0 SOME = 1 class _PAT(object): dot = _reprimitive(".") aChar = _reprimitive(r"[.\n]") aDigit = _reprimitive(r'\d') aWhitespace = _reprimitive(r'\s') aBackslash = _reprimitive(r'\\') anAlphanum = _reprimitive(r'\w') aLetter = _CHARfun(('a','z'), ('A','Z')) aPunctuationMark = _CHARfun("""~`!@#$%^&*()_-+={[}]|\:;"'<,>.?/""") # The standard US keyboard punctuation marks: does _not_ include whitspace chars. stringStart = _reprimitive(r'\A') stringEnd = _reprimitive(r'\Z') wordBorder = _reprimitive(r'\b') emptyString = _reprimitive('') someDigits = aDigit * 1 anyDigits = aDigit * 0 someLetters = aLetter*1 anyLetters = aLetter * 0 someChars = aChar*1 anyChars = aChar * 0 someWhitespace = aWhitespace*1 anyWhitespace = aWhitespace*0 anInt = (_convert("+")|"-")*MAYBE + someDigits aFloat = anInt + (_recat(".") + anyDigits)*MAYBE def __call__(self, arg, *rest): ''''Returns a _rexobj, a subclass of the builtin string class, which happens to know it is a regular expression.''' arg = _convert(arg) for next in rest: arg = arg + next return arg PAT = _PAT() _primitiveInverses = { PAT.aDigit : r'\D', PAT.aWhitespace : r'\S', PAT.wordBorder : r'\B', PAT.anAlphanum: r'\W', } # Fill in the reverse mappings for key, val in _primitiveInverses.items(): _primitiveInverses[val] = key def ALT(arg, *rest): '''ALT(a, b, c,...) is the same as PAT(a) | b | c | ...''' arg = _convert(arg) for next in rest: arg = arg | next return arg if __name__ == '__main__': print "Look in 'rex/__init__.py for documentation. Look in rex/_test/test_rex.py for some examples of using rex." ============================================================================= END __init__.py FILE test_rex.py ============================================================================= import unittest from rex import * class rex_test(unittest.TestCase): COMPLEX= PAT.aFloat['re'] + \ PAT.anyWhitespace + \ ALT("+", "-")['op'] + \ PAT.anyWhitespace + \ PAT.aFloat['im'] + \ 'i' def testNames(self): '''Test extraction of data from named groups.''' results = [] for c in self.COMPLEX.itersearch("3+4i 5.78- +3.14i 1. +2.i"): if c: results.append(c['re'] + c['op'] + c['im'] + 'i') self.assertEquals(results, ["3+4i", "5.78-+3.14i", "1.+2.i"]) def testCharacterRanges(self): aRange = CHAR(('a','z'), 'C', '+', '\\', '\t', "F-H[]") self.assert_('c' in aRange) self.assert_('X' not in aRange) self.assert_('\t' in aRange, 'Does the raw tab in the char range get processed correctly?') self.assert_('\n' not in aRange) self.assert_('G' not in aRange) self.assert_('-' in aRange) self.assert_('[' in aRange and ']' in aRange) def testPrecedence(self): '''Tests to ensure that '+' functions correctly as having higher precedence than '|'. This test is necessary because rex pulls a few tricks to avoid creating too many nongrouping parentheses in patterns.''' pattern = PAT('a') + 'b' | 'c' + 'd' self.assert_('ab' in pattern) self.assert_('a' not in pattern) self.assert_('b' not in pattern) self.assert_('cd' in pattern) self.assert_('c' not in pattern) self.assert_('d' not in pattern) pattern2 = PAT('a') | 'b' + 'c' | 'd' self.assert_('bc' in pattern2) self.assert_('a' in pattern2) self.assert_('d' in pattern2) self.assert_('b' not in pattern2) self.assert_('c' not in pattern2) def testLookAheadBack1(self): '''Tests lookahead and lookback assertions.''' phrase1 = "12wordOne ()wordTwo_wordThree_wordFour wordFive! wordSix3 wordSeven" # For testing purposes, this definition of a 'word' isn't really a word. aWordPat1 = PAT( ~-(PAT.aDigit | PAT("_") | PAT.aLetter), # The character before the possible word can't be a digit, underscore, or letter. PAT.someLetters, # Find the word. (+(PAT.aPunctuationMark | PAT.aWhitespace | PAT.stringEnd)) # must be followed by something which will end a word. ) self.assertEquals( list(aWordPat1.iterstrings(phrase1, matched=True)), ['wordTwo', 'wordFive', 'wordSeven'] ) def testLookAheadBack2(self): '''Tests lookahead and lookback assertions.''' phrase1 = "12wordOne ()wordTwo_wordThree_wordFour wordFive! wordSix3 wordSeven" # For testing purposes, this definition of a 'word' isn't really a word. aWordPat2 = PAT( -(~PAT.aLetter), # Check that the character before the first letter of a possible word isn't a letter... ~-PAT('_'), #...or an underscore. PAT.someLetters, # Find the word. ~+PAT.aLetter, # The following character can't be a letter. ~+(PAT("!")) # but only accept words not followed by an exclamation! ) self.assertEquals( list(aWordPat2.iterstrings(phrase1, matched=True)), ['wordOne', 'wordTwo', 'wordSix', 'wordSeven'] ) if __name__=='__main__': unittest.main() From bit_bucket5 at hotmail.com Thu Jun 3 16:02:03 2004 From: bit_bucket5 at hotmail.com (Chris) Date: 3 Jun 2004 13:02:03 -0700 Subject: Perlish dictionary behavior Message-ID: One nice thing about Perl that is helpful when tallying things up by type is that if you increment a hash key and the key does not exist, Perl puts a one there. So you can have code that does something like this: my %thingCounts; foreach my $thing() { $thingCounts{$thing}++; } (I think the syntax is right, but with Perl I never am sure). In Python, this would generate a KeyError. So you'd do something like thingCounts = {} for thing in file: try: thingCounts[thing] += 1 except KeyError: thingCounts[thing] = 1 Is there any clever way to be able to just say, like in Perl, for thing in file: thingCounts[thing] += 1 and have it do the above? Perhaps with a custom dictionary class or something? Just wondering what that might look like. Just curious. Thanks. -Chris From claird at lairds.com Wed Jun 16 18:10:04 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 16 Jun 2004 22:10:04 -0000 Subject: Script parse output screen but cant get desired output new file!. References: <84k6ygmg30.fsf@redpeanut.com> Message-ID: <10d1h9s53ci6pb9@corp.supernews.com> In article , Chuck Amadi wrote: . . . >By the way list is there a better way than using the readlines() to >parse the mail data into a file , because Im using >email.message_from_file it returns >all the data i.e reads one entire line from the file , headers as well >as just the desired body messages . > >fp = file("/home/chuck/pythonScript/testbox") >mb = mailbox.UnixMailbox(fp, >email.message_from_file) > > >mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") >for mail in fp.readlines(): > mailout.write(mail) > >Something like this> > >for mail in mb: > body = mail.get_payload() > mailout.write(body) # write only the body messages to SurveyResults.txt > >Cheers if the is a better way I can't get my head round how I can print >mail ( >only the body messages) to screen and the entire mail headers and body >to the new file. > >Hi have any one got any suggstions to my script I can parse the email >body messages to screen but I want the same desired effect to save to a >new file.I have tried a few things to no effect. . . . There's a lot going on in your message. I *think* what you want is the suggestion to replace for mail in fp.readlines(): mailout.write(mail) with mailout.write(fp.read()) -- Cameron Laird Business: http://www.Phaseit.net From mrjean1 at comcast.net Tue Jun 15 20:08:33 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Wed, 16 Jun 2004 00:08:33 GMT Subject: Proper way to kill child processes References: Message-ID: <150620041719190320%mrjean1@comcast.net> Another issue *might* be that the TERM signal is passed to the Pyton process but ignored on Solaris. Try using a different signal like SIGQUIT or maybe even SIGKILL. The shell process and all its child processes should be terminated, by convention on *nix. Also on RedHat Linux it works. There may be secondary issue with killing processes created by popen2.Popen3(). The exit status of the child processes should be checked to avoid zombies. After killing a child process do call the wait() or poll() method. The wait() methods will wait forever and may cause the parent process to hang. To avoid that use poll() in a loop until the return value is non-negative. The sample code below may help. In any case, do use the list format for the cmd. That is better if there is no compelling need for the intermediate shell process. /Jean Brouwers ProphICy Semiconductor, Inc. PS) Sample code to avoid zombie (on *nix):
      p = self.popen
      os.kill(p.pid, signal.SIGTERM)
      t = 2.5  # max wait time in secs
      while p.poll() < 0:
          if t > 0.5:
              t -= 0.25
              os.sleep(0.25)
          else:  # still there, force kill
              os.kill(p.pid, signal.SIGKILL)
              os.sleep(0.5)
              p.poll() # final try
              break
    
    In article , Bob Swerdlow wrote: > My application starts up a number of processes for various purposes using: > self.popen = popen2.Popen3("/usr/local/bin/python -O "myscript.py") > and then shuts them down when appropriate with > os.kill(self.popen.pid, signal.SIGTERM) > Everything works fine on MacOSX. However, I'm doing a port to Solaris (so I > can run it on my web site) and find that the child processes are not > stopping! Solaris is creating TWO new processes: one for the SHELL and then > another started by the shell to run my Python script. The os.kill() is > killing the shell process, not the one running my Python code. > > Actually, I really want to kill both of these processes, but I only have the > pid for the shell process. I cannot kill the whole process group because > that kills the main process, too (I tried it). > > So, what is the best way to kill both the shell process (whose pid is > available from the Popen3 object) and its child process that is running my > Python script? It looks like the python script process id is always one > greater than the shell process id of the shell process, but I'm sure I > cannot rely on that. > > Thanks, > > Bob Swerdlow > COO > Transpose > rswerdlow at transpose.com > 207-781-8284 > http://www.transpose.com > > ---------------------------------- > Fight Spam! > Add this link to your signature (as I did): http://wecanstopspam.org > Click through to find out more. > ---------------------------------- > > > From donn at drizzle.com Sat Jun 12 10:54:39 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 12 Jun 2004 14:54:39 -0000 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: <1087052078.511051@yasure> Quoth Duncan Booth : | "Roger Binns" wrote in | news:q3ipp1-4bp.ln1 at home.rogerbinns.com: ... |> But for this thread, the actual problem is that __del__ methods may |> not be called on objects, and if you read the doc implies they almost |> never will be called. So we have the counter-intuitive (and IMHO user |> hostile) situation where someone marks a class as needing extra code |> to run to destroy it, and Python addresses that by saying you will |> be lucky if the object will be destroyed (ie by not destroying the |> object). | | No, Python guarantees that the object will (almost always) be destroyed. It | just doesn't make guarantees about when that will happen. If you want | guarantees about resources being released you have to write the code to do | that yourself (e.g. with try..finally). The same applies for other | languages such as Java, or languages running in Microsoft's .Net framework. Er, Python guarantees that the object will almost always be destroyed? What the heck does that mean? | Guaranteeing that all resources will be released at a specific time has | implications for performance, and finalisers are actually pretty rare in | practice, so the usual solution is to compromise. It isn't clear to me what it takes to guarantee immediate finalization, so if it is to you, that might be worth spelling out a little more. It doesn't cost anything in the ordinary case, I mean with C Python's reference count storage model, if you get it, you get it for free. As for whether finalizers are rare in practice, of course they would be in languages like Java where they're evidently about useless, and maybe in Python where they're of limited value and more or less deprecated. It's kind of a circular argument for leaving it broken, though. (Maybe broken is the wrong word - finalization really does work. It can take some extra care to make it work reliably, but that extra attention to releasing exception tracebacks, avoiding cycles, etc., could be not altogether a bad thing.) Donn Cave, donn at drizzle.com From edcjones at erols.com Wed Jun 2 22:49:54 2004 From: edcjones at erols.com (Edward C. Jones) Date: Wed, 02 Jun 2004 22:49:54 -0400 Subject: Triple quoted repr Message-ID: <40be9310$0$2979$61fed72c@news.rcn.com> On 2003-09-04, Rasmus Fogh said: > I need a way of writing strings or arbitrary Python code that will > > a) allow the strings to be read again unchanged (like repr) > b) write multiline strings as multiline strings instead of escaping > the \n's. > > A repr function that output triple-quoted strings with explicit > (non-escaped) linebreaks would be perfect. > > Failing that, what is the simplest way to get close to the goal? There were no responses. Anyone have an answer? From nomail at nospam.no Wed Jun 23 14:56:45 2004 From: nomail at nospam.no (Dominic) Date: Wed, 23 Jun 2004 20:56:45 +0200 Subject: How to call Java from Python? In-Reply-To: <2jrnfdF1592c4U1@uni-berlin.de> References: <2jrnfdF1592c4U1@uni-berlin.de> Message-ID: There is a language interoperability project, which can by found at http://www.llnl.gov/CASC/components/ "Babel: a tool for mixing C, C++, Fortran77, Fortran90, Python, and Java in a single application. This is our cornerstone product, representing 90% of our effort. Babel is the foundation for a multilanguage scientific compoenent framework. We are often called "The Babel Team" because of this tool's visibility." However google has not found any references to it in the comp.lang.python newsgroup which is kind of strange. Is nobody using it - here? Judging from their documentation it seems quite reasonable to use for scientific projects. When they have finished the java-"server" integration it should even be perfect. ciao, Dominic From tlviewer at yahoo.com Mon Jun 28 01:30:07 2004 From: tlviewer at yahoo.com (gnu valued customer) Date: Mon, 28 Jun 2004 05:30:07 GMT Subject: know how to install GMP properly for usage by programs ? References: <89b27d52.0406271818.1feb1fae@posting.google.com> Message-ID: "Jasper" wrote in message news:89b27d52.0406271818.1feb1fae at posting.google.com... > Hello pythoners I followed the directions on how to install GNU GMP > for windows (below and on the URL) > http://www.cs.nyu.edu/exact/core/gmp/ and I don't notice any > performance gain..in Perl one is supposed to place this in the code: > use Math::BigFloat lib => 'GMP'; > > But I notice zero difference in calculation speed..I realize this is a > python board, but I am wondering if there is anyone who knows how to > verify installation, or any tricks to ensure the library is actually > being used, like executing the program in the GMP directory or > something.. any tips would be appreciated.. > Thank you, > Jasper Marzin > ****************** > Installing GMP on Windows: > Install latest Cygwin. Make sure that you choose to install "gcc", > "m4" and "make" since the default installation doesn't include them. > Download latest GMP from GNU MP to ${gmp_download}. > Run "Cygwin Bash", unzip and untar GMP into ${gmp_build} using > following command: > cd ${gmp_build} > tar xzvf ${gmp_download}/gmp-x.x.x.tar.gz > Configure GMP for compilation: > cd gmp-x.x.x > ./configure --prefix=${gmp_install} > Build GMP: > make > Install GMP header files and lib files: > make install I've followed the course outlined here http://www.kalinabears.com.au/w32perl/math_gmp.html but my build of Perl is 5.8 built with VC++ 6. You will need another module Math::BigInt::GMP, also found at that link. good luck, tlviewer From nopsoft at poczta.onet.eu Fri Jun 25 10:27:57 2004 From: nopsoft at poczta.onet.eu (Janusz U.) Date: Fri, 25 Jun 2004 16:27:57 +0200 Subject: eZ80 - correction [z80 vs Python thread] References: <40db0161$0$29542$afc38c87@news.easynet.co.uk> Message-ID: > Why not start from Stackless Python and thus have a multithreaded > language which is well suited to automata on your uc ? thanks, I'll try. > Python won't do threads on your Z80 because it relies on the OS, and you > have no OS... > Stackless has threadlets which use little memory (you need that) ! Yes, I think it maybe critical in final application. > > Perhaps you could look at the pippy project which is python on a PDA. > > They will have had to shrink python down, maybe you could use that as a > > starting point. I'll compare that. eZ80 has sometimes implemented OS like linux kernel but I'm afraid I don't use it. thx again Janusz From rmb25612 at yahoo.com Mon Jun 14 15:01:22 2004 From: rmb25612 at yahoo.com (Richard James) Date: 14 Jun 2004 12:01:22 -0700 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: <2c60f0e0.0406141101.13df93ac@posting.google.com> Peter Hansen wrote in message news:... > Ryan Paul wrote: > > > The proof is in the source. This is part of a ruby program I wrote. This > > snippet is actually a single 'line'. I broke it into several lines for > > slightly improved readability. This single line would probably take at > > least 15 lines to do in python, probably more if you wanted to do it > > intelligently. > > > > ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| > > Dir[$prefix+fn].collect {|x| > > x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| > > `cat #{sesc x}.* > #{sesc x}`} } > > This is proof of something, I'm sure, but for me it's simply another > indication that (a) Ruby is more like Perl than it is like Python, > (b) unreadable code can be written in any language, and (c) I > really don't mind using 15 lines to write something if it means > the resulting code can readily be understood. > > Thanks for reinforcing my lack of interest in switching to Ruby. :-) > > -Peter Well back in my day, in '75, "Real men" programmed in Intel binary machine codes without using those "sissy" Assembly language mnemonics... I think the value of maintainable code far outweighs cute one line coding tricks... And no matter how close to the hardware it made you feel, I really don't miss those #%$@ front panel switches! :) -- R.J. From tkpmep at hotmail.com Tue Jun 22 09:08:31 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 22 Jun 2004 06:08:31 -0700 Subject: References and copies References: Message-ID: 1. Aaaargh.........! 2. I see, said the blind man, (as he picked up his hammer and nail)....................... 3. Thanks for the insight! Thomas Philips From amartin at wpsnetwork.com Fri Jun 4 13:47:25 2004 From: amartin at wpsnetwork.com (Aurelio Martin) Date: Fri, 04 Jun 2004 19:47:25 +0200 Subject: installing cx_Oracle In-Reply-To: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> Message-ID: <2ibqtfFl8tmdU1@uni-berlin.de> Rodrigo Daunaravicius wrote: > I can't get this configuration working: > cx_Oracle 4.0.1 > Oracle 8.0.6 > Python 2.3.3 > Win NT4.0 SP6fc > > My first shot at the problem was just running the installation thingie > pre-built for win32/python2.3/Oracle8i. It installed with no complaints but > I can't import the module (can't find OCIEnvCreate entry point in the > OCI.dll library). > This version was built for Oracle 8.1.7, so I figure that must be the > problem. > > Then I downloaded the sources, but can't build them. After a fair amount of > fiddling with setup.py and some of the C header files to compensate for the > unusual file structure of my Oracle Client installation and for the use of > the gcc compilator instead of Visual Studio, I got stuck at this point: > > :>python setup.py -build -c mingw32 install > :running build > :running build_ext > :building 'cx_Oracle' extension > :D:\minGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Id:\orant\oci80\include > :-Id:\orant\rdbms80\demo -ID:\Python23\include -ID:\Python23\PC -c > :cx_Oracle.c -o build\temp.win32-2.3\Release\cx_oracle.o > :"-DBUILD_TIME="""June 04, 2004 16:42:10""" > :In file included from cx_Oracle.c:63: > :Environment.c: In function `Environment_New': > :Environment.c:78: warning: implicit declaration of function `OCIEnvCreate' > :[follows a bunch of declaration errors for anything that's named > :OCIwhatever] > > > According to the Oracle Docs, "OCIEnvCreate creates and initializes an > environment for OCI functions to work under". > > So my uneducated guess is that this OCIEnvCreate function is not present in > Oracle 8.0.6, but I can't find anything in the docs that hints to it. > > > 1. Is there a way around this OCIEnvCrete problem? > > 2. Is there an alternative to cx_Oracle that works out of the box with > Oracle 8.0.6? (tryed DCOracle2, but couldn't make it work with Python2.3 > AND without Zope) > > 3. Should I give up cx_Oracle and stick with ODBC? > > 4. Should I give up python and stick with Access VBA? (sorry, bad joke) > > > > Any insight would be helpful (even another forum where I could forward this > specific question). > > Thanks in advance, > Rodrigo Daunaravicius I had the same problem trying to connect to an Oracle 8.0.5 database. The cx_Oracle binary was compiled for Oracle 8i/9i, and it didn't work with the Oracle 8.0.5 OCI (Oracle Call Interface). Neither did the source (I think it's designed to connect to an 8i/9i OCI, different from an 8.0 OCI). The solution (for me): I installed an Oracle 8i client in another ORACLE_HOME in the same Windows box, and modified the PATH environment variable to put the BIN directory of the (new) Oracle 8i ORACLE_HOME before the BIN directory of the (old) Oracle 8.0.5 ORACLE_HOME. So, when the cx_Oracle binary looks for the OCI, it finds the Oracle8i installation and connects to the database. From your post, it's not clear to me if you have an Oracle 8.0.6 server in your machine, or not. Maybe an Oracle server installation does not like the Oracle 8i client installation and the PATH modification that I suggest. Hope this helps Aurelio From steve.menard at videotron.ca Thu Jun 17 15:01:54 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Thu, 17 Jun 2004 15:01:54 -0400 Subject: Need some help with Python/C api and threading In-Reply-To: <40d1e09d$1@newsflash.abo.fi> References: <40d1e09d$1@newsflash.abo.fi> Message-ID: Simon Dahlbacka wrote: > Steve Menard wrote: > >> Les Smithson wrote: >> >>>>>>>> "Steve" == Steve Menard writes: >> >> >> Thanks for any help you can provide, > > would this: > http://www.python.org/peps/pep-0311.html > > ..be of any help? > > /Simon YES!!!! thats exactly it!!! thanks! Though I gotta ask, in which version of Python was this introduced? It'll have a big influence over the compativility list. Steve From __peter__ at web.de Thu Jun 10 09:39:40 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jun 2004 15:39:40 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <8ef9bea6.0406091745.5f9e0aa3@posting.google.com> Message-ID: Hung Jung Lu wrote: > Jacek Generowicz wrote: >> Python has many qualities, but let's stop kidding ourselves that its >> current state is some sort of global optimum in the space of >> programming languages. A local optimum. You could argue that properties and decorators, maybe list comprehensions, are a step away from that. >> In spite of its many qualities, Python has a number of >> shortcomings. Let's stop kidding ourselves that its shorcomings are >> features. I'm confident that Python's developers are well aware of the tradeoffs they make. > Totally agree. > > Two years ago or so, the Perl newsgroup/mailing-list overshadowed > Python's newsgroup/mailing-list. Today, the opposite is true. When I > started with Python, there was one single book, and it was not even > available in most bookstore. Python has come a long way in popularity. > > However, some bad habits of Perl Mongers have been transplanted into > the Python community. In particular, blind advocacy/worship, and > refusal to hear/learn/see better features from other languages. Pythonistas know that piling up all the best of breed features will not result in the best language ever. > In term of smartness or powerfulness, Python is only about average. How did you measure that? > Python is good because it kind of sits in the middle of many possible > technological directions. But when you see comments from people that > are bilingual in Python and other languages like Self/Io, Haskell, > Lisp, etc., it's easy to see that Python is frankly kind of > second-tier player, full of limitations and problems. Are there any languages without limitations? If so, that might be the problem of those languages. It is easy to claim that Python is bad and could be better, the hard thing is to make the concrete steps in the evolvement of the language and hopefully avoid the impasses. If you have to make contributions to that, write a PEP, hack a demo implementation, and I'm sure the Python developers will listen. Peter From jepler at unpythonic.net Tue Jun 15 07:58:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 15 Jun 2004 06:58:02 -0500 Subject: Newbie question: what is causing my socket error? In-Reply-To: References: Message-ID: <20040615115802.GB8618@unpythonic.net> socket.gethostname() should return the fully-qualified name of the machine where the Python script is executing. This name would be used, I think, in the HELO step of the SMTP protocol. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From davidf at sjsoft.com Fri Jun 4 16:40:53 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 04 Jun 2004 22:40:53 +0200 Subject: Python reference In-Reply-To: <2ic34fFl7uinU1@uni-berlin.de> References: <2i96n6Fklj78U2@uni-berlin.de> <2ib5mmFkop62U2@uni-berlin.de> <2ic34fFl7uinU1@uni-berlin.de> Message-ID: Reiner Block wrote: > Hi Thomas, > > >>And to find keywords in the index of the Python docs, you could use >> > > really great this documentation. I'm searching and searching > for two possibilities: test if a string is a number (integer) or to strip > leading and trailing blanks. But it is impossible to find in the documentation > how to do it. :-( Really: I never saw a worse docu as this one. Search for "strip" will give you the second. The other is more difficult to find like this - its isdigit. But both can be found easily be saying help(str) from the Python prompt. The problem is that you've misunderstood the purpose of this web page. > > Angry greetings There's no need to be angry! He made a page that other people can find useful, and you didn't find it useful. He didn't set out to harm you... David From nomail at nospam.no Thu Jun 17 06:09:36 2004 From: nomail at nospam.no (Dominic) Date: Thu, 17 Jun 2004 12:09:36 +0200 Subject: Python interceptor package In-Reply-To: References: Message-ID: I've attached two source fragments which I had used to wrap/intercept objects. "weave" can be used to plug between an object (like a proxy). It temporarily modifies "self" so that even method calls inside an object can be trapped from the outside. (Sorry could not find a use case and I'm too lazy to write one right now.) The "trace_all" just wraps functions inside a module. Well, it probably won't help you much. But who knows. Maybe you come up with an idea :-) Ciao, Dominic ============================================= ============================================= def weave(delegate, into, for_): class X(object): def __getattribute__(self, key): def wrapper(*args,**kargs): class XX(object): def __getattribute__(self, key): if getattr(delegate, key, None): return getattr(delegate, key) else: return getattr(into, key) def __setattr__(self, key, value): if getattr(delegate, key, None): setattr(delegate, key, value) else: setattr(into, key, value) return getattr(into.__class__,key).im_func(XX(), *args, **kargs) if key in for_: # catch attribute if getattr(into, key, None): # return getattr(into, key) # else: return wrapper # catch method elif getattr(delegate, key, None): return getattr(delegate, key) else: return getattr(into, key) def __setattr__(self, key, value): print key, value setattr(into, key, value) return X() ============================================= ============================================= # wrap stuff here from trace import trace_all trace_all('fork', locals()) --------------------------------- @file ../prototype/trace.py indent = 0 hash = {} def trace(name, f): def wrapper(*args,**kargs): """wrapped""" global indent, hash print " "*indent + "%s:%s(%s,%s)" % (name, f.func_name, args, kargs) indent = indent + 1 result = f(*args,**kargs) indent = indent - 1 hash[name] = hash.get(name,{}) hash[name][f.func_name] = hash[name].get(f.func_name,0) + 1 return result return wrapper from types import FunctionType def trace_all(name, d): for k,v in d.items(): if type(v) == FunctionType and k != 'trace_all' and v.func_doc != 'wrapped': #print "Wrap %s" % k d[k] = trace(name, v) From cookedm+news at physics.mcmaster.ca Tue Jun 8 16:47:05 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 08 Jun 2004 16:47:05 -0400 Subject: Python Speed Question and Opinion References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> <40c58636$0$8219$afc38c87@news.easynet.co.uk> <3064b51d.0406080809.2b94b54c@posting.google.com> Message-ID: At some point, beliavsky at aol.com wrote: > Peter Hickman wrote in message news:<40c58636$0$8219$afc38c87 at news.easynet.co.uk>... > > > >> You are correct, it is just that if all you are concerned about is speed then >> assembler is what you need. However when you put this to people you find out >> that what they really want is 'easy to write fast programs'. Assembler comes >> with many hurdles but you are not going to get any faster using a higher level >> language. > > Do you have experience to back up your claims? > > I have not written assembler, but sources I respect tell me that good > C++ and Fortran (especially Fortran 95 with its array operations) > compilers DO let you write programs in a high-level language that are > more efficient than the hand-coded assembly you might produce (taking > infinitely longer to write). > > Given an infinite amount of programming time, very few programmers are > going to write assembly code that outperforms LAPACK (in Fortran) for > linear algrebra or FFTW (in C) for Fourier transforms. Those are interesting examples: FFTW actually uses routines coded in assembly language, and ATLAS (a common implmentation of BLAS, which underlies LAPACK), also uses assembly language. The difference is the code is generated by a program: basically, the authors have made custom compilers to determine the best combination for the architecture. In the case of ATLAS, benchmarks can be run to determine which combinations of parameters are the best for a particular machine (taking into account cache size, for instance). Some routines *are* hand-written assembly, but they're small enough, and used enough that someone sat down and thought about it long and hard. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From dave.opstad at agfamonotype.com Fri Jun 18 10:25:28 2004 From: dave.opstad at agfamonotype.com (Dave Opstad) Date: Fri, 18 Jun 2004 07:25:28 -0700 Subject: Using multiple "*"-style arguments Message-ID: File this one under "enhancement request" I guess, but it would sure be nice. I wrote this line the other day, thinking it would just work: x = struct.pack(">HhhhhhhHHHL", i, *bounds, *b[0:2], *b[6:9], len(s)) Unfortunately, it doesn't. The only valid place for an "*"-style argument is at the end of the arguments list. But this line seems so natural! Since struct.pack expects all its arguments separately (rather than gathered into a list or tuple), I have to be able to accommodate its needs, and since I had several arguments already in lists, I thought I could get away with this notation. Certainly I can get around this limitation by either spelling out the arguments (i.e. b[0], b[1], b[6]...), or by writing multiple lines of code to gather the arguments into a single list which could then have the "*" applied. But I'd love a simpler, more compact notation, not unlike what I've written above. Does anyone know of a current Python idiom for unravelling list arguments in calls? Dave From peter at engcorp.com Wed Jun 23 08:18:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 08:18:12 -0400 Subject: Encryption with Python In-Reply-To: <7x7jty7rk1.fsf@ruckus.brouhaha.com> References: <889cbba0.0406221926.3f4e5776@posting.google.com> <7x7jty7rk1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Hansen writes: > >>Besides, what you say is not possible. On my machine, >>which is about a P4 2500MHz, scanning an array.array('c') with >>22MB of data in it, doing nothing but reading each byte and >>ignoring it, takes about 8 seconds. So does converting the >>array to a list, which is pretty much all C code. Strings >>are immutable, so you can't be working with one of them... > > Well, you could do 32-bit operations which are maybe 4x faster. > You could maybe get even more speedup using built-in C functions. > For example, you could do rot13 encryption with the string.translate > method which should be quite fast. Both are good ideas, but I made an assumption that I was starting with a simple 22MB string, and the cost of converting that to 32-bit (presumably using array.array still?) would have to be taken into account, for fairness. I also assume Kamilche wasn't talking about using the builtin rot13, since he claimed to have written this himself... -Peter From davidf at sjsoft.com Wed Jun 23 04:36:47 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 23 Jun 2004 10:36:47 +0200 Subject: plot dates, print plotted data In-Reply-To: References: Message-ID: Evagelia Tsiligianni wrote: > Hello! > > I am trying to find a tool that can plot and print (plotted) data. > I need it supports plotting dates as well. > I 've tried wxPlot and chaco but each of them applies one of my requests > either printing or date plotting. Can anybody help? > > Thanks > Evagelia Try matplotlib.sourceforge.net (it has lots of backends and I'm pretty sure it supports dates for the x range) David From agriff at tin.it Wed Jun 16 02:53:15 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 16 Jun 2004 06:53:15 GMT Subject: mutable default parameter problem [Prothon] References: Message-ID: On Tue, 15 Jun 2004 22:01:19 -0800, Troy Melhase wrote: >Seriously, you see a "wart" and a "problem". I see a pleasant side-effect of >the documented semantics. True, new folks are surprised by the behavior, but >once it's understood, it becomes more powerful. > >How do you intend to account for code like this: > >def F(a, b, cache={}): > try: > return cache[(a,b)] > except (IndexError, ): > value = cache[(a,b)] = do_some_long_calc(a,b) > return value I'm new to python. To my eyes this is a pretty poor attempt to have static variables. I've implemented in the past a few scripting languages, and it's not really difficult to implement static variables... it's quite surprising for me there's no such a concept in python and just that wart... hmmm... excuse me... that bad smelling wart has to be used instead. >Or even this: > >shared_cache = {} > >def F(a, b, cache=shared_cache): > ... A global you mean ? Why not just saying "global shared_cache" at the start of the function ? If you need more power than a global then you probably a (callable) class is going to serve you better than a function. Is really a feature that if someone passes (by mistake) an extra parameter to the function the script silently swallows it and behaves strangely ? Or you also double-wrap the function, so that a(x,y) calls real_a(x,y,cache=[]) ? >Of course you can argue that this is bad style, but the counter argument is >just as strong: this is quite pythonic and quite readable. Pythonic ? In the sense that this is for example more explicit ? Are you kidding ? >Python is a tool, and you decrease the utility of that tool when you limit >it's idioms. > >> How much Python code would these different proposals break? > >A lot. I ran this: This doesn't surprise me. Static variables are useful when you don't really need the power of a class instance. Too bad that them are missing in python, and for unknown (to me) reasons they haven't been added in the evolution of the language. >$ find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} \; | wc > >And see 67 instances just in the standard library. Multiply that by a factor >of 1000, 10000 or more to reflect code in the field, and you might start to >understand the significance of changing the language definition. That something is used is one thing. That something is elegant is another. Andrea From kurt_jmed at yahoo.fr Tue Jun 1 07:35:00 2004 From: kurt_jmed at yahoo.fr (=?iso-8859-1?q?amine=20cobain?=) Date: Tue, 1 Jun 2004 13:35:00 +0200 (CEST) Subject: need help Message-ID: <20040601113500.9180.qmail@web86401.mail.ukl.yahoo.com> i'am a c++ programmer and i decided to embedding a gui python application that use wxpython for graphic user interface , and then there is a bigh problem cause when i launch a python script from c++ code the size of memory is growing up, and when i close the python application the memory size no change. i need a serious help cause the deadline for my project is near i use python 2.3.3 and wxpython 2.4.1 ............................... --------------------------------- Yahoo! Mail : votre e-mail personnel et gratuit qui vous suit partout ! Cr?ez votre Yahoo! Mail Dialoguez en direct avec vos amis gr?ce ? Yahoo! Messenger ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.ferraro at agip.it Thu Jun 17 07:45:54 2004 From: g.ferraro at agip.it (Giovanni Ferraro) Date: 17 Jun 2004 04:45:54 -0700 Subject: Cannot install PythonWin Message-ID: Please help me install my PythonWin. I start pywin32-201.win32-py2.3.exe and the procedure locates automatically in the registry my d:\progammi\python python installation... However as I click on "Next" button after this, I get the message "Can't load Python for pre-install script"... that's it... no more installation! I was unable to find any related documentation either! Am I simply cut out of PythonWin world ? Why ? I'm running Win2000 with no administrative privileges and have installed Python 2.3.4 From rupole at hotmail.com Tue Jun 22 01:37:43 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 22 Jun 2004 01:37:43 -0400 Subject: Windows XP - cron or scheduler for Python? References: Message-ID: <40d7c1cc_5@127.0.0.1> You can actually run tasks under your userid without a password if you're logged in. However, you have to set a certain flag for the task. (TASK_FLAG_RUN_ONLY_IF_LOGGED_ON) You can do this programatically using Pywin32. Roger "Peter Hansen" wrote in message news:aN2dndDVVeQO4kvdRVn-sw at powergate.ca... > Eric @ Zomething wrote: > > > I'm trying to have some scripts run periodically on Windows XP and found the "Task Scheduler" did not execute my scripts. My scripts are of the form scriptName.py, and will run just by invoking that name in the Command Prompt. > > > > Has anyone used the Windows Task Scheduler to run .py scripts, and if so is there some intracacy to it? > > I had not tried it, so I just did. My first attempt failed. As it > turned out, it was because I ignore the password field, assuming > it would be able to run anyway while I was logged in. The "status" > field in the Task Scheduler window showed the reason... once I > fixed that, it did work, either as "c:/tick.py" (make sure you > include the right path here or in the "start in this folder" field) > or as "c:/a/python23/python.exe c:/tick.py". > > If it's not working, double-check the status field to see why it > didn't work... > > -Peter From apardon at forel.vub.ac.be Wed Jun 16 11:15:06 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Jun 2004 15:15:06 GMT Subject: PIL: How to use a palette? Message-ID: Is it possible to know how many colors are in a palette and which ones? -- Antoon Pardon From tjreedy at udel.edu Fri Jun 4 12:13:41 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 4 Jun 2004 12:13:41 -0400 Subject: Python reference References: <2i96n6Fklj78U2@uni-berlin.de> <2i9e1tFkjtj8U1@uni-berlin.de><2i9g5sFjg95hU1@uni-berlin.de> <40C03D47.3000502@cenix-bioscience.com> Message-ID: "Neil Benn" wrote in message news:40C03D47.3000502 at cenix-bioscience.com... > Generally the documentation is good, remembering that this is an > open-source project and most people hate doing documentation there is a > lot of good documentation available and the books are pretty good. and remembering that the references are voluteer work... > However there problem that I've had most frequently is actually finding > the information I need (personally I don't like the 'everyone > contribute' type of documentation as there can be a lot of clutter and > repetition). I think the module index is OK but there are fundamental > things missing. For example, I have a String object and want to find a > method that can give me a starts with. Before people say I can type > dir("IT'S OBVIOUS") or simply just guess (is it startswith, starts_with, > StartsWith, etc - that's before I get to the parameters), let's assume > that I'm coming from a language without an interepter - say Java, C#, > VB, C/C++, Pascal, etc. If you have a specific suggestion, submit a SourceForge tracker item with category documentation. If you have an actual patch to the LaTex source, its a patch item. If it is pretty clearly a flaw, make a bug item. If a suggestion for improvement but not obviously a bug, make an RFE item. Many improvements to the official docs have come from such submissions! In this case, it appears that the list you wanted in in 2.3.6.1 String Methods which you find under 2.3.6 Sequence Types, etc. In the interactive interpreter, help(str) also gives a list which eventually shows | startswith(...) | S.startswith(prefix[, start[, end]]) -> int | | Return 1 if S starts with the specified prefix, otherwise return 0. With | optional start, test S beginning at that position. With optional end, stop | comparing S at that position. Terry J. Reedy From peter at engcorp.com Wed Jun 23 22:09:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 22:09:23 -0400 Subject: Efficiency of str.replace? In-Reply-To: <2junsqF15s54eU1@uni-berlin.de> References: <2junsqF15s54eU1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > For my web-based application, I need to make twelve different calls to > str.replace for the content of /every/ page on /every/ page view (or > find a harder to implement and probably less elegant solution). Would > that be a major performance hit? Consider that each call makes a new copy of the whole string. On the other hand, whether it's a major hit or not depends entirely on one thing: how many replacements are made. And how big the page is -- two things. And what you consider "major" to be. There are three things that this question depends upon, and these are.... Measurement is you only answer. Nobody else can say guess what you would consider "major". (Not to mention what you'd consider less elegant. I can think of some elegant, though less simple, solutions to the potential performance problem, but I wouldn't think for a moment of implementing them unless some profiling proved there was a real problem.) -Peter From claird at lairds.com Thu Jun 3 17:52:12 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jun 2004 21:52:12 -0000 Subject: Why did no one invent Python before? References: <40bf974a$0$12756$636a15ce@news.free.fr> Message-ID: <10bv7cclu56bmf4@corp.supernews.com> In article <40bf974a$0$12756$636a15ce at news.free.fr>, bruno modulix wrote: >Alan Gauld a ?crit : >(snip) >> >> True, although BASIC was atound in 1963 and interpreted > >I think I remember that first basic was compiled. Interpreted versions >came later... (sorry, can find the URL...) . . . Compiled first: '64. Interpreters showed up a few years later, away from Dartmouth. I haven't been able to figure out where the latter is documented. -- Cameron Laird Business: http://www.Phaseit.net From bart_nessux at hotmail.com Wed Jun 2 09:11:13 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 02 Jun 2004 09:11:13 -0400 Subject: memory error Message-ID: def windows(): import os excludes = ['hiberfil.sys', 'ipnathlp.dll', 'helpctr.exe', 'etc', 'etc', 'etc'] size_list = [] for root, dirs, files in os.walk('/'): total = [x for x in files if x not in excludes] for t in total: s = file(os.path.join(root,t)) size = s.read() size_list.append(size) s.close() windows() The above function crashes with a memory error on Windows XP Pro at the 'size = s.read()' line. Page File usage (normally ~120 MB) will rise to 300+ MB and pythonw.exe will consume about 200 MB of actual ram right before the crash. The machine has 512 MB of ram and is doing nothing else while running the script. I've written the script several ways, all with the same result. I've noticed that a binary read 'rb' consumes almost twice as much physical memory and causes the crash to happen quicker, but that's about it. Initially, I wanted to use Python to open every file on the system (that could be opened) and read the contents so I'd know the size of the file and then add all of the reads to a list that I'd sum up. Basically attempt to add up all bytes on the machine's disk drive. Any ideas on what I'm doing wrong or suggestions on how to do this differently? Thanks, Bart From jimka at rdrop.com Tue Jun 8 11:30:42 2004 From: jimka at rdrop.com (Jim Newton) Date: Tue, 08 Jun 2004 17:30:42 +0200 Subject: promoting [] by superclass? In-Reply-To: <40C580A0.A01B38A7@alcyone.com> References: <2ik7qrFo8httU1@uni-berlin.de> <2ik9hjFnvcsbU1@uni-berlin.de> <40C4FF56.F81105B@alcyone.com> <2il6llFo4tkpU1@uni-berlin.de> <40C580A0.A01B38A7@alcyone.com> Message-ID: <2im7kkFnjduhU1@uni-berlin.de> wow that is great. now the other question: class Pair(list): ... how can i "cast", "promote" [] to class Pair? Erik Max Francis wrote: > Jim Newton wrote: > > >>if that is the case then why does the following fail >> >>class another: >> pass >> >>another.__str__() >> >>I would think that would return a string such as >>"<__main__.another instance at 0x8132b64>" >>but it does not seem to. > > > Because __str__ is a special method which str defers to. If you want > the str of anObject, call str(anObject). The object will then show you > the string representation for that object. You shouldn't care whether > or not it's got that behavior from defining a __str__ method, or whether > it's gotten it from a parent class. > From tmohr at s.netic.de Wed Jun 9 16:16:38 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 09 Jun 2004 22:16:38 +0200 Subject: tp_getattrfunc, access members that are a list References: Message-ID: Hi, > For sequence like behaviour, you must implement PySequenceMethods: > sq_length, sq_item, sq_add_item for example. thanks for that hint, i'll try that one. Best regards, Torsten. From adonisv at REMTHISearthlink.net Fri Jun 18 00:09:50 2004 From: adonisv at REMTHISearthlink.net (Adonis) Date: Fri, 18 Jun 2004 04:09:50 GMT Subject: Why does one work, but not the other? References: Message-ID: ----- Original Message ----- From: "j_mckitrick" Newsgroups: comp.lang.python Sent: Thursday, June 17, 2004 9:54 PM Subject: Why does one work, but not the other? > I've done this before: > > data = [self.cong.tm[k] for k in self.cong.tm.li] > #li is list, tm is dict > > instead of: > > for k in self.cong.tm.li: > data.append(self.cong.tm[k]) > > but when I try: > > self.liststore = [[item] for item in data] > > > instead of: > > for item in data: > self.liststore.append([item]) > > I get an empty list! What gives?? > > jonathon >>> tm = {'a':1, 'b':2, 'c':3} >>> li = tm.keys() >>> data = [tm[k] for k in li] >>> data [1, 3, 2] >>> # also you can do >>> data2 = [tm[k] for k in tm] >>> data2 [1, 3, 2] Check the dictionary, make sure it has entries? When supplying the dictionary with elements given by the list, make sure the keys exist. or you can do: >>> data = [tm.get(k) for k in li] Will return None if a key does not exist to further debug. Hope this helps. Adonis From fumanchu at amor.org Thu Jun 17 23:23:43 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 17 Jun 2004 20:23:43 -0700 Subject: Using metaclasses to play with decorators. Message-ID: j_mckitrick wrote: > You guys are WAY over my head, and I'm supposed to be a C.S. > junior! :-\ > > Could someone give me an idea of what metaclasses and > decorators _are_? Sure thing. > I think metaclasses are classes with their base methods > overridden, correct? > > And decorators are a form of delegation, right? Oh, and you were doing so well until you guessed... ;) > If so, where am I wrong? And how do these techniques make > for better code/coding? Metaclasses are mind-demolition tools: http://www.python.org/2.2/descrintro.html#metaclasses As a CS student, you're probably familiar with the concept of a 'factory': a block of code which forms objects of a given class. In Python, classes are also objects. A metaclass can be thought of as a 'class factory': a factory which produces classes (as opposed to instances of classes). To say it another way, a class can loosely be considered a template for objects; a metaclass is a template for classes. Metaclasses allow you to customize the creation of classes. A common use is when you have a base class, let'a call it A, and you want to provide a behavior for each subclass "class B(A)", C, D... For example, you might want to 'register' each subclass in a module-level list. You can do this without metaclasses: class A(object): pass class B(A): custom_data = {} class C(A): funky_stuff = [] subclasses_of_A = [B, C] ...but that can get tedious, especially if you aren't writing the subclasses (perhaps you're writing a framework). Whenever anyone writes a subclass (perhaps in a different module), they have to remember to append their new subclass to subclasses_of_A. Metaclasses solve this by customizing class-creation code. In our registration example, we might write: subclasses_of_A = [] class RegisterA(type): def __init__(cls, name, bases, dct): subclasses_of_A.append(cls) class A(object): __metaclass__ = RegisterA class B(A): custom_data = {} class C(A): funky_stuff = [] Testing this (we'll save our module as 'metatest.py'), we obtain (PythonWin 2.3.2): >>> import metatest >>> metatest.subclasses_of_A [, , ] When we declare class A, we are creating a new object 'A' which happens to be a class. By giving it a __metaclass__ attribute, we can customize the creation of class A. RegisterA doesn't override type.__new__, so type.__new__ forms the new class as usual. RegisterA does override __init__, so RegisterA.__init__ gets called with our new (empty) class A as the first argument, at which point we append metatest.A to our list. I'll leave you to figure out how to exclude A but keep all the subclasses ;) Exercise 2 would be to make this mechanism generic (that is, keep subclasses_of_A separate from subclasses_of_Thing). ================================ Decorators are a very recent discussion; you might want to browse recent threads on python-dev for a lot more information. You should certainly read PEP 318 (http://www.python.org/peps/pep-0318.html). Basically, a decorator is a way to transform a function. Again, this can usually be done without metaclasses. The most-frequently-discussed examples are staticmethods and classmethods: class Thing(object): def newThing(cls, attr): t = cls() t.attr = attr return t newThing = classmethod(newThing) Decorators will hopefully provide a clearer syntax for saying the same thing (although the exact syntax is still up for debate): class Thing(object): def newThing(cls, attr) [classmethod]: t = cls() t.attr = attr return t This moves the transformation ('classmethod') closer to the function definition, rather than placing it at the end of the function. In addition, you don't have to write the name 'newThing' three times. Also, multiple transforms could be defined at once. Does that help? Waiting expectantly for a heapin' helpin' of picked nits, Robert Brewer MIS Amor Ministries fumanchu at amor.org From davidf at sjsoft.com Fri Jun 25 01:17:55 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 25 Jun 2004 07:17:55 +0200 Subject: Rolling a Container Into a String In-Reply-To: References: <889cbba0.0406241742.51a2980b@posting.google.com> Message-ID: Terry Reedy wrote: > "Kamilche" wrote in message > news:889cbba0.0406241742.51a2980b at posting.google.com... > >>I want to convert a dict into string form, then back again. After >>discovering that eval is insecure, > > > With arbitrary code from an arbitrary source, yes. > If you *know* that you are eval-ing your own safe strings, then no problem. > > >>I wrote some code to roll a Python >>object, dict, tuple, or list into a string. > > > repr(object) already does that for you. Why duplicate the work? > > You only need custom a eval function, which might check that string is safe > (no function calls, no list comps) and then eval, or which might do parsing > and construction itself. > > Terry J. Reedy > > Or use the pprint module which does nice pretty-printing David From mark at prothon.org Sat Jun 26 02:26:29 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 25 Jun 2004 23:26:29 -0700 Subject: any trick to allow anonymous code blocks in python? References: Message-ID: Doug Holton wrote: > Mark Hahn wrote: >> I'm not trolling for Prothon users, since Prothon isn't ready for >> use anyway, but I'm curious why you have to use the Python >> intepreter. Can you fill me in? > > You know better than me, but last I checked, in prothon you can't use > any of the wealth of python bindings to 3rd-party code libraries. > Perhaps eventually either prothon could be made compatible with > python, or SWIG/Boost/Pyrex etc. could be made compatible with > prothon so that it would be easy for example to compile wxpython for > prothon. wxprothon. Oh, ok. I thought you meant there was some inherent reason you had to use the Python interpreter no matter what. When I said Prothon wasn't ready I was including lack of 3rd-party libraries as one reason. We hope to have all the big ones on board by early next year. SWIG, Boost etc. will be the obvious places to start to get leverage on a lot of libs. We plan to have wxWidgets (what used to be wxWindows) as our standard GUI when we release 1.0 late this year. The only thing keeping it from being our standard might be how hard it is to install on Linux. In any case we will have our own wrapper for wxWidgets. We hope to have cool new wxWidget wrapper features that take advantage of our native OS threads and some of our unique language features like functions-as-commands and caller access (kind of like macros). It's easy to brag about it now. We haven't started on it yet. :-) From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 16:12:00 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 22:12:00 +0200 Subject: try/except/finally construct not available? In-Reply-To: References: <2kb09jF3t3eU2@uni-berlin.de> <2kbagnFc74pU2@uni-berlin.de> Message-ID: <2kbc10Fb8muU1@uni-berlin.de> Christopher Baus wrote: > Hi, > > I'm just learning python after years of C/C++/Java/bash/etc. It is going > pretty good except a few minor issues regarding syntax. I have to admit > the while/else contruct is a bit weird, but I think I understand the > motivation. But I am confused about exceptions having read the chapter in > Learning Python. > > How do I do something similar to the following java code? > > try{ > a.mightThrow(); > } > catch(Exception e){ > System.out.print("looks like an exception"); > } > finally{ > a.cleanup(); > } > > try: > pass > finally: > pass > > Doesn't allow the programmer to catch certain exceptions, handle them, and > then perform operations in either case. This is, unfortunately, a FAQ: You must use try: try: except WhatEver: finally: This is due to the fact that try-except and try-finally are two different constructs; there was a thread here not long ago, starting with Message-ID (if you use a news server to access comp.lang.python). Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From jcarlson at uci.edu Tue Jun 8 18:38:33 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 08 Jun 2004 15:38:33 -0700 Subject: simplify printing of a list In-Reply-To: <3064b51d.0406031408.1b676379@posting.google.com> References: <3064b51d.0406031408.1b676379@posting.google.com> Message-ID: > print "100%6d"%[0,1,2] The real problem is that "100%6d" already has a meaning in string formatting, though not what you like. On the most part, Python string formatting conventions follow C string formatting conventions. Python has added "%(key)s" formatting, and there may be $-formatting in the future (I stopped following that thread months ago). Again, the syntax you offer "100%6d" is already valid, if meaning something else. - Josiah From peter at engcorp.com Mon Jun 21 13:35:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 13:35:10 -0400 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: Ivan Voras wrote: > Peter Hansen wrote: > >> Larry Bates wrote: >> >>> 2) Always call Python and have it run the application. >>> Don't just try to run progname.py. >> >> This actually works, though, at least on my system. It >> might be because I inserted .py in the PATHEXT env var >> globally, though I thought it was just because running >> a .py is possible simply by clicking on it in Explorer >> (ie. the File Association does the job). > > No, putting .py in PATHEXT is necessary. That way, you can run python > programs from the command line (cmd) using just "scriptname", without > the extension! (it performs just like .bat, .exe and similar files) Are you sure? I just tried removing .py from my PATHEXT and not only did it still work from Explorer, it even worked from the command line! Then I tried redirecting the File Assocation under File Types to point to notepad instead of python. Now typing "xxx.py" at the command line or clicking on the xxx.py file in Explorer both launch Notepad to edit the file. I'm not sure what PATHEXT is really needed for, but executing .py files on the command line in Windows XP does not seem to be one of them... -Peter From dkturner at telkomsa.net Mon Jun 21 06:40:42 2004 From: dkturner at telkomsa.net (David Turner) Date: 21 Jun 2004 03:40:42 -0700 Subject: does python have useless destructors? References: <7ifz8udxp2.fsf@enark.csis.hku.hk> Message-ID: Michael Hudson wrote in message news:... > dkturner at telkomsa.net (David Turner) writes: > > [snippety] > > > We have three issues here - garbage collection (undoubtedly more > > efficient than reference counting), RAII (undoubtedly safer than > > try/finally), and PEP 310 (the "with" form). > > I fail to buy either of your 'undoubtedly's. You may be correct in > both of them, but they both require justification... > > (Besides, saying garbage collection is more efficient than reference > counting is like saying fruit is more tasty than apples). > > > I've already pointed out the problems with "with" (it's the same ball > > game as try/finally, and suffers from the same limitations). > > I must have missed that. Message-ID? For your convenience, I've summarized my arguments (briefly) in a posting here: http://dkturner.blogspot.com/2004/06/garbage-collection-raii-and-using.html (Something I didn't mention: reference counting involves atomic increments and decrements which can be expensive). > > So my opinion is that the RAII idiom should somehow be enabled in > > Python. The crucial difference between "with" and RAII here is that > > "with" requires intervention by the end-user of the object, whereas > > the RAII idiom does not. > > Well, in C++ the distincton the creator of the object makes is that > the RAIIed thing is an automatic variable, isn't it? Not necessarily. You can usefully have a shared (reference-counted) pointer to an RAII object. In fact, this is more generally useful than an automatic variable, if more expensive (it's a cover for the auto variable concept). But I do agree that C++'s auto variables led directly to the development of RAII, which might otherwise have been missed. Regards David Turner From BELLEMAIL-SA at exponent.com Wed Jun 23 22:46:05 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 19:46:05 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F84@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = eurleif at ecritters.biz Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 266 Scanning time = 06/23/2004 19:46:05 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment id43342.zip contained WORM_NETSKY.P virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From rowen at cesmail.net Wed Jun 2 14:19:10 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 02 Jun 2004 11:19:10 -0700 Subject: Problem building Python 2.3.4 on RedHat Enterprise; tcl not found Message-ID: I'm trying to build Python 2.3.4 from source on a RedHat Enterprise machine for installation in a net-wide accessible directory /net/python. I tried all of the following variants of ./configure (the first was required for Python 2.3.3 on RedHat 9): ./configure --prefix=/net/python --enable-unicode=ucs4 ./configure --prefix=/net/python ./configure --prefix=/net/python --enable-unicode=ucs2 All of these result in the ominous message (even the last form, which really surprised me): checking for UCS-4 tcl... no Having gone through the make in one case and gotten no _tkinter, I'm expecting the same results for the other two cases. Any hints? At this point I'm spinning my wheels. I'm not even sure if tcl is built with UCS-4 or UCS-2 on RedHat Enterprise. My fallback will be to build my own tcl/tk. Blasted RedHat. Python 2.3.3 was working just fine under RedHat 9, and I'd have been happy to keep using it, but Tkinter is acting flaky after the OS upgrade -- tkColorChooser.askcolor is broken (returning strings that Python has no idea what to do with). -- Russell From EX5VENNTD01-SA at Ixfin-mmarellise.com Fri Jun 18 23:22:35 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Sat, 19 Jun 2004 05:22:35 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B7420163590D@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = qrczak at knm.org.pl Recipient(s) = python-list at python.org; Subject = *SPAM* Mail Delivery (failure python-list at python.org) Scanning time = 06/19/2004 05:22:35 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The message body contained HTML_Netsky.P virus. ScanMail deleted the message body. Warning to recipient. ScanMail has detected a virus. From hgk at et.uni-magdeburg.de Wed Jun 16 02:41:10 2004 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Wed, 16 Jun 2004 08:41:10 +0200 Subject: Bug or Feature: self.__varname only as self._ClassName__varname Message-ID: Hi all, I don't know if this is feature. For me it looks like a bug?! ########################################### import sys class CTest: def __init__(self): self.test="Test" self._test="_Test" self.__test="__Test" if __name__ == "__main__": t = CTest() print t.test print t._test try: print t.__test except: print sys.exc_type print t._CTest__test ############################################ The output is: Test _Test exceptions.AttributeError __Test python is: Python 2.3.4 (#2, May 29 2004, 03:31:27) [GCC 3.3.3 (Debian 20040417)] on linux2 same on windows with python 2.3 Any comments? Best regards Hans Georg From xholcik1 at fi.muni.cz Wed Jun 16 12:34:33 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Wed, 16 Jun 2004 16:34:33 GMT Subject: regexp substitution - a lot of work! In-Reply-To: References: Message-ID: Yes, sorry, I was in such a hurry I didn't found it in the documentation, but when I want to use a lot of very different expressions using a lot of different grouping, which would be easy to implement using s/(..)/x\1x/ then it is quite problematic having to use re.sub(), isn't it? for example these perlish expressions: 's/^.*?\s*//' 's/\s*
    .*//s' 's/^(?:<[^>]>)?\t(.*?)
    /

    \1

    /' 's/\t+| {2,}/ /' 's/(<[^/][^>]*>)([^\n])/\1\n\1/' 's/(?]*>)/\n\1/' 's/ /\n/' couldn't it be easier to call external perl (or sed) ? Thanks, ---------------------------------------_.)-- | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* ----------------------------------------''-- On Wed, 16 Jun 2004, Tuure Laurinolli wrote: > Lukas Holcik wrote: > > > >> That is quite a lot of work! Don't you know some better and easier way? >> Thanks in advance, > > Why not use re.sub? > >> regexp = re.compile(..) >> result = regexp.search(data) >> while result: >> data = data[:result.start()] + .. result.group(..) + \ >> data[result.end():] >> result = regexp.search(data) >> >> ... for one regexp substitution > > > regexp = re.compile(a_pattern) > result = regexp.sub(a_replacement, data) > > Or use a callback if you need to modify the match: > > def add_one(match): > return match.group(1) + '1' > > regexp = re.compile(a_pattern) > result = regexp.sub(add_one, data) > From FBatista at uniFON.com.ar Wed Jun 16 14:32:26 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 16 Jun 2004 15:32:26 -0300 Subject: PEP 327 (Decimal data type) updated Message-ID: There's a new version of the PEP at http://www.python.org/peps/pep-0327.html This one includes a lot of fixes, the results of the last discussion in python-dev, and a new section: Documentation, which includes all the methods and attributes available (with examples!). Enjoy it! Any feedback is welcomed. . Facundo From theller at python.net Wed Jun 30 07:16:46 2004 From: theller at python.net (Thomas Heller) Date: Wed, 30 Jun 2004 13:16:46 +0200 Subject: setting icon using py2exe? References: Message-ID: Grant Edwards writes: >> 2) According to http://starship.python.net/crew/theller/moin.cgi/CustomIcons >> you can set the icon_resources in the setup.py like this: >> >> # setup.py >> from distutils.core import setup >> import py2exe >> setup(windows=[{"script":"vfcupdate.py","icon_resources":[(1,"rivatek.ico")]}]) >> >> That doesn't work either: > >> File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 577, in build_executable >> add_icon(unicode(exe_path), unicode(ico_filename), ico_id) >> RuntimeError: MapExistingFile: The handle is invalid. > > Never mind.... > > Further googling reveals this is a known bug when running under > Win98/Me: > > http://groups.google.com/groups?th=4d594c535345b98b The bug should be fixed in CVS. Since py2exe now can also be built with MingW32, you could try that, even if you don't have MSVC. Or you have to wait for the release. Thomas From sprenger at moving-bytes.de Wed Jun 9 03:39:01 2004 From: sprenger at moving-bytes.de (Peter Sprenger) Date: Wed, 09 Jun 2004 09:39:01 +0200 Subject: parsing in python Message-ID: Hello, I hope somebody can help me with my problem. I am writing Zope python scripts that will do parsing on text for dynamic webpages: I am getting a text from an oracle database that contains different tags that have to be converted to a HTML expression. E.g. "" ( # is an integer number) has to be converted to where the image data comes also from a database table. Since strings are immutable, is there an effective way to parse such texts in Python? In the process of finding and converting the embedded tags I also would like to make a word wrap on the generated HTML output to increase the readability of the generated HTML source. Can I write an efficient parser in Python or should I extend Python with a C routine that will do this task in O(n)? Regards Peter Sprenger From fowlertrainer at anonym.hu Thu Jun 24 05:55:14 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Thu, 24 Jun 2004 11:55:14 +0200 Subject: Have Zope a querystring parse routine ? (plus others) Message-ID: <40DAA502.6010004@anonym.hu> Hi ! Sorry, but zope at zope.org is not send mails to me... So I trying with that list... 1.) I want to use query-string, and post datas in combined dictionary. I have a page that I must access with special query string, but it have post datas. The simple way is to redefine the post action, not the use of hidden parameters: action="/?pid=113" But if I post that page, the pid is not in request, or request.form, because it is in query string, and Zope is use that post datas, not the query string. So query string is unparsed, and if I want to get the params, I need to parse items, and place in querydict dictionary. My parse routine (what a pity) not handle the non-us, or other special characters. How to I do it simply ? 2.) How to I avoid in Zope that request.form items are appear in request ? It is a possible way to inject variables in request from out... 3.) I there a way in Zope to get some often used routines simply ? (Aliases ?) Now I need to repeat in every pyscript: rq=context.REQUEST ... or CreateCombo=context.routines.html.CreateCombo combotext=CreateCombo(name,id,items,......) I think that often used routines are placeable in request dictionary: init.py rq=context.REQUEST oup={} # often used procs proc=context.routines.html.CreateCombo oup['CreateCB']=proc rq.set('OUP',oup) usage: rq=context.REQUEST;oup=rq['OUP'] proc=oup['CreateCB'] proc(.....) But have a Zope an alias to use the procs with simply aliases ? Thanx for help: FT From rupole at hotmail.com Tue Jun 15 17:52:41 2004 From: rupole at hotmail.com (Roger Upole) Date: Tue, 15 Jun 2004 17:52:41 -0400 Subject: Pythin createprocessasuser -- OpenProcessToken, 'Access is denied.' References: <9a361bc.0406132315.73f2db7a@posting.google.com> <40ce2028_1@127.0.0.1> Message-ID: <40cf6bcd_5@127.0.0.1> No, AdjustTokenPrivileges doesn't actually add privileges. It just enables privileges that you already have that aren't enabled by default. Administrative privileges (SE_SECURITY_NAME, SE_TCB_NAME, etc) generally aren't enabled by default. You can use win32security.LsaAddAccountRights to add extra privileges to an account. (You can only do so from an admin account, of course) Roger "Ivan Voras" wrote in message news:campmv$hih$2 at bagan.srce.hr... > Roger Upole wrote: > > > You'll probably need to call AdjustTokenPrivileges before LogonUser, since > > you need > > SE_TCB_NAME enabled for the calling process. > > Can processes started under users that don't have that privilege acquire it > just like that? From chuck at smtl.co.uk Wed Jun 9 06:46:45 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Wed, 09 Jun 2004 11:46:45 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: Your message of "Wed, 09 Jun 2004 10:20:00 BST." <200406090920.i599K0eb002672@sevenofnine.smtl.co.uk> References: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> <200406090826.i598QVeb002497@sevenofnine.smtl.co.uk> <200406090920.i599K0eb002672@sevenofnine.smtl.co.uk> Message-ID: <200406091046.i59Akjeb002862@sevenofnine.smtl.co.uk> Hi again I get output desired .Now to parse the fileobject and all body messages to an external File named SurveyResults.txt Is this the correct way to go about it . for mail in mbox: # body = mail.get_payload() # bodies.append(body) # msg = mail.message_from_file(mail) print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() # break # just look at one message # The File SurveyResults.txt must all ready exist. output = open("SurveyResults.txt", 'w') # mode 'w' means open the file for writ-ing (any data already in the file will be erased) mailout = mail.get_payload() output. writelines(mailout) output. close() # this is at end of the script Here's my error but I thought mail is my file Traceback (most recent call last): File "getSurveyMailRev2.py", line 37, in ? mailout = mail.get_payload() NameError: name 'mail' is not defined From gabor at z10n.net Wed Jun 16 05:04:07 2004 From: gabor at z10n.net (gabor) Date: Wed, 16 Jun 2004 11:04:07 +0200 Subject: is there a python icq bot? Message-ID: <1087376647.8125.2.camel@dubb> hi, is there a python icq bot somewhere? or at least a simple python icq library? thanks, gabor From aleator at jyu.fi Mon Jun 28 13:18:47 2004 From: aleator at jyu.fi (aleator) Date: Mon, 28 Jun 2004 20:18:47 +0300 Subject: Drawing with python. Message-ID: Hello. What is the recommendable means of producing bitmaps with python. Basic primitives I need are polygons, antialiased lines and ellipses. I have tried, so far, GD-module (Very slow) and Pygame(Antialiased lines are ugly, pixelated). I do not necessarily need to produce bitmaps, any image that is good for wxpython application and WWW is good enough. - Ville Tirronen From sholden at flexal.cs.usyd.edu.au Fri Jun 18 22:43:06 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 19 Jun 2004 02:43:06 GMT Subject: Game - Map data structures References: <40D39B53.13F679FF@alcyone.com> Message-ID: On Fri, 18 Jun 2004 18:48:03 -0700, Erik Max Francis wrote: > Sam Holden wrote: > >> That's going to make it really hard to determine which boats are on a >> given water tile. > > Surely if you're dealing with populating a grid of things with objects, > you're not going to do so by holding objects in each slot. You'll > implement some sort of sparse array, instead. I'm not doing it and hence don't care enough to think about how I would do it, the OP did however state: - A Water object need only links to which armies reside on the Tile (ie. sailing armies/fleets). Which imples to me that the water object has an armies list or something hanging of it. -- Sam Holden From km at mrna.tn.nic.in Mon Jun 28 15:25:30 2004 From: km at mrna.tn.nic.in (km) Date: Tue, 29 Jun 2004 00:55:30 +0530 Subject: python desktop Message-ID: <20040628192530.GA25470@mrna.tn.nic.in> Hi all, Are there any plans for a pure python desktop for linux ? are there any similar projects ? regards, KM From tdelaney at avaya.com Mon Jun 14 19:44:39 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 15 Jun 2004 09:44:39 +1000 Subject: does python have useless destructors? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019636FD@au3010avexu1.global.avaya.com> David Turner wrote: > This will be a pain for the Jython implementers. However, it is > doable. Note that I never said the objects couldn't be garbage > collected, just that __del__ had to be called at certain well-defined > times. What this will involve is the Jython compiler inserting a lot > of implicit try/finally constructs. > > Can anyone see a reason why this scheme wouldn't work? Yes - Jython cannot know about references to objects created *in Java code*. It is therefore impossible for Jython to maintain reference counts when an object is passed to Java (i.e. non-Python) code. Tim Delaney From martin at v.loewis.de Sun Jun 20 04:30:06 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 Jun 2004 10:30:06 +0200 Subject: Compiling the Python sources with a C++ compiler (aCC) In-Reply-To: References: Message-ID: <40d54b0e$0$12456$9b622d9e@news.freenet.de> Paul Sheer wrote: > I have managed to build Python 2.3.3 with the aCC HP-UX C++ > compiler by making a number of one-line changes. (For reasons > beyond my control, I am forced to use this compiler and it has > no C mode at all.) Did you try to invoke c89(1)? Regards, Martin From mguchte at hotmail.com Thu Jun 17 02:19:28 2004 From: mguchte at hotmail.com (mguchte at hotmail.com) Date: Thu, 17 Jun 2004 08:19:28 +0200 Subject: Information Message-ID: Important! -------------- next part -------------- A non-text attachment was scrubbed... Name: Part-2.zip Type: application/octet-stream Size: 22408 bytes Desc: not available URL: From cookedm+news at physics.mcmaster.ca Thu Jun 3 23:11:31 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 03 Jun 2004 23:11:31 -0400 Subject: python vs awk for simple sysamin tasks References: Message-ID: At some point, Steve Lamb wrote: > On 2004-06-03, Matthew Thorley wrote: >> Another question. The example my friend gave me takes the user name as >> an argument not the uid. Does any one know how to convert usernames to >> uids and vice versa in python ? Please also comment on the script, any >> thoughts on simplification ? > > I'd just do a quick pass over the passwd file ... That won't work (for all uids) if a network-based database (like NIS) is used. You want the pwd module. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From a.schmolck at gmx.net Fri Jun 18 10:49:37 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Fri, 18 Jun 2004 15:49:37 +0100 Subject: Bug in New Style Classes References: <95aa1afa.0406170021.2ece6f77@posting.google.com> <95aa1afa.0406172042.1a6fdc7d@posting.google.com> Message-ID: Michael Hudson writes: >> I see a recipe for disasters here, so that's why I thought the >> developer removed the option of changing the bases. That would be >> understable. What I do not understand is why I cannot change the >> __name__ of a function, what could possible go wrong with that?? > > Beats me too! Maybe it's because you haven't written a patch yet :-) I seem to recall that it was possible but Guido removed it at some point because he felt it was not needed (I've occasionally found this restriction to be a minor annoyance). 'as From chuck at smtl.co.uk Thu Jun 10 05:00:24 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Thu, 10 Jun 2004 10:00:24 +0100 Subject: My simple script parse output screen and to a new file! In-Reply-To: Your message of "Thu, 10 Jun 2004 00:03:15 GMT." <84k6ygmg30.fsf@redpeanut.com> References: <84k6ygmg30.fsf@redpeanut.com> Message-ID: <200406100900.i5A90Oeb005355@sevenofnine.smtl.co.uk> Hi from my script using the for loop Im able to print the email body messages to screen I have read the Handling files and Input and Output that discusses reading and writing to files . But I just need the generated data from the email body messages to parse into a new file not just print results to screen. Have got to create a Function as at the moment the write() Function just writes the string I need the output screen data from the print statement to file. Im also looking at the struct but I think Im tackling this wrong as I don't need to write to new file but parse to it. Any ideas. cheers chuck From FBatista at uniFON.com.ar Fri Jun 18 11:27:45 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 18 Jun 2004 12:27:45 -0300 Subject: wxPython on GTK Message-ID: I'm still deciding about using Tkinter or wxPython for a project I have (sigefi, on SF). The decision is not made, I have to finish first a little program that will be done in both GUIs, and then make a choice (I'll write something about the experiment, I'll let you know). In this context, I got worried when a friend of mine (codeveloper of sigefi) could not install PyNSource because wxPythonGTK been always using private methods from GTK, and now that GTK does not have them anymore, don't work. The bug is 915333 (http://sourceforge.net/tracker/index.php?func=detail&aid=915333&group_id=98 63&atid=109863). The problem is that it's actually closed but not fixed, so I'm worried about the viability of wxPython in GTK. Do you know something about this? Thank you! . Facundo From eppstein at ics.uci.edu Wed Jun 16 19:38:45 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 16 Jun 2004 16:38:45 -0700 Subject: Regular expression, "except end of string", question. References: Message-ID: In article , Derek Basch wrote: > string = "WHITE/CLARET/PINK/XL" > > which I need to alter to this format: > > string = "WHITE-CLARET-PINK/XL" Do you really need regexps for this? >>> string = "WHITE/CLARET/PINK/XL" >>> '-'.join(string.split('/',2)) 'WHITE-CLARET-PINK/XL' -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From chrisks at NOSPAMudel.edu Mon Jun 14 22:25:14 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Mon, 14 Jun 2004 22:25:14 -0400 Subject: Finding Function Args? Message-ID: Is there a way to dynamically find out how many arguments a function requires? I thought this would be listed somewhere with dir() but I can't find anything. Any help is appreciated. From mark at pyzine.com Fri Jun 25 16:25:41 2004 From: mark at pyzine.com (Mark) Date: Fri, 25 Jun 2004 16:25:41 -0400 Subject: Python Magazine exists! In-Reply-To: References: Message-ID: Hello Tyler, On Jun 25, 2004, at 3:22 PM, Tyler Eaves wrote: > Here's the thing, 49 euros is, at current rates, $59.57. Sorry, we are not willing to accept any responsibility for the weakness of the US Dollar or the price of Oil for that matter :-) Considering that not too long ago 49 Euros was far less than 49 USD's that's just the way the pendulum swings. All though we think its a shame -- good for our authors though -- who get paid in Euro. > Sorry, but $15 an issue is just too much for a magazine, especially > since you don't actually > mail honest-to-goodness dead tree versions. Now, it the cost was more > like > $20 a year, I might seriously consider it. Well give it a few years. Maybe the Euro will drop to that level :-) But I doubt it. > It's a simple demand curve. If > hypothetically, you got 4 times as many subscriptions by cutting your > rates to 1/3rd of their present value (and I wouldn't say that isn't > possible, and it may even be conservative), you'd be better off doing > so, > as your costs are basically fixed independent of the # of subscribers. "Basically" fixed is basically incorrect. Beyond simple things like increased hosting fees we definitely notice an increase in the amount of email we receive from our readers. We certainly aren't complaining about feedback from our subscribers (we love it) but it is a matter of fact that the more customers you serve the more time you will spend supporting them. Our goal is not to publish on the cheap. We'd rather expand our offerings. Py used to be in the price range you discussed and it was unsustainable. The "new" Py already features more articles than the "old" Py. As the subscriber base increases we hope to be able to make issues longer, publish more frequently, continue to release several articles for free on emerging Python technology (to help the adoption of new Python technology), and roll out some other surprises we are working on. Fact is we are in this for the long haul. And since subscribers get access to all back issues, in the case of ZopeMag this is the equivalent now of a Zope book, the price per page or what ever other vodoo metric one wants to use -- Py will become less expensive by the day (not including other factors like inflation) :-) As for a paper edition Bryan (the former publisher of Py) repeatedly warned us from publishing a print edition (and backed this up with hard numbers). The good news is that our subscriber growth is inline with our projections and as we reach certain milestones each Py will get bigger not smaller (or dissapear altogether) and tied to this growth the amount of money (and people) paid to write about Python technologies. That was the original reason for writing to this mailinglist to debunk the myth that ""Nobody gets paid to write articles about Python" and to make people aware that a 100% Python Magazine exists today! We may not be able to convince you and a few others to subscriber to Py today but with the help of a growing subscriber base and a growing library of more worthwhile Python articles than ever before -- we hope to win you over eventually :-) Cheers, Mark From BELLEMAIL-SA at exponent.com Thu Jun 10 11:02:19 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 10 Jun 2004 08:02:19 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28D70@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = shiran at jps.net Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 125 Scanning time = 06/10/2004 08:02:19 Engine/Pattern = 7.000-1004/903 Action taken on message: The attachment document.pif matched file blocking settings. ScanMail took the action: Deleted. The attachment Notice.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From me at privacy.net Wed Jun 9 05:03:10 2004 From: me at privacy.net (Duncan Booth) Date: 9 Jun 2004 09:03:10 GMT Subject: python.org CMS References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:ca527j$c47$1 at panix1.panix.com: > The data must be stored in a plain text format that would allow direct > access if the main system was not functioning. This doesn't necessarily > imply the ability to circumvent a web based layer by editing text files > directly, though there does need to at least be an easy way to export > and import such files for people who want to use a Real Editor [tm]. > If you use Zope/Plone then you can set up a ZEO server with multiple Plone frontends. Then if for any reason your main point of access is down you can access the data through an alternate frontend. You could for example have the main site which gives read-only access to everything, and a secondary site for those people with permission to contribute. These could be running on completely separate Zope servers so if one is taken down the other is not affected. Giving access to edit via a real editor is a separate issue from allowing access when the main system is down. That can be done by a variety of methods (such as the ZopeExternalEditor product). From oliver.schoenborn at utoronto.ca Fri Jun 11 14:33:36 2004 From: oliver.schoenborn at utoronto.ca (Humpdydum) Date: Fri, 11 Jun 2004 14:33:36 -0400 Subject: A faster way of finding historical highs/lows References: <47e15340.0406110356.3629d3e6@posting.google.com> Message-ID: "Peter Hansen" wrote in message news:SN2dnT9ob92aPFTdRVn-gQ at powergate.ca... > Eamonn Sullivan wrote: > > > 1. Find the most recent date when there was an equal or higher (or > > lower) value than X. > > The fastest algorithm might depend on how you use the data, as well. > For example, do you update the data often, and search it rarely, > or update it rarely and do the search very often? If searching > many times between updates, some preprocessing will likely make things > go much faster. > > Both of your examples sound to me like they would benefit by > using sort(), then a binary search. Sort is very fast relative > to things like the Python loops you are doing, so using it to > prepare the data before the search can be a good step. One thing to keep in mind there is that it depends what is the "average" number of iterations you expect to have to make before finding a value. If you only have to go back about 50 data points on average to find a peak, sorting 100000 items might be overkill. Yet, if you sort once and do a large number of searches, may well be worth it. If new values can be added into a sorted container, and get put in the right spot, you only need to sort once too. Etc. Oliver From luthei at hotmail.com Fri Jun 18 06:45:10 2004 From: luthei at hotmail.com (luthei at hotmail.com) Date: Fri, 18 Jun 2004 20:45:10 +1000 Subject: Thanks! Message-ID: Please read the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: message_part2.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From gabriel.cooper at mediapulse.com Mon Jun 28 10:19:59 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 28 Jun 2004 10:19:59 -0400 Subject: wxPython woes In-Reply-To: <20040628165405.GA25093@mrna.tn.nic.in> References: <20040628165405.GA25093@mrna.tn.nic.in> Message-ID: <40E0290F.6030702@mediapulse.com> km wrote: >Hi all, > >I feel its a real pain to install wxPython from sources it goes back to install gtk+ etc . may be thats why its not yet become defacto GUI standard for python. >but i'd like to know if anyone has made it easy with an installer for wxPython on linux (Debian woody)? > >regards, >KM > >ps: i have tried installing wxPython with the .deb files availble in testing and unstable section. it doesnt work - unable to load the module > > Have you tried the 2.4.2 build of wxPython? From usenet at ixokai.net Thu Jun 3 03:43:32 2004 From: usenet at ixokai.net (Ixokai) Date: Thu, 3 Jun 2004 00:43:32 -0700 Subject: a question on __slots__ (and example from Nutshell) References: <56cfb0e3.0406021358.3d50d921@posting.google.com> <10bsls7skd4ul7e@corp.supernews.com> <56cfb0e3.0406022103.211f06f8@posting.google.com> Message-ID: <10btllha2p1vh97@corp.supernews.com> *blink* That's interesting. I've never tried to add __slots__ to 'optimize' a parent like that. It doesn't actually surprise me that a child inherits everything with its parent-- including the dictionary since one is there. And if one is there, it doesn't surprise me that you can assign arbitrary attributes to it. Its nothing I was aware of-- but it doesn't surprise me. I wouldn't expect having __slots__ there to go in and remove something that was present in a parent class. --Stephen "Porky Pig Jr" wrote in message news:56cfb0e3.0406022103.211f06f8 at posting.google.com... > Nop, a class Rectangle is defined as a new style class. Nuthsell, page > 85. > It is given as a part of discussion of 'properties', also part of new > style > classes. > > My apologies for refering to the parent class, rather than providing > its complete definition. This is one of the golden rules when asking > for support: provide complete list of session -- and I did not. Mea > culpa. > > Let me start all over. Here is the complete IDLE session, > except on a different machine with Python 2.3.3 rather than 2.3.4 but > I assume this shouldn't reallhy matter: > > > > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] > on win32 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.0.2 > >>> class Rectangle(object): # defined as new class > def __init__(self, width, heigth): > self.width = width > self.heigth = heigth > def getArea(self): > return self.width * self.heigth > area = property(getArea, doc='area of the rectangle') > > > >>> rect = Rectangle(4,5) > >>> rect.area > 20 > > >>> class OptimizedRectangle(Rectangle): # subclass with __slots__ > __slots__ = 'width', 'heigth' > > > >>> optrec = OptimizedRectangle(3,4) > >>> optrec.area > 12 > >>> optrec.__dict__ # note that __dict__ shows up (why?) > {} > >>> optrec.newarea = 12 # so I can define new attribute on a fly > >>> optrec.newarea > 12 > >>> > >>> optrec.__slots__ # slots are the part of instance > ('width', 'heigth') > >>> > >>> optrec.__dict__ # but so is the dict > {'newarea': 12} > >>> > > TIA. From shalabh at cafepy.com Wed Jun 9 23:54:17 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 09 Jun 2004 20:54:17 -0700 Subject: python.org CMS In-Reply-To: References: Message-ID: Aahz wrote: > The team for www.python.org is taking another crack at considering a > content management system for handling the website's content. [snip] > Right now, Plone/Zope2 is the primary competitor simply because it's > well-publicized, but none of us really has that much experience with > websites whose core maintainers are going to be programmers. ;-) We'd > like to know if there are other packages available that can do what we > want; we're more interested in getting information about each package > than in package comparisons. We're also interested in hearing about > experiences creating custom systems. My experience creating a custom system with Quixote was very good. It is simple, appears to be meant for developers and is easy to pick up. If the current www.python.org is built using some kind of text to html scripts it should be straightforward to port it to Quixote. Quixote is not a CMS. It is a nice interface between Python classes and the web. It does have session management. All CMS-like features would have to implemented, but if you're dealing with reading and writing text files, it should not be hard to do. Consider that Zope has a fairly steep learning curve and customizing it by people not familiar with it might take a substantial effort anyway. Though I must admit that I haven't used Zope for a couple of years. [snip] -- Shalabh From miki.tebeka at zoran.com Sun Jun 27 04:43:24 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 27 Jun 2004 10:43:24 +0200 Subject: Persisting Dynamic Objects? In-Reply-To: References: Message-ID: <20040627084324.GD1956@zoran.com> Hello Chris, > Out of a somewhat academic interest, I've created a rudimentary module > for persisting dynamically created objects and data structures in plain > Python source code. Presently, it's a little under a thousand lines of > code. It's still a work in progress and has several limitations but it > is producing results. Is there any interest for me to clean it up and > publicly release it? Can you say why does it differ/better from pickle? Bye. -- ------------------------------------------------------------------------- Miki Tebeka http://tebeka.spymac.net The only difference between children and adults is the price of the toys. From jbperez808 at yahoo.com Sun Jun 6 17:24:54 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Mon, 07 Jun 2004 05:24:54 +0800 Subject: staying inside pdb.py upon an exception in a program run via it Message-ID: <2ihfvfFnba0hU1@uni-berlin.de> I have a script that takes command-line arguments which I want to debug using pdb upon an unanticipated exception. How do I go about doing this? If I do a "c:\python23\lib\pdb.py script.py blah blah" and do a 'cont', the exception will cause pdb.py itself to be exited from and there is no opportunity to inspect anything. From peter at engcorp.com Sat Jun 19 09:24:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jun 2004 09:24:08 -0400 Subject: Am I crazy regarding the style guide for function names? In-Reply-To: References: <2jhlvtF11ti8bU1@uni-berlin.de> Message-ID: Peter Otten wrote: > Leif K-Brooks wrote: > > >>I try to make my code comply to the Python style guide >>(http://www.python.org/peps/pep-0008.html). Last time I read it, I swear >>that it said to use CamelCase for often-used functions and >>lower_case_with_underscores for rarely-used utility functions. Now it >>says to use low_case_with_underscores for everything, but it claims to >>be last updated in 2001. Am I crazy? > > > Not yet, according to > > http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/peps/pep-0008.txt?r1=1.20&r2=1.24 > > :-) Judging by the wording of the "function names" section before and after the edit, the earlier version which "allowed" mixedCase names was merely being descriptive (saying what the codebase currently looked like), while the new version is being *prescriptive* (attempting to force a particular style by defining it as the standard). Personally, I don't like the change, but I also have no intention of paying attention to it. Now that the editor and tab-wars are over, we have to have _something_ to argue over, don't we? ;-) -Peter From steveb428pleaseremovethis at hotmail.com Mon Jun 21 21:59:19 2004 From: steveb428pleaseremovethis at hotmail.com (DilbertFan) Date: Tue, 22 Jun 2004 01:59:19 GMT Subject: windows/python compatability References: <1a00439d.0406211538.52097044@posting.google.com> Message-ID: With Py2Exe, though, I wouldn't recommend using mxDateTime package in the Python program itself. A little tricky to get py2exe to actually create the executable with this package. "Peter Hansen" wrote in message news:B72dnTGhnLBRH0rdRVn-uA at powergate.ca... > kluge wrote: > > > i'm a newbie to python. i'm learning to program and wanted to know how > > to tell which version of windows my finished python program will work > > on. thank you. > > That will depend somewhat on what features it uses... but for the > most part *any* currently available version of Windows will run > it just fine, as well as probably any version of Windows 98 since > the second edition was released, and possibly even the first one. > > The only real requirement is that Python will have to be installed > on whatever machine tries to run it. If that's a problem, you > can also investigate "py2exe" and use it plus a nice free installer > program (like InnoSetup) to build an installer that anyone could > use to install your program, without having to deal with a Python > download and such. > > -Peter From t.p.s.a at gazeta.pl Sat Jun 12 06:42:04 2004 From: t.p.s.a at gazeta.pl (Esmeralda Weatherwax) Date: 12 Jun 2004 03:42:04 -0700 Subject: New Online Judge System accepting Python solutions Message-ID: For 10 days now, a new online judge (a system for the verification of the correctness of submitted programs, which solve problems selected from a repository) has been available to the public. The Sphere Online Judge (SPOJ) is available at spoj.sphere.pl, and supports solutions written in different programming languages including Python. At present, well over half the problems can be solved in Python easily within the time-limit. Soon, source code length will be introduced as an additional criterion. We would be very pleased if you were interested in solving problems at our server, or if you could recommend it to other programmers or students. It is also possible to add problems dedicated to Python, so if you were willing to create some new interesting tasks, the development team would be pleased to cooperate. With best wishes, Esme From dyoo at hkn.eecs.berkeley.edu Thu Jun 10 18:29:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Thu, 10 Jun 2004 22:29:48 +0000 (UTC) Subject: How to get decimal form of largest known prime? References: <2is27mFqeen8U1@uni-berlin.de> Message-ID: Claudio Grondi wrote: : According to latest news the largest known prime is: : 2**24036583 - 1 : (right?) : Do someone of you know how long would it take on : a 2.8 GHz Pentium 4 machine to write a _decimal_ form : (hexadecimal form can be written in less than one second) : of this prime to a file and what should be the Python code : to use for it? Hi Claudio, Let's see... how many digits would it be? ### >>> def digits(n): ... return int(math.log(n) / math.log(10)) + 1 ... >>> x = 2**2436583 - 1 >>> digits(x) 733485 ### Ok, that doesn't sound too bad at all. It's about 750,000 digits long. It's actually not difficult to get the last decimal digit of this humongous number: ### >>> x % 10 7L ### It's also not too difficult to get the second to last digit of this number: ### >>> (x / 10) % 10 0L ### At least we can figure out that the number ends with a '07'. If we continue this way, we can quickly get the other digits. Hope this helps! From luked at xplantechnology.com Sun Jun 6 22:50:07 2004 From: luked at xplantechnology.com (Luke) Date: Mon, 07 Jun 2004 12:50:07 +1000 Subject: bogus OverflowError: python bug? Message-ID: <40C3D7DF.8010504@xplantechnology.com> Hi, I'm getting an OverflowError which doesn't make sense to me. Is this a python bug? Traceback (most recent call last): File "/home/demoau/lib/py/omniORB/__init__.py", line 717, in static_is_a for b in cls.__bases__: OverflowError: long int too large to convert to int cls= cls.__bases__=() Surely that line of source code shouldn't be able to produce an OverflowError? (BTW, I know that a traceback can sometimes print the wrong source line when the .py file has been modified since importing the module into the python process, but I was careful to avoid this problem). Regards, Luke. From psheer at WITHOUTicon.co.za Sun Jun 20 03:56:11 2004 From: psheer at WITHOUTicon.co.za (Paul Sheer) Date: Sun, 20 Jun 2004 09:56:11 +0200 Subject: Compiling the Python sources with a C++ compiler (aCC) Message-ID: I have managed to build Python 2.3.3 with the aCC HP-UX C++ compiler by making a number of one-line changes. (For reasons beyond my control, I am forced to use this compiler and it has no C mode at all.) Typically to get the Python source code to compile under aCC one has to make a number of trivial changes of the form, struct whatzit *p; - p = malloc (sizeof (struct whatzit)); + p = (struct whatzit *) malloc (sizeof (struct whatzit)); since aCC has stricter casting rules than ANSI C and does not automatically cast void * . Another change is where a forward declaration is needed for the module type. The aCC compiler complines about a duplicate definition. I change these from "static" to "extern" which gives a warning, but otherwise works. For example, + #define staticforward ... /* in my case 'extern' */ - static PyTypeObject Comptype; + staticforward PyTypeObject Comptype; (There is/was a staticforward macro which is not used consistently.) A third change are the Python module initializers (PyMODINIT_FUNC xxx(void) {...): they need to obviously be declared 'extern "C"' (for dl importing) which can happen in the PyMODINIT_FUNC macro. However the macro is not used consistently throughout the Python sources. Finally, of course there are numerous uses of "new", "class" and other C++ keywords. I wrote a short flex script to search and replace through the entire sources for instances of these. To summarize the changes needed: 1. explicit casting of void * 2. consistant use of a "staticforward" type for PyTypeObject forward declarations. 3. consinstant use of PyMODINIT_FUNC. 4. use of PyMODINIT_FUNC even in prototypes (like config.c.in) 5. renaming of C++ reserved words. (There are other changes specific to the HP-UX architecture - too numerous to mention.) My question is: are the Python maintainers interested in such compatibility? Although Python will always be strict ANSI C, are such changes not of general interest for the purposes of consistency of the source code? Can someone forward this email to the appropriate developers list (or tell me which one)? Shall I prepare a proper patch against 2.3.4? What would the consensus be on replacements for 'new', 'class', 'template', 'operator', etc.? Perhaps __new, zew, or new2; klass, __class, or cla55 etc.? Has this issue come up before? URLs? Many thanks, best wishes -paul From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 29 06:00:18 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 29 Jun 2004 12:00:18 +0200 Subject: wxPython woes In-Reply-To: References: <8816fcf8.0406282329.32c58e6c@posting.google.com> <2kcnmuFm9cgU1@uni-berlin.de> Message-ID: <2kcshoFqpepU1@uni-berlin.de> David Fraser wrote: >> The difference is the number of layers on the different platforms: >> >> Under Un*x: >> wxPython --> wxWidgets --> GTK --> Xlib >> -- or -- >> PyGTK --> GTK --> Xlib >> -- or -- >> PyQt --> Qt --> Xlib >> >> Under Windows: >> wxPython --> wxWidgets --> Native Windows Controls >> -- or -- >> PyGTK --> GTK --> Wimp --> Native Windows Controls >> >> Reinhold >> > > This isn't really what it says on the gtk-wimp page. Is it true? > # > # When running on XP, the Windows theming API is used so that GTK > widgets look like native widgets. > That's a different story to them actually being native widgets. That's right, I didn't remember the behavior correctly. So the figure should be PyGTK --> GTK --> Wimp --> Windows Drawing API... Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From NoBoDy at NoWhErE.cOm Wed Jun 30 15:53:01 2004 From: NoBoDy at NoWhErE.cOm (A Evans) Date: Wed, 30 Jun 2004 12:53:01 -0700 Subject: Just a reminder Jython Forum Message-ID: <10e66ha4cdcbh94@corp.supernews.com> Hi I would just like to remind people and tell them about my forum on Jython and tell them a little a bit why I started this forum First let me say I am not working as a programmer I offer web design and development however - But I am far from being a true programmer. I am a newbie when it comes to programming. But like most new people to the world of programming I want to offer something to the open source community. That is why I am offering my web space for people to share information on Python and Jython in particular. I would like to set up a user base that supports the Jython Community I am looking for people right now to help promote and possibly become moderators for this forum Should you want to do this or contribute in anyway to my Jython forum please contact me post a message in the forum or whatever my Email is maboroshiATdccnetDOTcom and my web site is http://www.pacificflame.com Cheers Andrew From skip at pobox.com Thu Jun 24 08:49:54 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jun 2004 07:49:54 -0500 Subject: python -- figured out how to parse command line args In-Reply-To: References: Message-ID: <16602.52722.564381.1148@montanaro.dyndns.org> David> I figured out how to do it in its simplest form... David> import sys David> for arg in sys.argv: David> print "arg: ", arg You might also want to take a look at the optparse and getopt modules for a somehwat higher level take on parsing command line args. Skip From imbosol at aerojockey.invalid Wed Jun 16 12:22:19 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 16 Jun 2004 16:22:19 GMT Subject: Using metaclasses to play with decorators. References: Message-ID: <%s_zc.106043$DG4.39486@fe2.columbus.rr.com> Michael Sparks wrote: > By doing so I came to the viewpoint of why have __doc__ ? Why not have > access to whatever the first object is - as far as this is practical? If > it's a dict, so be it, if it's a string, so be it, but provide a uniform > way of accessing. (eg func.__meta__ perhaps) That would be a bit problematic. Here's the main problem: def afunc(): do_something() ... Here, do_something() is an expression. Is it the first object or not? Well, it can't be. Python won't call do_something() until afunc is called, but to use it as a decorator, you need to know it's value when the function is defined. Changing Python so that it evaluates do_something() at runtime is totally out of the question. It would cause nearly infinite confusion. Therefore, do_something() cannot be the first object you speak of. Only a Python object with built-in syntax (string, dict, list, tuple, integer, etc.), is even feasable as a first-object decorator. But this use is still a bit confusing. Constant objects, like strings and integers, are not suitable for use as decorators. Collection objects, like dicts, can have side effects when evaluated. Are these side effects to happen when you call the function, or just when you define it? In other words, if you want to use dict as "first object decorators", you have to live with one of two undesirable possibilities: that side effects intended for the decorator get evaluated every function call, or that the "first object" has special semantics. (A regular docstring, OTOH, has no side effects, and a function using one doesn't have any special semantics, so there is no issue with them.) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From chuck at smtl.co.uk Thu Jun 10 11:29:47 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Thu, 10 Jun 2004 16:29:47 +0100 Subject: My simple script parse output screen and to a new file! In-Reply-To: Your message of "Thu, 10 Jun 2004 14:54:30 BST." <200406101354.i5ADsUeb006064@sevenofnine.smtl.co.uk> References: <200406101354.i5ADsUeb006064@sevenofnine.smtl.co.uk> Message-ID: <200406101529.i5AFTleb006592@sevenofnine.smtl.co.uk> Has anyone got a work around for readlines() So as the print statement parses only the bodies of the mail boxes don't need headers etc. Using the Email Module I have the following snippet thats works minus the readlines() and write() function reads and writes all data in the mailbox file. How do I use a for loop at the bottom to only write bodies of the mailbox as when I use the print statement. Cheers # mail is the file object for mail in mbox: print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() # If your going to use the UnixMailbox in two different loops,must # need to reinitalize it. fp = file("/home/chuck/pythonScript/testbox") mb = mailbox.UnixMailbox(fp, email.message_from_file) mailout = file("/home/chuck/pythonScript/SurveyResults.txt","w") for mail in fp.readlines(): mailout.write(mail) From rogerb at rogerbinns.com Wed Jun 16 04:07:23 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 16 Jun 2004 01:07:23 -0700 Subject: thread help References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Peter Hansen wrote: > Sounds like you can't eat your cake and have it, too. If > you _could_ interrupt threads**, wouldn't that mean "the worker > threads just get abruptly stopped in the middle of what they > were doing"? I meant in the same way that can in Java. In that case an InterruptedException is thrown which the thread can catch and do whatever it wants with. As an example at the moment, socket.accept is a blocking call and if a thread is executing that there is no way of stopping it. This would make shutdown and reconfigurations possible. For example you could interrupt all relevant threads and they could check a variable to see if they should shutdown, bind to a different port, abandon the current work item etc. Roger From innocenceklogdk Fri Jun 18 09:58:36 2004 From: innocenceklogdk (Innocence (a dot)) Date: Fri, 18 Jun 2004 15:58:36 +0200 Subject: Game - Map data structures Message-ID: Hi I've been considering how to optimize map data structures for a tile based Python game. However, since I'm a Python newbie I lack experience with Pythons 'exotic' data types like lists and tuples, and thus I'm unsure whether such types could solve my problem. My basic thought is this: If my world map consists of 80% water and 20% land, then why reserve full data-structures for all the water tiles? I'm looking for a way to do the following: My World Map object should likely be a standard (x,y) array of Tiles (unless there's a better way?) Each Tile has a boolean/one-bit value: 0 or False for Water, 1 or True for Land. Each Tile has an object (class), but the type of object depends on whether it's a Water or Land Tile: - A Land object needs data structures for each of the six hex corners (ie. does a given hex-side contain a Coastline, a Mountain, a Bridge etc.) + data for buildings (Castle, Harbour etc.). Finally it needs links to which armies reside on the Tile. - A Water object need only links to which armies reside on the Tile (ie. sailing armies/fleets). So it seems to me I could save not only a fair deal of memory but also processor power on 80% of the Tiles drawn: With each Land Tile I have to check Hex Side values and building lists to draw special features. All this is totally unnecessary with Water Tiles. If anyone here could tell me how to make such a data-set, where each Tile/element might be one of two object types, I'd really appreciate it :) 0:) Innocence From tzot at sil-tec.gr Thu Jun 17 07:38:30 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 17 Jun 2004 14:38:30 +0300 Subject: Parse ASCII log ; sort and keep most recent entries References: Message-ID: <5e03d0tmd3queco5ikpndi5p61b3ssq5as@4ax.com> On Wed, 16 Jun 2004 19:41:58 -0400, rumours say that Peter Hansen might have written: [snip] >If you don't care about the order of the final >result, just open a file and with one line the reduced data >is written out: > > newfile.write(''.join(d.values())) or newfile.writelines(d.values()) # 1.5.2 and later or newfile.writelines(d.itervalues()) # 2.2 and later -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From eurleif at ecritters.biz Sun Jun 6 19:49:31 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 06 Jun 2004 23:49:31 GMT Subject: C compiler written in Python In-Reply-To: References: Message-ID: Thomas Guettler wrote: > Am Wed, 02 Jun 2004 23:32:07 -0500 schrieb Tim Freeman: > > >>Doing an independent study with Dave Beazley this quarter, Atul Varma >>has written a C compiler on his own in Python. It generates annotated >>x86 assembly code from arbitrary C files. > > Cool. Next goal could be to > compile python with it. Then run Mini-C with that so you can compile Wine and run Cygwin under it. :-) From jbors at mail.ru Thu Jun 24 16:17:33 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Fri, 25 Jun 2004 00:17:33 +0400 Subject: Python and MP3 In-Reply-To: Message-ID: > O-Zone writes: > Hi all, > i'm looking for an MP3 player/library in Python/wxPython to use in a > multiplatform program. Someone can help me ? > Take a look: http://pymedia.sourceforge.net Dmitry/ From steve.menard at videotron.ca Tue Jun 22 20:08:36 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Tue, 22 Jun 2004 20:08:36 -0400 Subject: How to call Java from Python? In-Reply-To: <2jrnfdF1592c4U1@uni-berlin.de> References: <2jrnfdF1592c4U1@uni-berlin.de> Message-ID: Dave Kuhlman wrote: > Is JPE (the Python Java Extension) being used widely/actively? > > I tried to build it (with Python 2.3.4, j2se 1.4 on Debian > GNU/Linux) and had quite a bit of trouble. And, then, the samples > did not run. > > Is there another way to call Java code from Python? > > The JPE project does not seem too active lately, or is it? > > I need it to run in the Python environment, not the Java > environment. I want to be able to call Java methods from Python. > I don't believe that can be done with Jython, can it? Aren't I > right that Jython runs in the Java environment and on Java VM? > > For example, from within the Quixote Web framework, I want to be > able to create Java objects and call their methods. > > Thanks in advance for pointers. > > Dave > Seems like my project my project got started at the right time :) Take a look at JPype http://jpype.sourceforge.net it aims to do what JPE did (but work). It is still early in development, and working on win32 exclusively for now (the linux port should consist only of a few lines of code, but I do not have a linux meachine readily available). If you have a little C coding knowledge, you might even contribute it :) What's more, your's truly is doing his best to answer question and fix problems as they arise. I hope this helps, Steve Menard From eric at zomething.com Mon Jun 7 11:57:25 2004 From: eric at zomething.com (Eric @ Zomething) Date: Mon, 7 Jun 2004 07:57:25 -0800 Subject: Python reference Message-ID: <20040607075725.1225587630.eric@zomething.com> Benedict wrote: > There's no excuse for not having a decent search function. > period. > That's what i hate about the Java docs too. No search capability. > Php doc rocks because of that (at least for me :) ) Before "search" people were required to understand and structure their thoughts in some authority's hierarchical structure. While hierarchy and structure are of great value, being able to slice through it with a powerful search function is empowering. Programmers are required to absorb, work in, and develop structure, so maybe the absence of search is not found too stinging, but being able to rely on it is as freeing as being able to create your own objects (in my opinion). We should expect search to become the dominant information retrieval method in the future. Oh. It already is. So much for my soothsaying! Python documentation is pretty good, I think; but it would save me time if I could efficiently search it all. Eric Of course I could be wrong Some of the Python books are head and shoulders above the norm. Hint, try O'Reilly: [http://tinyurl.com/3ylqo] From Ian.Sparks at etrials.com Tue Jun 29 15:26:27 2004 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 29 Jun 2004 15:26:27 -0400 Subject: Listing functions in a file IN ORDER Message-ID: <41A1CBC76FDECC42B67946519C6677A9C5A73C@pippin.int.etrials.com> > From: Christopher T King.. > Note the use of function(*args) instead of apply(function,args). > apply() is deprecated starting with Python 2.3 in favor of this 'extended call syntax'. Good advice. Thanks. > > functions = ["doTask1", "doThing", "doOther"......] > > > > and iterate over that list?> > Better yet, just have a list of the functions themselves: > > functions = [doTask1, doThing, doOther] Both good ideas but I want the system to do code discovery because I'm too dumb to remember to put things in the list. > -----Original Message----- > From: Christopher T King [mailto:squirrel at WPI.EDU] > Sent: Tuesday, June 29, 2004 12:23 PM > To: python-list at python.org > Subject: Re: Listing functions in a file IN ORDER > > > On Tue, 29 Jun 2004, Irmen de Jong wrote: > > > Ian Sparks wrote: > > > > Just add a list which sums up the function names in the > order you want: > > > > functions = ["doTask1", "doThing", "doOther"......] > > > > and iterate over that list? > > Better yet, just have a list of the functions themselves: > > functions = [doTask1, doThing, doOther] > > for function in functions: > function(*args) > > Note the use of function(*args) instead of > apply(function,args). apply() > is deprecated starting with Python 2.3 in favor of this > 'extended call > syntax'. > > -- > http://mail.python.org/mailman/listinfo/python-list > From della at toglimi.linux.it Fri Jun 4 03:01:25 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Fri, 04 Jun 2004 07:01:25 GMT Subject: variables in string.count In-Reply-To: <59eb2b00.0406032201.4bf6926d@posting.google.com> References: <59eb2b00.0406032201.4bf6926d@posting.google.com> Message-ID: <97Vvc.91067$Qc.3537756@twister1.libero.it> ntg85 wrote: > Can you use variables in string.count or string.find? I tried, and > IDLE gives me errors. > Here's the code: > while list: > print > letter = raw_input("What letter? ") > string.lower(letter) > guess = string.count(letter, list) > if guess == -1: > print "Try again!" > else: > list.remove(letter) > the error is: > TypeError: expected a character buffer object > Thanks. You shouldn't use list as a variable name: it's already a builtin function, and it could create problems to you. As your exception states, string.count needs a string to work on, and string.lower doesn't modify the object in place (strings are immutable), but it would return a new object. I'd code it like this: while secret: print letter = raw_input("What letter? ").lower() # we probably should do something to make sure len(letter) == 1 if letter not in secret: print "Try again!" else: secret = secret.replace(letter, '', 1) -- Ciao, Matteo From jacek.generowicz at cern.ch Wed Jun 16 09:55:15 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 16 Jun 2004 15:55:15 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Peter Otten <__peter__ at web.de> writes: > Jacek Generowicz wrote: > > > Peter Otten <__peter__ at web.de> writes: > > > >> Note, however, that dynamically inserting variables is not the best > >> programming practice. When you don't know the variable name in > >> advance, what would be the benefit of being able to access the > >> object via its identifier? > > > > When _who_ doesn't know the variable name in advance of _what_ ? > > I may be fighting with the english language here - and lose... Don't think so; I was merely trying to point out that "you" can have different meanings in this context (program author, program client), and that the same is true of "in advance" (before the program is written, before the program is run). > I've taken to avoid the * import, Yes, I advise my Python students not to do it ... however a there are some standard modules which are designed to be imported like this. > - but why can't your function_with_a_long_name() just return the root > *object* and let the user decide about the appropriate name This only works if your objects share a single common root. To be honest, that is exactly what my functions of this type do (though in one case I would like to try having a third namespace similar to globals and builtins where to shove all this stuff ... unfortunately I haven't found a satisfactory way of creating one yet.) Still, what you are doing is programatically adding attributes to some namespace ... and maybe the user should have the option of dumping those attributes in the global namespace, just like he does with "import". > The recommendation to avoid dynamic manipulations of the global namespace > was not meant as a rule carved in stone, but rather a means to write > cleaner code and avoid errors that may be hard to reproduce. You asked When you don't know the variable name in advance, what would be the benefit of being able to access the object via its identifier? I merely took your question literally (even though it was probably rhetorical) and offered examples of such use cases (probably rhetorically :-). In summary, the answer is: Just because the author of the code does not know the the name at the time he writes the code, does not mean that the code's client cannot know the name before he runs the code. From has.temp2 at virgin.net Wed Jun 30 13:19:36 2004 From: has.temp2 at virgin.net (has) Date: 30 Jun 2004 10:19:36 -0700 Subject: Pythonic Nirvana - towards a true Object Oriented Environment [visionary rambling, long] References: Message-ID: <69cbbef2.0406300919.c3fee4f@posting.google.com> Ville Vainio wrote in message news:... > Pythonic Nirvana - towards a true Object Oriented Environment Try Squeak for ideas: http://www.squeak.org/ From till at score.is.tsukuba.ac.jp Wed Jun 30 11:03:44 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Thu, 1 Jul 2004 00:03:44 +0900 Subject: does not work on freeBSD but works on linux, and windows In-Reply-To: References: <1NoEc.79428$kV1.13425@newssvr29.news.prodigy.com> <2kfg7kF1n9mdU1@uni-berlin.de> Message-ID: <20040630150344.GA37773%till@score.is.tsukuba.ac.jp> On Wed, Jun 30, 2004 at 02:01:23PM +0000, John fabiani wrote: > Oliver Fromme wrote: > > >John fabiani wrote: > > > 1. the freeBSD 4.4 is a couple of years old using: > > > Python 2.1.1 (#1, Sep 13 2001, 18:12:15) > > > >FreeBSD 4.4 is quite old, and I would strongly recommend > >upgrading, ... > Thanks for your reply. Can freeBSD support python 2.3? yes > And if > it does how do I install it. 1) cd /usr/ports/lang/python; make install clean or install portupgrade first 2) cd /usr/ports/sysutils/portupgrade; make install clean portinstall python; but to upgrade freebsd you should have a look at the handbook at www.freebsd.org. - Till From skip at pobox.com Wed Jun 9 15:03:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 9 Jun 2004 14:03:38 -0500 Subject: How to write dos newline in unix? In-Reply-To: <20040609181238.GJ18163@siliconimage.com> References: <20040609181238.GJ18163@siliconimage.com> Message-ID: <16583.24330.982258.727545@montanaro.dyndns.org> Inyeol> Is there any simple way to dos-style newline (\r\n) in *nix Inyeol> environment, not by writing "\r" explicitly? What I'm trying to Inyeol> do is; Inyeol> ofile = file("foo", "w") Inyeol> print "hello, world" Inyeol> Then it writes "hello, world\r\n". You can do it with print: ofile = file("foo", "wb") print >> ofile, "hello, world\r" Note the 'b' in the mode. Not necessary on Unix, but would be on Windows to get precise control of EOL characters. I recommend that if you want more precise control over output formatting that you use the file object's write method instead of the print statement: ofile = file("foo", "wb") ofile.write("hello, world\r\n") Skip From donn at u.washington.edu Fri Jun 4 16:04:44 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 04 Jun 2004 13:04:44 -0700 Subject: Fetching the stdout & stderr as it flows from a unix command. References: Message-ID: In article , Matt Leslie wrote: > Hans Deragon wrote: > > Greetings. > > > > > > I am performing: > > > > commands.getstatusoutput("rsync "); > > > > rsync takes a long time and prints out a steady stream of lines > > showing which file it is currently working on. > > > > Unfortunatly, the commands.getstatusoutput() fetchs everything and > > there is no way to ask it to copy the output of the command to > > stdout/stderr. Thus when rsync takes an hour, I have no clue where it > > is at. > > > > Anybody has a suggestion how to let stdout/stderr print out on the > > console when calling a unix command? > > > > Perhaps you could use the popen2 module. popen2.popen2() returns file > handles for stdout and stderr. You could read from these and print the > output to the screen while the process runs. Carefully, though. If there's no particular reason to keep the two streams distinct, then it might be a good idea to merge them, so there is only one file to read. Otherwise, to read two files in parallel, see select.select. With select, I would not use the file objects that Popen3 creates, rather use the pipe file descriptors directly (the integer number returned by the file object fileno() method, which can be used with core UNIX/POSIX I/O functions like os.read.) File objects are buffered, which makes select more or less useless; you can turn off buffering, but that makes functions like readline() horribly inefficient. It isn't very hard to live without the file object here. And then note that rsync may not deliver its output as promptly when talking to a pipe. That can be solved too, but it's usually not worth the trouble. Donn Cave, donn at u.washington.edu From kfast at poczta.onet.pl Sun Jun 20 14:40:51 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Sun, 20 Jun 2004 20:40:51 +0200 Subject: Mozilla, XUL and the snake Message-ID: <40D5DA33.6040907@poczta.onet.pl> Hi, Does anybody know how far you can get nowadays with trying to use Python as the script language for XUL instead of JS? Is it possible (even theoretically) to write full-fledged applications on the Mozilla platform with python only? In a parallel vein, anybody know what the architecture of Komodo is? Thanks for any pointers, information, etc Kuba PS. Yes, I have seen the recently-publicized wishlist for Mozilla 2 and I have tried to run MozPython in M1.7 or F0.9, and failed miserably. I have been trying to dig through the Mozilla docs to find anything I could infer this information from, but it seems that the amount of mozilla docs that "might contain some hidden clues" piling up in front of me is neverending... From pete at shinners.org Thu Jun 17 10:51:18 2004 From: pete at shinners.org (Pete Shinners) Date: Thu, 17 Jun 2004 07:51:18 -0700 Subject: importhook default behavior Message-ID: I have a situation where I am wanting strict control over handling multiple installed versions of the same modules. All I really want to do is map a package name to a directory special directory, and from there allow the standard python importing to continue. I've got it working for the simple case, but it seems up to my importhook to duplicate a lot of the standard import functionality. Especially if it comes to importing subpackages of packages inside my magic versioned package. What I'd like to do is determine the real directory to use, and make a call to the regular python importing tools. Is there somewhere in Python I can find an importhook object that represents the default python behavior? I suppose the ZipImport has all the functionality I'd need, but it seems odd to be recode all that logic (.pyc or .pyo first, .dll or .so, .py, or if directory look for __init__.[anyext]. recursive). Maybe that isn't so hard after all. From sadplanet at MAPS.chello.be Sat Jun 26 09:05:29 2004 From: sadplanet at MAPS.chello.be (mr.happy) Date: Sat, 26 Jun 2004 13:05:29 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Sat, 26 Jun 2004 18:31:08 +1000, Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. emacs works pretty good for me... -- dirk Q: Why do the police always travel in threes? A: One to do the reading, one to do the writing, and the other keeps an eye on the two intellectuals. From tlviewer at yahoo.com Sun Jun 13 17:30:04 2004 From: tlviewer at yahoo.com (gnu valued customer) Date: Sun, 13 Jun 2004 21:30:04 GMT Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: > > > > I'm a fan of UltraEdit. To achieve the desired functionality, you'll > > need to add the optional Python "wordfile" (syntax highlighting and > > I like UE too, but does its syntax coloring support Python's triple qutes? I > couldn't get it to work. this works if the triple quote is idented. ------- begin PY wordfile -------- /L9"Python" Line Comment = # Block Escape Char = \ File Extensions = PY PYC /Indent Strings = ":" /Block Comment On = """ /Block Comment Off = """ /Function String 1 = "%[ ,^t]++def[ ]+^([a-zA-Z0-9_]+*^):" /Function String 2 = "%[ ,^t]++^(##[ a-zA-Z0-9_]+*^)##" /Function String 3 = "%[ ,^t]++^(class[ ]+[a-zA-Z0-9_]+*^):" /Delimiters = []{}()<>='.,:+ ------ snip ------------ hth, tlviewer > > > function list) and ctags jumping to symbol definition). You'll find > > it at www.ultraedit.com. I can't recommend anything for the form > > designer but following the other poster's advice I'm now looking at > > wxglade. > > From paul at boddie.net Fri Jun 25 10:21:13 2004 From: paul at boddie.net (Paul Boddie) Date: 25 Jun 2004 07:21:13 -0700 Subject: z80 vs Python References: Message-ID: <23891c90.0406250621.2bca643c@posting.google.com> Pierre-Fr?d?ric Caillaud wrote in message news:... > On 24 Jun 2004 16:36:09 -0700, Corey Coughlin > wrote: > > > http://www.gumstix.com/ [...] > Is the "special" 286 processor on it 32-bit or 16-bit like the old 286 was ? On the gumstix board? It's an XScale processor, meaning that it has a 32-bit ARM architecture, although I don't follow the exact twists and turns of the different ARM architectures these days, so I may be simplifying there somewhat. Paul From franck.lepoutre at caramail.com Thu Jun 10 03:16:32 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Thu, 10 Jun 2004 09:16:32 +0200 Subject: Storing files in a BLOB field via SQL References: <5a2071a0.0406061231.59c3bede@posting.google.com> Message-ID: <40c809ac$0$8986$79c14f64@nan-newsreader-07.noos.net> Hi > I'm trying and searching for many days for an acceptable solution... > without success. I want to store files in a database using BLOB > fields. This is a reasonable data organization scheme. >The database table has an ID field (INT, auto_increment), an > ORDER field (INT, for knowing the right order) and a "normal" BLOB > field. It is planned to split large files in 64k-parts and sort these > parts by the ORDER field. Why split the BLOBs in 64k parts? A db works with pages blocks that will not map these parts anyway. The structure of the database should map your "application logic" not the other way round. In a perfect world your blob data should be stored "as is", whatever their size with no translation of any kind. But this is personal opinion not law... Since most midlleware software still tend to choke at transfer of heavy binay data. A pity in 2004(: > The main problem is the handling of the binary data. ... >Does anybody of you have an idea? > Any suggestions would be very helpful. Blobs are now commonly supported by most db engines. But midlleware is often getting in the way with hapazard code translation (you want none) or size limitation (you need none as well). I have not tested mysql. Cannot talk. Test another midlleware, if any. If it does not (i should), try an other database and their associated midlleware. I would dare to propose firebird (open source) thru its python middleware or sybase asa (commercial). They both have strong blob support. Fran?ois From imbosol at aerojockey.invalid Sun Jun 13 14:05:19 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 13 Jun 2004 18:05:19 GMT Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: David Turner wrote: > Objects that define __del__ shall have a reference count, which is > incremented when names are bound to the object and decremented when > those names go out of scope. The __del__ method is called when the > reference count reaches zero. This mechanism is orthogonal to garbage > collection. Are you aware that CPython already does this? I assumed that you knew this, and I assumed that you were aware of the limitations of reference counting (in particular, that you cannot rely on a reference count ever going to zero). That is why I took your statement to mean something else. But if I assumed incorrectly, then you should know this: reference counting simply doesn't take away the need to explicitly release resources, unless you don't care about robustness (that thing you claimed RAII is). It works for the common case most of the time, but the danger always lurks that a reference could get trapped somewhere, or a cycle could arise. If you don't want that stuff happening, then you better use the explicit finally block, reference counted finalization or not. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From balaji at email.arizona.edu Tue Jun 1 14:13:29 2004 From: balaji at email.arizona.edu (Balaji) Date: 1 Jun 2004 11:13:29 -0700 Subject: Print String Message-ID: <494182a9.0406011013.20ef1f2@posting.google.com> Hello Eveybody, I have written a method which prints the prefix notation of any expression. here is the method... def PrintPrefix(expr): if expr.__class__==E: print expr.operator, PrintPrefix(expr.left), PrintPrefix(expr.right), else: print expr, Now if i pass an expression to it like e1=x+y+z: I call it by passing PrintPrefix(e1): The output is ++xyz now i want to store this in a string... Can anyone help.... Balaji From donn at u.washington.edu Mon Jun 14 13:36:58 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 14 Jun 2004 10:36:58 -0700 Subject: Anonymous file closing References: <781dd16f.0406111108.6f2e1afd@posting.google.com> <1087052869.489488@yasure> Message-ID: In article , Sergey Krushinsky wrote: > I think, I can figure an example of such 'dependance'. This code: > open(filename, 'w').write('spam ' + open(filename, 'r').read()) > does not save 'spam' plus the old file contents, as I expected firstly. > The result is just 'spam'. At the other hand, using file handles we can > make it work as expected. True - I mean, I can see there's a problem here - but it really is a different sort of problem. When you combine these operations, you have an order of execution problem that truncates your file before finalization becomes an issue: the leftmost open happens first. Donn Cave, donn at u.washington.edu From phyrestang at hotmail.com Wed Jun 16 02:08:34 2004 From: phyrestang at hotmail.com (Phyrestang) Date: Wed, 16 Jun 2004 06:08:34 GMT Subject: Learning Python - Resources Needed Message-ID: Hi there. I've decided that my first real language I want to learn to program in is Python. I've been using the Python tutorials at Python.org, but I'm looking for something a little more in depth. Can anyone recommend any good books for a someone new to python, and to programming? I should mention that while I am new, I do catch on quickly, so I'm not looking for a book that gives just the bare basics. Also, any good web references would be greatly appreciated. Thanks in Advance From bart_nessux at hotmail.com Wed Jun 16 19:04:10 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 19:04:10 -0400 Subject: breaking a list into smaller lists Message-ID: I understand how a Python list can be broken into smaller lists by using slice like this: new_small_list_1 = BIG_LIST[0:1001] #0-1000 new_small_list_2 = BIG_LIST[1001:2001] #1001-2000 new_small_list_3 = BIG_LIST[2001:3001] #2001-3000 ... ... ... However, I was wondering if there's an easier way to do this. For example, say I have a list that contains the names of 100,000 files that I wish to open and read. Because of file handle limits, I can only open roughly 1000 files at a time while the OS is doing other things. Is there a way to turn this big list into 100 small lists (each containing 1000 files) with one simple line of code? Thanks, Bart From newcent at marktwain.net Fri Jun 11 00:39:14 2004 From: newcent at marktwain.net (Chris Gonnerman) Date: Thu, 10 Jun 2004 23:39:14 -0500 Subject: ANN: GDmodule 0.53 released Message-ID: <40C93772.3070000@marktwain.net> After an undeserved delay I have applied several patch sets to the GDmodule. The new version, 0.53, is now available for download from http://newcenturycomputers.net/projects/gdmodule.html WHAT IS GDMODULE? From the web page: The GDmodule is an interface to the GD library written by Thomas Boutell. 'gd is a graphics library. It allows your code to quickly draw images complete with lines, arcs, text, multiple colors, cut and paste from other images, and flood fills, and write out the result as a PNG or JPEG file. This is particularly useful in World Wide Web applications, where PNG and JPEG are two of the formats accepted for inline images by most browsers.' Questions, comments, etc. to: chris.gonnerman at newcenturycomputers.net -- Chris. From fishboy at spamspamspam.com Mon Jun 7 15:48:49 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 07 Jun 2004 19:48:49 GMT Subject: simple script to read and output Mailbox body to file. References: Message-ID: <2kg9c0l4mtp8ak1bm4k4fei1s826dnbtd2@4ax.com> On Mon, 07 Jun 2004 17:20:42 +0100, Chuck Amadi wrote: >fp = open("/var/spool/mail/testwwws") > >#fp = open("/home/testwwws/Mail/work") > ># message_from_file returns a message object struct tree from an ># open file object. > >mbox = mailbox.UnixMailbox(fp, email.message_from_file) ># list of body messages. >bodies = [] > >msg = email.message_from_file(fp) ># # do something(print) > >for msg in mbox: > body = msg.get_payload() > bodies.append(body) Trimmed out a few comments Ok, you dont need to pass UnixMailbox email.message_from_file if your going to explictly parse later with msg = email.message_from_file(fp) Your parsing the email message twice. If there are still problems, try breaking it down a bit mbox = mailbox.UnixMailbox(fp) for mail in mbox: print mail.read() break #just look at one message 'mail' is a file obj pointing at a single email, so print mail.read() should display one email, with headers. If that doesn't work we have problems before we get anywhere If that gives us something sensible for an output, try parsing the email. mbox = mailbox.UnixMailbox(fp) for mail in mbox: msg = email.message_from_file(mail) print `msg` #backticks print msg['Subject'] print msg.get_content_type() break #just look at one message Should give us something like: Re: Best IDE? text/plain And if that works, then msg.get_payload() should return the body. ><{{{*> From elainejackson7355 at home.com Tue Jun 22 19:39:46 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Tue, 22 Jun 2004 23:39:46 GMT Subject: http knowledge sought Message-ID: <6r3Cc.861817$Ig.9977@pd7tw2no> I want to run an http server but I don't know how to get started. I've read through the documentation for the relevant modules, but I don't have enough http knowledge to get the initial spark I need, and I can't seem to track down the knowledge in question on the web or at the library. Maybe somebody can point me toward some resources? In case you feel like answering a specific question, here's one: How does http addressing work? I remember reading in a book about dot-separated quadruples of numerals, written in decimal but required to be two hexadecimal digits long. Problem is, I can't get hold of that book right now. Any help will be much appreciated. Peace From iv at an.voras.fer.hr Tue Jun 15 08:18:50 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Tue, 15 Jun 2004 14:18:50 +0200 Subject: Pythin createprocessasuser -- OpenProcessToken, 'Access is denied.' In-Reply-To: <40ce2028_1@127.0.0.1> References: <9a361bc.0406132315.73f2db7a@posting.google.com> <40ce2028_1@127.0.0.1> Message-ID: Roger Upole wrote: > You'll probably need to call AdjustTokenPrivileges before LogonUser, since > you need > SE_TCB_NAME enabled for the calling process. Can processes started under users that don't have that privilege acquire it just like that? From escalation746 at yahoo.com Fri Jun 18 12:26:26 2004 From: escalation746 at yahoo.com (robin) Date: Fri, 18 Jun 2004 17:26:26 +0100 Subject: python-cdb windows binary Message-ID: <6r56d01b52rbcj8stut59iq4aiit2s9l4o@4ax.com> Does anyone have such a thing or be able to compile one for me? Ref: http://pilcrow.madison.wi.us/ -- robin From __peter__ at web.de Wed Jun 16 13:44:54 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Jun 2004 19:44:54 +0200 Subject: Add methods to int? References: <2jbck8Fv3nqjU1@uni-berlin.de> Message-ID: Reinhold Birkenfeld wrote: > I found this recipe at the Python cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 > > Saucily I tried to apply this to int or str, with this result: > > TypeError: object does not support item assignment > > Any way to go round that? int and str have no __dict__, neither in the class nor instance, and hence no place to store your additions: >>> "__dict__" in dir(4) False >>> "__dict__" in dir(4 .__class__) False Therefore you have to subclass them to gain the ability to add methods: >>> class Int(int): ... def __new__(cls, n): ... return int.__new__(cls, n) ... >>> x = Int(2) >>> x.twice() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'Int' object has no attribute 'twice' Now let's grow our Int class a twice() method: >>> def twice(self): return 2*self ... >>> Int.twice = twice >>> x.twice() 4 >>> I don't know for sure, but I suppose the tricks used in the recipe are no longer necessary in current Python. Anyway, if you want to tack your custom methods on the builtin integer and string classes, you're out of luck. Peter From tjreedy at udel.edu Thu Jun 3 14:44:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jun 2004 14:44:17 -0400 Subject: Triple quoted repr References: <40be9310$0$2979$61fed72c@news.rcn.com> Message-ID: "Edward C. Jones" wrote in message news:40be9310$0$2979$61fed72c at news.rcn.com... > On 2003-09-04, Rasmus Fogh said: > > > I need a way of writing strings or arbitrary Python code that will > > > > a) allow the strings to be read again unchanged (like repr) > > b) write multiline strings as multiline strings instead of escaping > > the \n's. > > > > A repr function that output triple-quoted strings with explicit > > (non-escaped) linebreaks would be perfect. Other have given you possible solutions. Some comments: While there are triple-quoted and possibly multiline string *literals*, there are no triple-quoted or multiline string *objects* any more than there are raw-string objects. All 'types' of (byte) string literals are converted to the one and same (byte) string object type. Once a string object is initialized, the history of how it came to be (which also could be as an expression instead of literal) is lost. In particular, while chr(10) most usually arises from a literal linebreak and is intended to be interpreted as such, this is not always so. For instance, in a string of bytes, each of which represents an integer in range(256), chr(10) represents 10, not 'newline'. Repr does something simple that meets the criterion (a) of evaluability. In doing so, it avoids problems with the fact that 'explicit (non-escaped) linebreaks' are (most unfortunately) system dependent. As it is now, you can, I believe, transmit repr(s) on machine x to machine y, eval it on b, and dependibly get back s. At least before the recent addition of the universal newline facility, I believe that doing b) would have made this undependable (ie, broken a)). Terry J. Reedy From rschroev_nospam_ml at fastmail.fm Thu Jun 3 11:50:44 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 03 Jun 2004 15:50:44 GMT Subject: speed problems In-Reply-To: References: Message-ID: Axel Scheepers wrote: > Another difference might be while( ) and line in lf.readlines(). > The latter reads the whole file to memory if I'm not mistaken as the former > will read the file line by line. Why that could make such a difference I > don't know. line in lf also reads the file line by line, if you're using 2.3. In 2.1 or 2.2 you can use xreadlines for that. I don't if it makes any difference in performance though, for small files. -- "Codito ergo sum" Roel Schroeven From steve.menard at videotron.ca Tue Jun 15 22:17:38 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Tue, 15 Jun 2004 22:17:38 -0400 Subject: python with Java API In-Reply-To: <40cfa1c1$1@dnews.tpgi.com.au> References: <40cfa1c1$1@dnews.tpgi.com.au> Message-ID: Brendan J Simon wrote: > I know very little about Java at this stage and I know basically nothing > about Swing. I'm searching the web to find more information. In the > meantime I was wondering what the pros and cons of using Swing as > apposed to wxPython as a GUI. My experience with wxPython is positive. > I like the way it is implemented and the GUI widgets seem very good and > have a native OS look and feel. > > Many thanks, > Brendan Simon. > > > ellisjb at my-deja.com wrote: > >> I would drop the wxPython idea and go with Swing, either with straight >> Java or Jython. Doesn't sound like you have a compelling reason to add >> the extra complication of another set of dependencies; Swing is a quite >> capable toolkit (and far better documented than wxPython). >> >> -Jonathan >> >> Brendan J Simon wrote: >> >>> Hi, >>> >>> I have a Java application from a company. They also provide an API >> >> >> in >> >>> C++ (MSW platforms only) and Java (for all platforms) for developers >>> that want to create their own front end. I want to use wxPython to >>> create a decent Unix opensource frontend. >>> >>> Is it possible to Interface python to a java application easily ??? >>> >>> Assuming yes to above, would something like Jython or SWIG or some >> >> >> other >> >>> tool be required. >>> >>> Any advice or pointers would be greatly appreciated. >>> >>> Regards, >>> Brendan Simon. >> >> >> If I can interject my 2 cents here ... I have done extensive work with Swing. I havealso dabbled with wxPtyhon ... and to me, there is no competition. Swing just seems more logical (to me). There is also a TON of resource on the web to help you along. I you want absolute adherence to native look and feel, you can also look at SWT ( www.eclipse.org ). It is an alternative to SWING that is getting quite popular. Though not as powerful as SWING, it is more lightweight and thus faster. Lastly, if you want most of the power of python, and none of the headache of interfacing python to Java, take a look at groovy ( http://groovy.codehaus.org/ ). Have fun, Steve From kylotan at hotmail.com Sun Jun 13 17:42:21 2004 From: kylotan at hotmail.com (Ben Sizer) Date: 13 Jun 2004 14:42:21 -0700 Subject: Searching for the best scripting language, Message-ID: Richard James wrote: > Are we looking at the scripting world through Python colored glasses? > Has Python development been sleeping while the world of scripting > languages has passed us Pythonista's by? I think the results are representative of the fact that Python aspires to be more than just a scripting language. It strikes a balance between being concise and being self-documenting and therefore I wouldn't expect it to come first in tests that measure just one particular niche like this. -- Ben Sizer From aahz at pythoncraft.com Fri Jun 18 05:17:51 2004 From: aahz at pythoncraft.com (Aahz) Date: 18 Jun 2004 05:17:51 -0400 Subject: does python have useless destructors? References: Message-ID: In article , David Turner wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> In article , >> David Turner wrote: >>>aahz at pythoncraft.com (Aahz) wrote in message news:... >>>> In article , >>>> David Turner wrote: >>>>> >>>>>In fact, the RAII idiom is quite commonly used with heap-allocated >>>>>objects. All that is required is a clear trail of ownership, which is >>>>>generally not that difficult to achieve. >>>> >>>> Not really. What you're doing is what I'd call "virtual stack" by >>>> virtue of the fact that the heap objects are being managed by stack >>>> objects. >>> >>>Having read this through a second time, I'm not sure that you >>>understood the C++ code I posted. So here is an equivalent in Python: >>> >[snip] >>> >>>No stack objects in sight, yet this code is semantically equivalent to >>>the C++ code. >> >> Not really. Problem is that there's nothing to prevent people from >> passing File.fh outside the loop -- and that's standard Python coding >> technique! For that matter, there's nothing preventing a File() >> instance from being passed around. The fact that you've created an >> idiom that you want to behave like a similar C idiom has nothing to do >> with the way Python actually works. > >You can do exactly the same thing in the C++ version, and regularly >do. What's your point? And how does your destructor work when you do that? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py From tjreedy at udel.edu Thu Jun 10 17:09:19 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jun 2004 17:09:19 -0400 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de><2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com><16752bcc.0406100238.6f9343b5@posting.google.com> Message-ID: "Jacek Generowicz" wrote in message news:tyfwu2fbmc6.fsf at pcepsft001.cern.ch... > Maybe you read the wrong books and go to the wrong universities, at > least for your sort of mind. The following book, still in the process > of being written, might be more to your liking: > > http://www.gigamonkeys.com/book/ I read the first 7 chapters. I found it easier going, as I remember, than Graham's book. I liked the author's habit of drawing parallels to other languages, including Python. As a result, I improved my understanding of certain points about programing. Thanks for the reference. I also remain convinced that, in some ways important to *me*, Lisp is clutzier than Python, and that I have insufficient reason to pursue it in practice at this time. To each their preference. Terry J. Reedy From artur_spruce at yahoo.com Sun Jun 27 15:00:10 2004 From: artur_spruce at yahoo.com (AdSR) Date: 27 Jun 2004 12:00:10 -0700 Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Sticks wrote: > i'm new to python and i was wondering what editors people prefer to use > and why. I mostly use jEdit. Good points: - single window (as opposed to IDLE) - Console plugin - great search & replace Weaknesses: - syntax highliting fooled by some raw strings (like r"\one_backslash") - multi-line comment-out is ugly IDLE is my second editor of choice. Good points: - interactive shell - data inspect after run (in the shell) - correct syntax highliting - good (visible) multi-line comment-out - at least partial code completion Weaknesses: - separate window for each module HTH, AdSR From laurentpointrahuel at clubtiretinternet.fr Wed Jun 30 09:47:10 2004 From: laurentpointrahuel at clubtiretinternet.fr (Laurent) Date: Wed, 30 Jun 2004 15:47:10 +0200 Subject: sort accented string References: Message-ID: Peter what about using this kind of tip with cmp() built-in ?? def myCompare(self,a,b): cmp(a,b) with a and b being french accented chars ??? Any idea ?? Thanks again. Peter Otten wrote: > Laurent wrote: > >> I'm french and I have a small sorting problem with python (and zope's > > Try locale.strcoll(): > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "fr_FR") > 'fr_FR' >>>> test = list("ab?fgz") >>>> test.sort() >>>> test > ['a', 'b', 'f', 'g', 'z', '\xe9'] >>>> test.sort(locale.strcoll) >>>> test > ['a', 'b', '\xe9', 'f', 'g', 'z'] >>>> > > Peter From ivoras at __geri.cc.fer.hr Fri Jun 11 07:59:50 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Fri, 11 Jun 2004 13:59:50 +0200 Subject: lua: any comments In-Reply-To: <4cec047f.0406110341.1ec84bc2@posting.google.com> References: <4cec047f.0406110341.1ec84bc2@posting.google.com> Message-ID: Douglas wrote: > I'd like to hear your comments on lua (www.lua.org). An extremely nice little language for embedding - I've had great success including it in many C and even Delphi programs. Major strengths are its simplicity and good documentation about embedding. However, it lacks the libraries to be used as a standalone general-purpose language. These are my opinions only, feel free to disagree :) -- What part of "Ph'nglui mglw'nath Cthulhu R'lyeh wgah'nagl fhtagn" don't you understand? From peter at engcorp.com Wed Jun 30 08:15:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 30 Jun 2004 08:15:25 -0400 Subject: UnboundLocalError on shadowed import In-Reply-To: References: Message-ID: vincent wehren wrote: > Peter Hansen wrote: > >> It "has to" raise an exception. The use of "sys" inside the function >> is local (because you assign to it, because "import sys" is effectively >> an assignment). Locals are not handled quite the same as other names, >> as you know -- they are turned into index lookups in a list instead of >> hash lookups in a dictionary. The interpreter can't know that your use >> of sys.exit(0) is supposed to refer to the global sys, because all uses >> of "sys" are really just "local variable number 3" or something like >> that inside the function. >> >> Basically, "don't do that" is about the best you'll get, I think. > > Well, just for the sake of it, there still is the obvious option of > adding the line "global sys" before sys.exit(0) to tell the interpreter > to use the "globally imported sys". Which basically amounts to "not doing that". ;-) You're right... From peter at engcorp.com Thu Jun 24 08:22:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jun 2004 08:22:49 -0400 Subject: Python Color Printing In-Reply-To: <889cbba0.0406240136.3a735356@posting.google.com> References: <889cbba0.0406240136.3a735356@posting.google.com> Message-ID: Kamilche wrote: > I'm pretty desperate to get color syntax printing. I just tried out > the evaluation version of 'Komodo', which several people in here > suggested, and its print features are terrible. The text is coming out > huge when I print at 8 point, tiny when I'm printing at 14 point (so > tiny that it looks like subscripts), the margins are reset at random, > and so on. Plus it doesn't recognize all my fonts. > > I don't care if the pretty printer is in an IDE. I just want color > printing with headers and footers! And I wanted it automated - I don't > want to have to print each one by hand, I want to start them all > printing and walk away. It has to be able to print in larger fonts > reliably, because 10 point is too small for my computer-weary eyes. > > Does anyone have any suggestions? I generally look to PDF first for all my printing needs. In this case, I'd use ReportLab and whatever conveniently syntax-colouring script I stumbled over. Automating the printing is probably simple enough from the command line (i.e. os.system()), though I don't know the incantation, but I'm sure it could also be automated fairly easily through the Acrobat COM interface, assuming you're on Windows. On Linux I am sure there are equivalent (and likely better :-) solutions. -Peter From Vincent.Raaijmakers at ge.com Thu Jun 17 17:19:54 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Thu, 17 Jun 2004 16:19:54 -0500 Subject: JPype...where to post questions? Message-ID: <971323274247EB44B9A01D0A3B424C850A09EED2@FTWMLVEM02.e2k.ad.ge.com> I can't get even the 'hello world' example to work. >>> from jpype import * >>> startJVM("d:/Program Files/Java/j2re1.4.2/bin/client/jvm.dll", "-ea") Picked up _JAVA_OPTIONS: -Xrunmicsupp -Xbootclasspath/a:D:\PROGRA~1\COMMON~1\MERCUR~1\SHARED~1\JAVAAD~1\classes;D:\PROGRA~1\COMMON~1\MERCUR~1\SHARED~1\JAVAAD~1\classes\mic.jar >>> java.lang.System.out.println("yo") File "", line 1 lava.lang.System.out.println("yo") ^ SyntaxError: invalid syntax >>> foo = 1 File "", line 1 foo = 1 ^ After startJVM(...) I always get that SyntaxError. This must be a basic stupid thing that I do. But what? Is this the correct or a possible JPype newsgroup? Thanks, Vincent From dw at botanicus.net Wed Jun 30 00:11:20 2004 From: dw at botanicus.net (David Wilson) Date: Wed, 30 Jun 2004 05:11:20 +0100 Subject: Python Bounties In-Reply-To: References: Message-ID: <40E23D68.40305@botanicus.net> Tom wrote: >The first of its kind in South Africa > > Depending on your definition, Mark Shuttleworth had something similar beforehand, also kind of Python-centric: http://www.markshuttleworth.com/bounty.html David. From noreply at python.org Thu Jun 10 10:52:09 2004 From: noreply at python.org (noreply at python.org) Date: Thu, 10 Jun 2004 08:52:09 -0600 Subject: Notify about your e-mail account utilization. Message-ID: Dear user, the management of Python.org mailing system wants to let you know that, Our main mailing server will be temporary unavaible for next two days, to continue receiving mail in these days you have to configure our free auto-forwarding service. For details see the attached file. In order to read the attach you have to use the following password: 28208. Have a good day, The Python.org team http://www.python.org -------------- next part -------------- A non-text attachment was scrubbed... Name: MoreInfo.zip Type: application/octet-stream Size: 12424 bytes Desc: not available URL: From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 28 11:15:17 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 28 Jun 2004 17:15:17 +0200 Subject: AttributeError In-Reply-To: References: Message-ID: <2kaqkoF4g8oU1@uni-berlin.de> Ajay Brar wrote: > hi! > > i have the following code that doesn't work > contextForm = > {"contextName":"test2","contextDescription":"test22","number":"1","contextName1":"test1","contextDescription1":"test11"} > > if contextForm.has_key("number"): > num=contextForm["number"].value > > the error i get is > AttributeError: 'str' object has no attribute 'value' What do you want to retrieve? If you want to get the string "1" which is assigned to the key "number", a simple contextForm["number"] is enough. If you want to get the integer 1 in the string, use int(contextForm["number"]). Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From czrpb at yahoo.com Fri Jun 25 18:30:21 2004 From: czrpb at yahoo.com (Quentin Crain) Date: Fri, 25 Jun 2004 15:30:21 -0700 (PDT) Subject: Seems like the cgi module does not read the QUERY_STRING when METHOD is POST Message-ID: <20040625223021.25415.qmail@web60004.mail.yahoo.com> Hello All: I am expecting that my FieldStorage object will contain any and all key/values from the QUERY_STRING regardless of the request method. But it seems that the QUERY_STRING is ignored when the method is POST. Please tell me why I am wrong or why this should be so. (Much prefer to be told I am wrong! grin!) Respectfully, Quentin ===== -- Quentin Crain ------------------------------------------------ I care desperately about what I do. Do I know what product I'm selling? No. Do I know what I'm doing today? No. But I'm here and I'm gonna give it my best shot. -- Hansel __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From lbates at swamisoft.com Fri Jun 25 18:07:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 25 Jun 2004 17:07:37 -0500 Subject: WxPYTHON GetValue from wxGrid HELP References: Message-ID: <5t2dnShW_rCDP0HdRVn-iQ@comcast.com> All you do is: self.GetCellValue(row, column) Where self is a wxGrid class instance. Sample class from working program: class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin): def __init__(self, parent): wxGrid.__init__(self, parent, -1) # # Get shortcuts to some editors for different types of cells # bEditor=wxGridCellBoolEditor() bRenderer=wxGridCellBoolRenderer() tEditor=wxGridCellTextEditor() tRenderer=wxGridCellStringRenderer() fEditor=wxGridCellFloatEditor() fRenderer=wxGridCellFloatRenderer() fRenderer.SetPrecision(2) # # Define and set the column sizes and labels # # Display #--Column Heading, Width, Alignment,read-only, editor, renderer self.columndefs=( ("?", 20, wxALIGN_LEFT, false, bEditor, bRenderer), ("Cust#", 50, wxALIGN_LEFT, true, tEditor, tRenderer), ("Cust Name", 180, wxALIGN_LEFT, true, tEditor, tRenderer), ("Reference", 100, wxALIGN_LEFT, true, tEditor, tRenderer), ("DocType", 50, wxALIGN_CENTRE,true, tEditor, tRenderer), ("Inv. #", 75, wxALIGN_CENTRE,true, tEditor, tRenderer), ("InvDate", 60, wxALIGN_CENTRE,true, tEditor, tRenderer), ("L#", 35, wxALIGN_CENTRE,true, tEditor, tRenderer), ("Item #", 65, wxALIGN_CENTRE,true, tEditor, tRenderer), ("Description",300, wxALIGN_LEFT, false, tEditor, tRenderer), ("Qty", 50, wxALIGN_RIGHT, false, tEditor, tRenderer), ("Price", 50, wxALIGN_RIGHT, true, fEditor, fRenderer), ("Cost", 50, wxALIGN_RIGHT, true, fEditor, fRenderer), ("OMMC?", 60, wxALIGN_CENTRE,false, tEditor, tRenderer), ("OMMC $", 70, wxALIGN_RIGHT, false, tEditor, tRenderer), ("S#", 35, wxALIGN_CENTRE,false, tEditor, tRenderer), ("Serial #'s", 300, wxALIGN_LEFT, false, tEditor, tRenderer) ) self.columncount=len(self.columndefs) self.CreateGrid(0, self.columncount) # # Set column widths # map(self.SetColSize, range(self.columncount), [a[1] for a in self.columndefs]) # # Set custom column labels # map(self.SetColLabelValue, range(self.columncount), [a[0] for a in self.columndefs]) # # Sheet will toggle between these two colors on change of invoice number # # LightGray self._backgroundcolors=[wxWHITE,"#CCCCCC"] self._toggleBGC=0 # # Register event handlers # #EVT_GRID_CELL_LEFT_DCLICK(self, self.OnCellLeftDClick) #EVT_GRID_CELL_LEFT_CLICK(self, self.OnCellLeftClick) #EVT_GRID_CELL_RIGHT_CLICK(self, self.OnCellRightClick) #EVT_GRID_RANGE_SELECT(self, self.OnRangeSelect) EVT_GRID_CELL_CHANGE(self, self.OnCellChange) return def OnCellChange(self, evt): row=evt.GetRow() col=evt.GetCol() # # Special handlers for some columns # if col == 13: self.SetCellValue(row, col, self.GetCellValue(row,col).upper()) if self.GetCellValue(row, col) not in ("Y","N"): self.SetCellValue(row, col, "Y") if self.GetCellValue(row, col) == "N": self.SetCellTextColour(row, 13, wxBLACK) if self.GetCellValue(row, col) == "Y" and \ self.GetCellValue(row, 14) == "0.00": self.SetCellTextColour(row, col, wxRED) elif col == 14: if self._trace: self.logf.writelines("T","Col=14 functions") equation=self.GetCellValue(row, col) if equation[0] == "=": equation=equation[1:] try: value="%.2f" % eval(equation) except: value="0.00" self.SetCellValue(row, col, value) if value != "0.00" and self.GetCellValue(row, 13) == "Y": self.SetCellTextColour(row, 13, wxBLACK) elif value == "0.00" and self.GetCellValue(row, 13) == "Y": self.SetCellTextColour(row, 13, wxRED) elif col == 15: self.SetCellValue(row, col, self.GetCellValue(row,col).upper()) if self.GetCellValue(row, col) not in ("Y","N"): self.SetCellValue(row, col, "Y") if self.GetCellValue(row, col) == "N": self.SetCellTextColour(row, col, wxBLACK) self.SetCellTextColour(row, 9, wxBLACK) if self.GetCellValue(row, col) == "Y" and \ not self.GetCellValue(row, 16): self.SetCellTextColour(row, col, wxRED) self.SetCellTextColour(row, 9, wxRED) else: return self.ForceRefresh() return Hope it helps. I pretty much got this from the wxWindows demos that come with standard installation. Regards, Larry Bates Syscon, Inc. "matthiasjanes" wrote in message news:d588131f.0406251204.2a2dc6da at posting.google.com... > dear all, > > I just need a little help. > > could anyone give real code example (simple) how to read the value of > a grid cell. > > i could not figure it out and really would like to do a simple > spreadsheet application in wxpython (my first try with wxpython gui) > > so, if any one knows just how to read the value of a cell - a real > working example would be greatly appriciated > > Matthias Janes From tzot at sil-tec.gr Thu Jun 24 09:53:00 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 24 Jun 2004 16:53:00 +0300 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <2c60f0e0.0406141101.13df93ac@posting.google.com> <9uGdnW9CBYaOalDdRVn-vA@powergate.ca> Message-ID: On Mon, 14 Jun 2004 15:20:43 -0400, rumours say that Roy Smith might have written: >In article <9uGdnW9CBYaOalDdRVn-vA at powergate.ca>, > Peter Hansen wrote: > >> Richard James wrote: >> >> > Well back in my day, in '75, "Real men" programmed in Intel binary >> > machine codes without using those "sissy" Assembly language >> > mnemonics... >> >> You used *binary*?! Ah, luxury.... > >Yeah, right. When I started out, they only let us use zeros. You had >to pay your dues for a few years before they started letting you use any >ones. That's nothing. After four years of intensive coding and debugging, they *might* get generous enough to provide us with a power cord for the machine. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From greg.knaddison at gmail.com Tue Jun 22 18:04:56 2004 From: greg.knaddison at gmail.com (greg.knaddison at gmail.com) Date: 22 Jun 2004 15:04:56 -0700 Subject: java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory Message-ID: Hi, I'm trying to use the httpclient within Jython (see http://jakarta.apache.org/commons/httpclient/ for more information on the httpclient). My Jython version is: Jython 2.1 on java1.4.2_04 (JIT: null) My Java version is: java version "1.4.2_04" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_04-b05) Java HotSpot(TM) Client VM (build 1.4.2_04-b05, mixed mode) My CLASSPATH includes: jdom.jar xerces.jar jython.jar jt400.jar log4j-1.2.8.jar commons-httpclient-2.0.jar When I just try to perform the import statements from example code I get the error pasted below. import org.apache.commons.httpclient.Cookie import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.HttpState import org.apache.commons.httpclient.cookie.CookiePolicy import org.apache.commons.httpclient.methods.GetMethod >>> import org.apache.commons.httpclient.HttpClient Traceback (innermost last): File "", line 1, in ? java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.apache.commons.httpclient.HttpClient.(HttpClient.java:101) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at org.python.core.SyspathJavaLoader.loadClass(SyspathJavaLoader.java) at java.lang.ClassLoader.loadClass(Unknown Source) at org.python.core.Py.findClassEx(Py.java) at org.python.core.SysPackageManager.findClass(SysPackageManager.java) at org.python.core.PackageManager.findClass(PackageManager.java) at org.python.core.SysPackageManager.findClass(SysPackageManager.java) at org.python.core.PyJavaPackage.__findattr__(PyJavaPackage.java) at org.python.core.PyObject.impAttr(PyObject.java) at org.python.core.imp.import_next(imp.java) at org.python.core.imp.import_logic(imp.java) at org.python.core.imp.import_name(imp.java) at org.python.core.imp.importName(imp.java) at org.python.core.ImportFunction.load(__builtin__.java) at org.python.core.ImportFunction.__call__(__builtin__.java) at org.python.core.PyObject.__call__(PyObject.java) at org.python.core.__builtin__.__import__(__builtin__.java) at org.python.core.imp.importOne(imp.java) at org.python.pycode._pyx2.f$0(:1) at org.python.pycode._pyx2.call_function() at org.python.core.PyTableCode.call(PyTableCode.java) at org.python.core.PyCode.call(PyCode.java) at org.python.core.Py.runCode(Py.java) at org.python.core.Py.exec(Py.java) at org.python.util.PythonInterpreter.exec(PythonInterpreter.java) at org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter.java) at org.python.util.InteractiveInterpreter.runsource(InteractiveInterpreter.java) at org.python.util.InteractiveInterpreter.runsource(InteractiveInterpreter.java) at org.python.util.InteractiveConsole.push(InteractiveConsole.java) at org.python.util.InteractiveConsole.interact(InteractiveConsole.java) at org.python.util.jython.main(jython.java) java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory Thanks for any help you can provide. If this is the wrong forum...point me the right way. Greg From chouyiyu at hotmail.com Mon Jun 28 17:46:32 2004 From: chouyiyu at hotmail.com (Yi-Yu Chou) Date: Mon, 28 Jun 2004 21:46:32 +0000 Subject: Display vtkRendererWidgets Message-ID: Dear python users, I tried to display 4 vtkRendererWidgets arrayed in a 2x2 grid. I method that I use is : root = Tk() frame1 = Frame(root).pack(side=TOP) frame2 = Frame(root).pack(side=BOTTOM) x_pane = vtkTkRenderWidget(frame1,width=200,height=200) y_pane = vtkTkRenderWidget(frame1,width=200,height=200) z_pane = vtkTkRenderWidget(frame2,width=200,height=200) all_pane = vtkTkRenderWidget(frame2,width=200,height=200) x_pane.pack(side=LEFT) y_pane.pack(side=RIGHT) z_pane.pack(side=LEFT) all_pane.pack(side=RIGHT) ..................................... Idealy, the arrangement would be like : X | Y -- | -- Z | all However, I got some errors when running my code. It seems that I can't use the syntax: vtkTkRendererWidget(frame1) (I tried to display only one vtkTkRendererWidget by using vtkTkRendererWidget(root), and it worked). Any ideas ? Thanks in advance !!! _________________________________________________________________ ??? MSN eShop?????????????????????????????? ? http://msn.com.tw/eshop From greg at cosc.canterbury.ac.nz Sat Jun 26 22:50:09 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 27 Jun 2004 14:50:09 +1200 Subject: ANN: PyGUI 1.5 Message-ID: PyGUI 1.5 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ This version adds a GLView class for 3D graphics using OpenGL. See 90-glview.py and 91-glview-task.py in the Tests directory of the distribution for examples of its use. What is PyGUI? -------------- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the address above. From __peter__ at web.de Thu Jun 10 13:18:54 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jun 2004 19:18:54 +0200 Subject: passing PyIntType objects by reference References: <10cgctu891gi127@corp.supernews.com> Message-ID: Patrick Stinson wrote: > when passing an python integer value to a C function > ie. > x = 1 > mymod.myfunc(x) > > is it possible to change the value of the python object "x" as happens in > c when you pass a pointer to an int? Is there something fundamentally > wrong with this idea, as this does not happen in pure python anyway? >>> a = 1 >>> b = 1 >>> a is b True If you somehow manage to change a's value into 42, you will change every 1 to 42. Peter From dallasm at aiinet.com Fri Jun 25 14:03:26 2004 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Fri, 25 Jun 2004 14:03:26 -0400 Subject: [python] using try: finally: except Message-ID: > This is a fictional example of what I want.... > > try: > x = 'hello' > except Exception, e: > print "oops" > finally: > y = 'world' > print x," ", y try: try: x = 'hello' except Exception, ex: print "oops" raise # to make the point further finally: y = 'world' print x," ", y - Dallas From p_s_oberoi at hotmail.com Sun Jun 20 16:22:42 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Sun, 20 Jun 2004 15:22:42 -0500 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> Message-ID: > FWIW, I've designed, written, used and killed both types of systems, > and think the DOM-style beats macro-style hands down for the majority > of use-cases, and definitely the most graphic designer-friendly > approach. Suffice to say I've no plans for killing HTMLTemplate any > time soon. ;) I expect it depends on what is changing more. If you are working on code in the application, then you want the templates themselves to have no code. On the other hand, if you are using a "finished" application and want to make changes to the HTML produced without fiddling with the application code, Cheetah-like systems are much more flexible (and simple substitution-only templates are very limiting). -param From a at a.invalid Fri Jun 4 00:26:17 2004 From: a at a.invalid (Timo Virkkala) Date: Fri, 04 Jun 2004 04:26:17 GMT Subject: Need help resolving accidental (honest!) language pissing match In-Reply-To: <69cbbef2.0406031334.6d2a16e1@posting.google.com> References: <69cbbef2.0406020615.7540ad0@posting.google.com> <69cbbef2.0406031334.6d2a16e1@posting.google.com> Message-ID: has wrote: > (p.s. If your interested, the numarray script takes about 1 sec on my > G4/867 running OS10.2.6 - about same speed as the original example. > Only change I made was replacing numint with uniform to get reals. But > numarray wins on sheer size and breadth of functionality, imnsho...;) How long does the AppleScript version take? We want results here! *grin* -- WT From mrjean1ATcomcastDOTnet at no.spam.net Wed Jun 30 02:21:08 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Wed, 30 Jun 2004 06:21:08 GMT Subject: Listing functions in a file IN ORDER References: Message-ID: <290620042332268230%mrjean1ATcomcastDOTnet@no.spam.net> Instead of listing the functions explicitly what about something like this: functions = [(name, function) for name, function in globals().items() if callable(function) and name.startswidth('do')] functions.sort() for _, function in functions: function(*args) /Jean Brouwers ProphICy Semiconductor, Inc. In article , Ian Sparks wrote: > > From: Christopher T King.. > > Note the use of function(*args) instead of apply(function,args). > > apply() is deprecated starting with Python 2.3 in favor of this 'extended > > call syntax'. > > Good advice. Thanks. > > > > functions = ["doTask1", "doThing", "doOther"......] > > > > > > and iterate over that list?> > > Better yet, just have a list of the functions themselves: > > > > functions = [doTask1, doThing, doOther] > > Both good ideas but I want the system to do code discovery because I'm too > dumb to remember to put things in the list. > > > -----Original Message----- > > From: Christopher T King [mailto:squirrel at WPI.EDU] > > Sent: Tuesday, June 29, 2004 12:23 PM > > To: python-list at python.org > > Subject: Re: Listing functions in a file IN ORDER > > > > > > On Tue, 29 Jun 2004, Irmen de Jong wrote: > > > > > Ian Sparks wrote: > > > > > > Just add a list which sums up the function names in the > > order you want: > > > > > > functions = ["doTask1", "doThing", "doOther"......] > > > > > > and iterate over that list? > > > > Better yet, just have a list of the functions themselves: > > > > functions = [doTask1, doThing, doOther] > > > > for function in functions: > > function(*args) > > > > Note the use of function(*args) instead of > > apply(function,args). apply() > > is deprecated starting with Python 2.3 in favor of this > > 'extended call > > syntax'. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From moughanj at tcd.ie Sat Jun 12 01:00:32 2004 From: moughanj at tcd.ie (James Moughan) Date: 11 Jun 2004 22:00:32 -0700 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> Message-ID: <16752bcc.0406112100.37751d84@posting.google.com> Jim Newton wrote in message news:<2it0kiFqud3kU1 at uni-berlin.de>... > > (define has-element (cond list) > > (equal () (member-if #'cond list)))) > > > > Well, it's definitely short. It doesn't exactly translate well, > > though; search the list for a sub-list that starts with an element > > which evaluates to true under cond. Evaluate to the equality of that > > list with the null list. Hmmm. > > > > Not sure what you mean by "does not translate well?" See the later part of my post. :) >Although maybe > i misunderstand, but it looks like you are naming the function the > opposite of what it does? > > (define has-not-element ( cond list) > (null (member-if #'cond list))) > > Are you really trying to find out whether the condition fails > for every element of the list? > Well, I am, but I intended to put a not in front of it! (not (null (member-if #'cond list))) in effect. > By the way, how do you find out in Python if there is > a member of a list that matches a condition? It is something > i often and never know the best way to do it? I can > use a list compression to find ALL the matches, but what > if i only want to know whether or not there is a match? > > -jim In Lisp style- write a function to do it. From km at mrna.tn.nic.in Wed Jun 16 14:32:42 2004 From: km at mrna.tn.nic.in (km) Date: Thu, 17 Jun 2004 00:02:42 +0530 Subject: overlapping regex Message-ID: <20040616183242.GA32669@mrna.tn.nic.in> Hi all, python re module deals with only nonoverlapping matches. how to go for if i want to find out overlapping matches and their span ? regards, KM From has.temp2 at virgin.net Sun Jun 20 16:04:15 2004 From: has.temp2 at virgin.net (has) Date: 20 Jun 2004 13:04:15 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> Message-ID: <69cbbef2.0406201204.7535e057@posting.google.com> Rene Pijlman wrote in message news:<2irad0dr21do731goqv510qcse24sccnh0 at 4ax.com>... > Daniel Ellison: > >With Cheetah (for example) there is no real chance for the template to load > >into an HTML editor for enhancement by a designer. > > This is a good point. ZPT solves this very nicely: > http://zpt.sourceforge.net/ ZPT still embeds programming logic within templates. Not to the same extent as PHP does, and it manages to hide it a bit better (I nicked ZPT's clever "hide stuff in tag attributes" idea myself), but common programming structures - loops, conditionals and assignments - are still firmly wedged into the HTML markup in one form or another. PyMeld, Nevow.renderer and HTMLTemplate genuinely solve this problem by eliminating _all_ embedded logic, reducing templates to pure HTML markup. The only 'special' content within the template are simple name bindings, typically stored within selected tag attributes such as 'id'. This template is converted into a basic DOM-like object model, each named HTML element becoming an independent mutable object within that model. Your application can then push data into this structure to generate the finished HTML page. It's a very different approach to macro-like web templating systems PHP, ZPT, Cheetah, etc., but very similar to that used in desktop GUI applications. FWIW, I've designed, written, used and killed both types of systems, and think the DOM-style beats macro-style hands down for the majority of use-cases, and definitely the most graphic designer-friendly approach. Suffice to say I've no plans for killing HTMLTemplate any time soon. ;) From nicksjacobson at yahoo.com Sat Jun 5 21:46:11 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 5 Jun 2004 18:46:11 -0700 Subject: exec throws an exception...why? Message-ID: This works fine: x = 1 def execfunc(): print x execfunc() So why doesn't this? s = \ """ x = 1 def execfunc(): print x execfunc() """ codeobj = compile(s, "", "exec") d = {} e = {} exec codeobj in d, e Error message: Traceback (most recent call last): File "C:\Nick\proj\python1.py", line 17, in ? exec codeobj in d, e File "", line 6, in ? File "", line 5, in execfunc NameError: global name 'x' is not defined I'm using ActiveState Python 2.3.2 on Windows XP Pro. Thanks! P.S. It does work if I say exec codeobj in d but I don't understand why. From eurleif at ecritters.biz Mon Jun 28 14:59:57 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 28 Jun 2004 14:59:57 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: <2kb85fF9s6hU1@uni-berlin.de> Christopher T King wrote: > Libraries licensed under the GPL can be used without GPLing the code that > uses them - you only have to GPL any extensions you make to the library. No they can't, that's what the LGPL is for. http://www.fsf.org/licenses/gpl-faq.html#IfLibraryIsGPL From hungjunglu at yahoo.com Sun Jun 20 21:35:08 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Jun 2004 18:35:08 -0700 Subject: OT: Chat server References: <8ef9bea6.0406170749.399c4956@posting.google.com> <7xbrjef78f.fsf@ruckus.brouhaha.com> Message-ID: <8ef9bea6.0406201735.6ead8e4b@posting.google.com> Paul Rubin wrote: > > If you are serious about long term, you should probably use Jabber > > instead. > > > > http://www.jabber.org/ > > Why? IRC seems a lot better for chatting. Perhaps this helps a little bit: http://www.jabber.org/about/overview.php Jabber is just more popular, and shows up more on my radar screen. I started to look into Jabber recently only after the suggestion of a guru net friend. I guess part of the reason is: (a) XML-based, (b) formalized standard. The XML-based may seem frivolous, but from what I have seen in the growth of popularity of XML-RPC through the years, I can see that it is a factor in people's choice, despite that they often don't touch the XML part themselves. Jabber is also gradually becoming a developer's tool. Dr. Dobb's Journal recently has an article on it. In fact, when one works with multiple computers, I think Jabber kind of becomes essential: what else is there for centralized monitoring that is open-source, easy to use, language-independent and platform-independent? Sure, XML-RPC may be the easiest way to make programs talk across computers, but Jabber takes care of many admin things for you: security, monitoring/logging, fault-tolerant, etc. Now, I know you are only interested in chatting, but maybe down the future you'd like to expand your system. Think about controlling computers by using the very same chat client. Why limit oneself to Person-to-Person conversations, when one can reserve the power of Person-to-Application and Application-to-Application conversations as well? The possibilities are endless. Also, I just don't see people graviting towards IRC. I see people graviting towards Jabber. E.g.: Mitch Kapor chose Jabber as the instant messenger (IM) for his open-source alternative ("Chandler") to Microsoft's Outlook (see http://osafoundation.org/Chandler-Product_FAQ.htm.) I could be wrong, but that's my overall impression. regards, Hung Jung From lunarium at comail.ru Wed Jun 9 05:05:54 2004 From: lunarium at comail.ru (Sergey Krushinsky) Date: Wed, 09 Jun 2004 13:05:54 +0400 Subject: Constructor overloading Message-ID: <40C6D2F2.10508@comail.ru> Hello all, Is there a common way to emulate constructor overloading in Python class? For instanse, I have 3 classes: 1/ Polar - to hold polar coordinates; 2/ Cartesian - to hold cartesian coordinates; 3/ Coordinates3D, which holds synchronized instances of the both in __p__ and __c__ fields respectively. I want to design Coordinates3D so that when instantiated with Polar argument, self.__p__=argument passed to constructor, and self.__c__ is calculated. When argument is Cartesian, self.__c__=argument, and self.__p__ is calculated. Runtime type checking works, but maybe there is a better way? Thanks in advance, Sergey From fallen at leveltwo.com Tue Jun 8 20:53:48 2004 From: fallen at leveltwo.com (Fred Allen) Date: 8 Jun 2004 17:53:48 -0700 Subject: Perlish dictionary behavior References: Message-ID: <72976037.0406081653.71d4a634@posting.google.com> Mr. Brewer: I fruitlessly tried your "thing counter", as you can see below. >>> class AllThingsStartAtZero(dict): ... def getitem (self, key): ... return dict.get(self, key, 0) ... >>> thingCounts = AllThingsStartAtZero() for thing in >>> ('a','b','c','d','a'): ... thingCounts[thing] += 1 ... Traceback (most recent call last): File "", line 2, in ? KeyError: 'a' >>> thingCounts {} Reason tells me it should work for me using... PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32. ...as it did for you. The runtime interpreter, however, says otherwise. Can you see what I've done wrong...I can't? With thanks in advance, I am, Respectfully yours, Fred Allen From jjl at pobox.com Sun Jun 13 14:44:36 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jun 2004 19:44:36 +0100 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: <873c4z47sb.fsf@pobox.com> Brian van den Broek writes: [...] > I'm still learning Python as a first language since some BASIC quite > some time ago, so my level of knowledge/understanding is not too > sophisticated. From that standpoint, I am wondering why the code that > Michael P. Soulier provided above would worry an experienced Python > programmer. If you have a file open for writing when the process exits, the data you've .write()ten isn't necessarily guaranteed to actually get written to disk. (Apparently, whether it does or not depends on the OS) So, if an exception occurs after the first .write(), and there's no finally: there to .close() your file, you might unexpectedly lose the data that's already been written. More generally, you might hang on to a resource (much) longer than necessary, which is a problem if that resource is expensive (because it's a scarce resource). For example, a database connection. [...] > I had thought I was being careful and smart by always checking for > filepath existence and always explicitly closing files, but I am > wondering what red flag I'm overlooking. [...] Explicitly checking for a file's existence is another Bad Thing, because of race conditions. I think Alex Martelli has written about this here before (google for LBYL and EAFP). John From bkc at Murkworks.com Sat Jun 26 13:23:03 2004 From: bkc at Murkworks.com (Brad Clements) Date: Sat, 26 Jun 2004 13:23:03 -0400 Subject: Python version of Net Peep? Message-ID: Hope this isn't too off topic. I recently read (in the past week) about The Network Auralizer (also known as Peep or Net Peep) http://www.auralizer.com:8080/peep (peep project on sf.net) """Peep is a network monitoring tool that represents network information via an audio interface. Network diagnostics are made not only based on single network events but whether the network sounds "normal". """ I think in whatever blob or page I read, it mentioned another project that does a simiular thing that I have not been able to find. Anyway, I could not find the other project so proceeded to setup Peep from cvs. After a lot of screwing around (Fedora Core 2) and trying to learn some Perl (like, how to download from CPAN .. no clue!) I finally got it to make a bird sound. I have no more time to place with this software, but the concept is interesting. I have some questions. 1. Has anyone used this software or a similar system on a regular basis? Is it just a "geeky neato idea" that isn't practidal in the long-run because it's annoying? 2. Are there any other projects out there that do this and work better? 3. I bet Python has all the parts we need to do this now.. Has anyone tried to do a similar project in Python (even if not finished) ? -- Novell DeveloperNet Sysop #5 _ From peter at engcorp.com Sat Jun 5 07:38:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Jun 2004 07:38:55 -0400 Subject: Ideas for yielding and exception raising In-Reply-To: References: Message-ID: Calvin Spealman wrote: > I was wondering if it was possible, now or with a patch, to do either of the > following: > > 1) Cause another thread's most recent function, or a given function in a > given thread, to yield its generator immediately, such that the generator > can be used to pick back up where it left off. That is, the function itself > wouldn't need an actually yield keyword. Could be used to allow a function > to be controlled in how much time it has per second or somewhat? > > 2) Cause an exception to be raised in all threads that have a reference to a > given object, as if the object itself is raising the exception. This would > allow functions to return Monitor Objects that would raise exceptions if > something bad happened. For example, maybe you want the function to run > continually until someone else requests access to some syncronized data, > and the Monitor would raise the exception at that time. Wouldn't it be better for both of these situations to do it explicitly and actually write the code that way? What is the advantage in putting this in the core and having it happen magically and behind the scenes, as it appears you want to happen? -Peter From michael at stroeder.com Fri Jun 25 03:00:21 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 25 Jun 2004 09:00:21 +0200 Subject: SNMP Toolkit In-Reply-To: References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> Message-ID: <65vsq1-9l1.ln1@nb2.stroeder.com> Mike C. Fletcher wrote: > > PySNMP is actually a *very* heavy library compared to C ASN.1 parsers. > I've certainly run into situations where it's just not fast enough to do > what we want to do. > [..] > That's all processor-bound time, not > IO bound. AFAIK the BER encoding/decoding is implemented in pure Python. If one has the time to implement these routines in C it'd be much less CPU intensive I guess. I wish support for BER and DER to be in the standard lib... Ciao, Michael. From benn at cenix-bioscience.com Thu Jun 10 09:04:27 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 10 Jun 2004 15:04:27 +0200 Subject: python.org CMS In-Reply-To: References: Message-ID: <40C85C5B.1010103@cenix-bioscience.com> Denis S. Otkidach wrote: >On 8 Jun 2004, Aahz wrote: > >A> The team for www.python.org is taking another crack at >A> considering a >A> content management system for handling the website's content. >A> This is >A> particularly important considering, for example, how far >A> beind we are in >A> posting job ads -- getting the community to do our grunt work >A> for us is >A> the primary motivator. >A> > > > > Hello, I administer a site (http://www.elrig.org) using postnuke (http://www.postnuke.com), it's very easy to use and can be customised using PHP. It does have limitations (as do all CMS packages) but it really does cut down the amount of time I have to spend mucking around with the site. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From guettli at thomas-guettler.de Thu Jun 3 08:09:40 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 03 Jun 2004 14:09:40 +0200 Subject: python applets? References: Message-ID: Am Wed, 02 Jun 2004 16:49:49 -0700 schrieb Russell E. Owen: >>One thing you can do in Python that you cannot in Java however is embed >>a user's web browser (such as Internet Explorer or Mozilla) in your >>Python program. In some cases that is more desirable. > > How do you do that? > > I've been using the webbrowser module to open help files for my python > application, but it has several problems. If the user already has their > browser open in another "desktop" (unix users seem fond of switching > between lots of desktops), then the help opens there instead of the > "desktop" that has the current app. Also, I really need to call > webbrowser in a thread, because it takes forever if the web browser > isn't already open. (Also, it's not safe to ask for file://...#anchor > urls; some OSs handle it, others do not. I ended up writing code that > retries without the anchor.) There is a module called webbrowser in the standard library. It opens the default browser. But it does not embed it into an other GUI. Regards, Thomas From jacek.generowicz at cern.ch Fri Jun 11 08:07:36 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jun 2004 14:07:36 +0200 Subject: distutils options Message-ID: The command "build_ext" has a --build-temp option. The command "install" calls the command "build_ext". The command "install" does not accept the --build-temp option. How can I specify --build-temp to "build_ext" when invoking the latter via "install" ? From jepler at unpythonic.net Sun Jun 6 17:55:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 6 Jun 2004 16:55:59 -0500 Subject: debug print shortcut? In-Reply-To: References: Message-ID: <20040606215559.GB15453@unpythonic.net> Here's one way. You specify the expression as a string, and the value or the exception raised is printed. import sys def debug(expression, depth=1): frame = sys._getframe(depth) locals = frame.f_locals globals = frame.f_globals try: value = eval(expression, globals, locals) except: value = sys.exc_info()[1] print >>sys.stderr, "%r -> %r" % (expression, value) >>> debug("3+3") '3+3' -> 6 >>> debug("1/0") '1/0' -> >>> def f(): ... y = 3 ... debug("y+1") ... >>> f() 'y+1' -> 4 Another way would be to pass the result of the expression to debug(), and use inspect.getsource() to locate the line of code in the caller. I haven't written this, but usage might look like >>> debug(3+3) debug(3+3) -> 6 With this approach, exceptions would be propagated, not handled in debug(). Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From wezzy at despammed.com Mon Jun 14 11:26:24 2004 From: wezzy at despammed.com (Wezzy) Date: Mon, 14 Jun 2004 17:26:24 +0200 Subject: Debugging Python with Emacs Message-ID: <1gfdsc1.xki45v1xowbeoN%wezzy@despammed.com> Hi all, i've just seen the pydebug plugin for jEdit and my question is : is there something similar for emacs ? i'm looking for a debugger frontend, a very simple program, just set breakpoint, execute one line and show variables' values ty -- Ciao Fabio From has.temp2 at virgin.net Mon Jun 21 13:51:51 2004 From: has.temp2 at virgin.net (has) Date: 21 Jun 2004 10:51:51 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <69cbbef2.0406201036.53506906@posting.google.com> <2jnslaF121d5gU1@uni-berlin.de> Message-ID: <69cbbef2.0406210951.78661973@posting.google.com> Daniel Ellison wrote in message news:<2jnslaF121d5gU1 at uni-berlin.de>... > has wrote: > > PyMeld, Nevow.renderer and HTMLTemplate all provide complete > > separation of business and presentation logic from HTML markup. > > > > Also, because they're designed specifically for templating, they > > should also be a lot simpler and easier to use than generic DOM > > systems such as ElementTree. > > > > Who said ElementTree was a generic DOM system? Oops. Sorry. Should've said "DOM-style", seeing as the acronym "DOM" is imbued with rather specific meaning. Basically, I mean anything that represents a document as an object model. > Admittedly, the just-in-time lookup on IDs is less than ideal. Better > would be a system which cached the elements containing IDs in a > dictionary on parsing the document. Have you looked at PyMeld/Nevow.renderer/HTMLTemplate at all? These systems only convert "special" elements into independent template nodes, resulting in a much simpler, more efficient object model. HTH From klachemin at home.com Sun Jun 13 13:37:46 2004 From: klachemin at home.com (Kamilche) Date: 13 Jun 2004 10:37:46 -0700 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: <889cbba0.0406130937.3d6c28df@posting.google.com> Thanks for your responses everyone! I'll go take a look at them all. From peter at engcorp.com Tue Jun 29 13:53:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jun 2004 13:53:50 -0400 Subject: win32 pyserial requires javax.comm for py2exe? In-Reply-To: References: Message-ID: Grant Edwards wrote: > I'm trying to package a small Python program using py2exe. > > Everything works fine until I add an "include serial", then > py2exe fails because > > The following modules appear to be missing > ['javax.comm'] Actually, you are assuming too much. It's a warning, not a failure. The .exe file is generated and will run just fine under Windows. Don't bother editing PySerial! You'll just create a maintenance hassle for yourself. -Peter From dyoo at hkn.eecs.berkeley.edu Mon Jun 7 16:15:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Jun 2004 13:15:24 -0700 (PDT) Subject: ANN: reminder for Bay Area Python Users Group meeting this week, June 10,2004 Message-ID: [Copied from the original announcement on baypiggies.net] Thursday, June 10, 2004 Agenda: Python's Type System Speaker: Bruce Eckel Where: Carnegie Institute of Washington, Stanford CA About the talk Bruce will be repeating his keynote from PyCon DC 2004. From the PyCon website: Many people observe that type checking is a religious discussion best avoided. I often agree, having started more than my share of fires in this area. However, there are a few issues surrounding types and type checking that capture the essential distinctions between programming languages. This understanding makes the pitfalls worth the risk, so in this talk I will look at various issues and arguments surrounding the concept of type, and in particular examine the phenomenon of 'latent typing' (often called 'weak typing'), why the concept is powerful, and how it is expressed in different languages. In the process, I will attempt to clear up many of the issues that have arisen during attempts to describe Python's place in the spectrum of language features. For driving directions and more information, please visit the Baypiggies web site at: http://baypiggies.net/ We hope to see you there! From vng1 at mac.com Wed Jun 16 23:28:49 2004 From: vng1 at mac.com (Victor Ng) Date: Wed, 16 Jun 2004 23:28:49 -0400 Subject: libxml2 and node identity Message-ID: I've been trying to find information with how to figure out node identity in libxml2 - but I'm at a loss. I can't seem to find what I'm looking for on the xmlsoft.org site and google doesn't seem to help at all with the following query: http://www.google.com/search?q=libxml2+node+identity Here's a snippet to show the problem: >>> import libxml2 >>> doc = libxml2.newDoc('1.0') >>> root = doc.newChild(None, 'root', None) >>> print root, doc.children >>> print root._o, doc.children._o What I'd _like_ to do is to be able to check that two nodes are actually identical. The Python wrappers as well as the PyCObject references don't seem to match up. I also can't seem to find any way to do something like "node.isSameNode(otherNode)" Help! From pet100us at yahoo.com Wed Jun 16 10:01:24 2004 From: pet100us at yahoo.com (pet100us) Date: 16 Jun 2004 07:01:24 -0700 Subject: Something simular to java's hsqldb for python?? Message-ID: <792ea523.0406160601.71eae208@posting.google.com> Hi, Is there some program that is simular to java's hsqldb (http://hsqldb.sourceforge.net/). It is a relational database that can easily be used within a small java program without installing a MySQL, Postgresql etc. It is used within the same virtual machine whitout installing anything extra. Is there somthing similar for python? I need a small database that I can build into my application. When the program starts the database should start and when the programm exits the database can stop. I know that the samething could be done with xml files or binary files. The database has some advantages. e.g. when I want to change the program that it uses a "real" database I dont need to replace much of the code. I just change the database driver an off we go. (the programmers dream) Thanks in advance pet100us From jacek.generowicz at cern.ch Wed Jun 16 07:16:10 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 16 Jun 2004 13:16:10 +0200 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: Alexander Schmolck writes: > you seem to imply that somehow scheme does something inappropriate No, that's what you inferred; I never intended to imply any such thing. I merely pointed out the facts: - Scheme iteration is recursion based - Scheme lexical scoping is not significantly different from Python's; the apparent differences can be explained by the above. Please don't falsely attribute any value judgements on the subject, to me. From jmccall at houston.rr.com Thu Jun 17 02:12:45 2004 From: jmccall at houston.rr.com (J. W. McCall) Date: Thu, 17 Jun 2004 06:12:45 GMT Subject: How to download a file from an HTTP server given the URL? Message-ID: Hopefully a simple question: how do I download a file (jpg image) to my hard drive from a website assuming I have its (the image's) URL? I tried urllib.urlretrieve() and it's not working. I'm relatively new to Python, so I'm probably make a dumb mistake or looking in the wrong place. Any help would be appreciated. Thanks, J. W. McCall From frithiof.jensen at die_spammer_die.ericsson.com Tue Jun 22 07:44:22 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 22 Jun 2004 13:44:22 +0200 Subject: Except MySQL error References: Message-ID: "Florian Lindner" wrote in message news:cb7dum$lfj$06$1 at news.t-online.com... > > I don't know which error to except... ...Apart from reading the docs, you can try it in idle and read what the 'puter says ;-) From xholcik1 at fi.muni.cz Thu Jun 17 10:00:25 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Thu, 17 Jun 2004 14:00:25 GMT Subject: Saving search results in a dictionary Message-ID: Hi everyone! How can I simply search text for regexps (lets say (.*?)) and save all URLs(1) and link contents(2) in a dictionary { name : URL}? In a single pass if it could. Or how can I replace the html &entities; in a string "blablabla&blablabal&balbalbal" with the chars they mean using re.sub? I found out they are stored in an dict [from htmlentitydefs import htmlentitydefs]. I though about this functionality: regexp = re.compile("&[a-zA-Z];") regexp.sub(entitydefs[r'\1'], url) but it can't work, because the r'...' must eaten directly by the sub, and cannot be used so independently ( at least I think so). Any ideas? Thanks in advance. -i ---------------------------------------_.)-- | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* ----------------------------------------''-- From tzot at sil-tec.gr Thu Jun 24 09:50:08 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 24 Jun 2004 16:50:08 +0300 Subject: Searching for the best scripting language, References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <40cdc47a$0$20179$afc38c87@news.easynet.co.uk> Message-ID: On Mon, 14 Jun 2004 11:34:18 -0400, rumours say that Peter Hansen might have written: >I'm waiting to see anyone succeed at writing Python code that badly. This is a FAQ :) http://www.python.org/doc/faq/programming.html#id19 -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From abra9823 at mail.usyd.edu.au Mon Jun 28 10:51:35 2004 From: abra9823 at mail.usyd.edu.au (Ajay Brar) Date: Tue, 29 Jun 2004 00:51:35 +1000 Subject: AttributeError Message-ID: <014101c45d1f$6aeef0f0$5700a8c0@nazgul> hi! i have the following code that doesn't work contextForm = {"contextName":"test2","contextDescription":"test22","number":"1","contextName1":"test1","contextDescription1":"test11"} if contextForm.has_key("number"): num=contextForm["number"].value the error i get is AttributeError: 'str' object has no attribute 'value' the trace is bash$ python Python 2.3.4 (#3, May 28 2004, 13:31:19) [GCC 2.95.2 19991024 (release)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> contextForm = {"contextName":"test2","contextDescription":"test22","number":"1","contextName1":"test1","contextDescription1":"test11"} >>> if contextForm.has_key("number"): ... num=contextForm["number"].value ... Traceback (most recent call last): File "", line 2, in ? AttributeError: 'str' object has no attribute 'value' any ideas why it isn't working? thanks Ajay Brar CS Honours 2004 Smart Internet Technology Research Group http://www.it.usyd.edu.au/~abrar1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at visualtrans.de Tue Jun 29 10:32:56 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 29 Jun 2004 16:32:56 +0200 Subject: unicode and shelve In-Reply-To: References: Message-ID: Guy Robinson wrote: > Hello, > > When I try and create a unicode key with a shelve I get the following > error: > > "TypeError: String or Integer object expected for key, unicode found" > > Is there anyway I can use unicode keys with shelve's? Well, not "Python unicode objects". You can however encode the python unicode strings to utf-8 or utf-16 if retaining your unicode characters is what you are looking for. Ofcourse, for lookups, you need to do the same thing. If you choose to use UTF-16, you might want to consider indicating endianess when encoding (e.g. key = key.encode("utf-16le")) to avoid the byte-order mark being written at the start of each key. Something like the following should work: # -*- coding: cp1252 -*- import shelve d = shelve.open("test.dat") key = u"?bersetzung".encode("utf-16le") d[key] = "Translator" HTH, -- Vincent Wehren > > TIA, > > Guy From allen at premierweb.com Sat Jun 12 21:42:51 2004 From: allen at premierweb.com (Allen Unueco) Date: Sun, 13 Jun 2004 13:42:51 +1200 Subject: time.strftime Timezone issue In-Reply-To: References: Message-ID: Never mind, I just looked at Modules/timemodule.c and now I realize it that time.strftime() is just a wrapper for the c library function of the same name. I guess I'll just live with my 'time.tzname[time.daylight]' code. -allen Allen Unueco wrote: > I feel that the '%Z' format specifier from strftime() returns the wrong > value when daylight savings is in effect. > > Today the following is always true: > time.strftime('%Z') == time.tzname[0] > > Shouldn't it be: > time.strftime('%Z') == time.tzname[time.daylight] > > -allen From wweston at att.net Wed Jun 2 16:35:45 2004 From: wweston at att.net (wes weston) Date: Wed, 02 Jun 2004 20:35:45 GMT Subject: Problem building Python 2.3.4 on RedHat Enterprise; tcl not found In-Reply-To: References: Message-ID: Russell E. Owen wrote: > I'm trying to build Python 2.3.4 from source on a RedHat Enterprise > machine for installation in a net-wide accessible directory /net/python. > I tried all of the following variants of ./configure (the first was > required for Python 2.3.3 on RedHat 9): > ./configure --prefix=/net/python --enable-unicode=ucs4 > ./configure --prefix=/net/python > ./configure --prefix=/net/python --enable-unicode=ucs2 > > All of these result in the ominous message (even the last form, which > really surprised me): > checking for UCS-4 tcl... no > > Having gone through the make in one case and gotten no _tkinter, I'm > expecting the same results for the other two cases. > > Any hints? At this point I'm spinning my wheels. I'm not even sure if > tcl is built with UCS-4 or UCS-2 on RedHat Enterprise. > > My fallback will be to build my own tcl/tk. Blasted RedHat. Python 2.3.3 > was working just fine under RedHat 9, and I'd have been happy to keep > using it, but Tkinter is acting flaky after the OS upgrade -- > tkColorChooser.askcolor is broken (returning strings that Python has no > idea what to do with). > > -- Russell Russell, There is some help here: http://www.talkaboutprogramming.com/group/comp.lang.python/messages/290343.html Appendix A was what I needed to get things working on RH9. wes From EX5VENNTD01-SA at Ixfin-mmarellise.com Thu Jun 10 10:21:41 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Thu, 10 Jun 2004 16:21:41 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B74201634F27@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = jceasar at tmp.org Recipient(s) = python-list at python.org; Subject = ello! =)) Scanning time = 06/10/2004 16:21:40 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment AttachedFile.zip contained WORM_BAGLE.GEN-1 virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From marco at reimeika.ca Thu Jun 10 21:17:43 2004 From: marco at reimeika.ca (marco) Date: 10 Jun 2004 21:17:43 -0400 Subject: tempfile broken in 2.3.4? Message-ID: Hi, It's probably me, but I'm really not sure what I'm doing wrong: BEFORE: bash-2.05b$ python2.2 Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile >>> tempfile.mktemp() '/tmp/@20219.0' >>> tempfile.template = 'ham' >>> tempfile.mktemp() '/tmp/ham1' >>> AFTER: bash-2.05b$ python2.3 Python 2.3.4 (#1, Jun 10 2004, 19:23:10) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile >>> tempfile.mktemp() '/tmp/tmpReDZMK' >>> tempfile.template = 'ham' >>> tempfile.mktemp() '/tmp/tmp6PcHuc' >>> Huh? -- marco at reimeika.ca Gunnm: Broken Angel http://amv.reimeika.ca http://reimeika.ca/ http://photo.reimeika.ca From lbates at swamisoft.com Wed Jun 2 17:42:25 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 2 Jun 2004 16:42:25 -0500 Subject: python applets? References: Message-ID: You might want to take a look at: http://grail.sourceforge.net/ http://www.modpython.org/ Larry Bates, Syscon, Inc. "Andreas R?sdal" wrote in message news:Pine.LNX.4.58.0406022142380.12694 at jaguar.stud.ntnu.no... > Hi, > > Is there such a thing as python applets for web browsers? (eg. such as > java applets?) I think that could be useful. > > Andreas R. > > From dmq at gain.com Mon Jun 14 19:25:57 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 14 Jun 2004 16:25:57 -0700 Subject: Can someone explain this weakref behavior? References: Message-ID: On Fri, 11 Jun 2004 18:09:32 -0400, "Tim Peters" wrote: >[David MacQuigg, trying to keep track of how many instances of a class > currently exist] > >... > >> Seems like we could do this more easily with a function that lists >> instances, like __subclasses__() does with subclasses. This doesn't have >> to be efficient, just reliable. So when I call cls.__instances__(), I >> get a current list of all instances in the class. >> >> Maybe we could implement this function using weak references. If I >> understand the problem with weak references, we could have a >> WeakValueDictionary with references to objects that actually have a >> refcount of zero. > >Not in CPython today (and in the presence of cycles, the refcount on an >object isn't related to whether it's garbage). > >> There may be too many entries in the dictionary, but never too few. > >Right! > >> In that case, maybe I could just loop over every item in >> my WeakValueDictionary, and ignore any with a refcount of zero. >> >> def _getInstances(cls): >> d1 = cls.__dict__.get('_instances' , {}) >> d2 = {} >> for key in d1: >> if sys.getrefcount(d1[key]) > 0: >> d2[key] = d1[key] >> return d2 >> _getInstances = staticmethod(_getInstances) >> >> I'm making some assumptions here that may not be valid, like >> sys.getrefcount() for a particular object really will be zero immediately >> after all normal references to it are gone. i.e. we don't have any >> temporary "out-of-sync" problems like with the weak references >> themselves. >> >> Does this seem like a safe strategy? > >An implementation of Python that doesn't base its garbage collection >strategy on reference counting won't *have* a getrefcount() function, so if >you're trying to guard against Python switching gc strategies, this is a >non-starter (it solves the problem for, and only for, implementations of >Python that don't have the problem to begin with ). > >Note that CPython's getrefcount() can't return 0 (see the docs). Maybe >comparing against 1 would capture your intent. > >Note this part of the weakref docs: > > NOTE: Caution: Because a WeakValueDictionary is built on top of a Python > dictionary, it must not change size when iterating over it. This can be > difficult to ensure for a WeakValueDictionary because actions performed by > the program during iteration may cause items in the dictionary to vanish > "by magic" (as a side effect of garbage collection). > >If you have threads too, it can be worse than just that. > >Bottom line: if you want semantics that depend on the implementation using >refcounts, you can't worm around that. Refcounts are the only way to know >"right away" when an object has become trash, and even that doesn't work in >the presence of cycles. Short of that, you can settle for an upper bound on >the # of objects "really still alive" across implementations by using weak >dicts, and you can increase the likely precision of that upper bound by >forcing a run of garbage collection immediately before asking for the >number. In the absence of cycles, none of that is necessary in CPython >today (or likely ever). > >Using a "decrement count in a __del__" approach isn't better: only a >reference-counting based implementation can guarantee to trigger __del__ >methods as soon as an object (not involved in a cycle) becomes unreachable. >Under any other implementation, you'll still just get an upper bound. > >Note that all garbage collection methods are approximations to true >lifetimes anyway. Even refcounting in the absence of cycles: just because >the refcount on an object is 10 doesn't mean that any of the 10 ways to >reach the object *will* get used again. An object may in reality be dead as >a doorknob no matter how high its refcount. Refcounting is a conservative >approximation too (it can call things "live" that will in fact never be used >again, but won't call things "dead" that will in fact be used again). Thank you for this very thorough answer to my questions. I have a much better understanding of the limitations of weakrefs now. I also see my suggestion of using sys.getrefcount() suffers from the same limitations. I've decided to leave my code as is, but put some prominent warnings in the documentation: ''' [Note 1] As always, there are limitations. Nothing is ever absolute when it comes to reliability. In this case we are depending on the Python interpreter to immediately delete a weak reference when the normal reference count goes to zero. This depends on the implementation details of the interpreter, and is *not* guaranteed by the language. Currently, it works in CPython, but not in JPython. For further discussion, see the post under {"... weakref behavior" by Tim Peters in comp.lang.python, 6/11/04}. -- One other limitation - if there is any possibility of an instance you are tracking with a weakref being included in a cycle (a group of objects that reference each other, but have no references from anything outside the group), then this scheme won't work. Cyclic garbage remains in memory until a special garbage collector gets around to sniffing it out. ''' You might want to put something similar in the Library Reference. -- Dave From ville at spammers.com Sat Jun 19 17:00:07 2004 From: ville at spammers.com (Ville Vainio) Date: 20 Jun 2004 00:00:07 +0300 Subject: Watershed Python Versions References: <40dd3107.0406191120.6879a1c6@posting.google.com> Message-ID: >>>>> "Ted" == Ted writes: Ted> I would like to collect opinions on which versions of Python Ted> should be considered watershed versions. By this I mean Ted> versions which are stable and contain significant landmark Ted> features. All Python versions are (supposed to be) stable :). I think it's generally perceived that 2.2 is a watershed version. It's the introduction of "modern" Python, with iterators, generators and new style classes. 2.0 might be also - 1.5.2 is the last "old" Python, and the version that has no doubt been irritating to many, due to Red Hat using it as the default Python in the old versions (pre 8.0). In fact I found writing for Python 1.5.2 almost intolerable, having to do without a+=1 (writing a=a+1 instead, ah, the pain). ISTR list comprehensions were introduced back on 2.0 too, but I really started loving them on 2.1 era. -- Ville Vainio http://tinyurl.com/2prnb From peter at engcorp.com Thu Jun 17 08:42:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jun 2004 08:42:02 -0400 Subject: How to download a file from an HTTP server given the URL? In-Reply-To: References: Message-ID: J. W. McCall wrote: > Ok, update: I got it to work downloading to the default temp directory > with default temp names using urllib.urlretrieve(). If I try to specify > the path and filename, if says that the file doesn't exist. I don't see > why it doesn't just create that file. Also try to give examples of real code when asking questions like this. What path and filename, etc? Show snippets that you typed at the interactive prompt and cut and paste (not retyped!) directly into the message. Also specify your platform and the version of Python you are using, and any other critical info you can think of. We're not mind-readers**. -Peter ** Well, some people here are, but they've already read your mind and concluded that you will find the answer on your own, given enough time, so they aren't wasting their valuable time helping you. Bastards. :-) From ewilhelm at somethinglike.sbcglobalDOTnet Sat Jun 5 10:16:40 2004 From: ewilhelm at somethinglike.sbcglobalDOTnet (Eric Wilhelm) Date: Sat, 05 Jun 2004 14:16:40 GMT Subject: C API for new-style classes Message-ID: Hi, By new-style classes, I'm referring to the changes which came into 2.2 as a result of PEP 252 and 253. I discovered this problem when trying to use the Perl Inline::Python module with a python class that was inheriting from the new builting 'object' class like so: class MyClass(object): The problem is in detecting that this class should be treated as a class from C. With old-style classes, PyClass_Check() returns true, but it doesn't work with new-style classes. With those, apparently we have to use PyType_Check(), but I cannot find this in the extension documentation. Another problem comes in identifying instances of this type of type-class, where PyInstance_Check() no longer returns true. Does anyone know of any documentation for the API for new-style classes? (It must work somehow or the python interpreter couldn't do it.) Thanks, Eric From hans at deragon.biz Fri Jun 4 15:13:10 2004 From: hans at deragon.biz (Hans Deragon) Date: 4 Jun 2004 12:13:10 -0700 Subject: Fetching the stdout & stderr as it flows from a unix command. Message-ID: Greetings. I am performing: commands.getstatusoutput("rsync "); rsync takes a long time and prints out a steady stream of lines showing which file it is currently working on. Unfortunatly, the commands.getstatusoutput() fetchs everything and there is no way to ask it to copy the output of the command to stdout/stderr. Thus when rsync takes an hour, I have no clue where it is at. Anybody has a suggestion how to let stdout/stderr print out on the console when calling a unix command? Best regards, Hans Deragon -- Consultant en informatique/Software Consultant Deragon Informatique inc. Open source: http://www.deragon.biz http://facil.qc.ca (Promotion du libre) mailto://hans at deragon.biz http://autopoweroff.sourceforge.net (Logiciel) From imbosol at aerojockey.com Thu Jun 3 18:09:33 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 3 Jun 2004 15:09:33 -0700 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <7x4qpsvdfg.fsf@ruckus.brouhaha.com> <10bujgn6m8bnfb0@corp.supernews.com> Message-ID: <60dfb6f6.0406031409.1a609b9a@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<10bujgn6m8bnfb0 at corp.supernews.com>... > I think the competition does gcc (and others) good. You just made Baby RMS cry. -- CARL BANKS From noamr at correctme.users.sourcephorge.net Wed Jun 2 14:52:45 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Wed, 02 Jun 2004 21:52:45 +0300 Subject: scoping questions In-Reply-To: References: Message-ID: David Stockwell wrote: > Hi, > > Another of my crazy questions. I'm just in the process of learning so > bear with me if you can. I actually ran it.... with two test cases > > TEST CASE 1: > Say I have the following defined: > --- beginning of code snippet ---- > > def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > > aFile = open('/tmp/test','r') > me(aFile) > data = aFile.read() > print data > > ------ end of code snippet ---- > my test file has a sentence 'This is a test of the /tmp/test file' > > When I run it I observed this output: > hello world > This is a test of the /tmp/test file > > Now what this means to me and this is where I need your help: > > When I call the 'me' function, its passing a reference to my original > aFile variable. > Inside the me function, I'm guessing it is now a new reference to the > same original aFile contents. When I assign it to a simple string, it > simply changes the local reference to point to that string. Since its a > copy of the reference, it doesn't affect the caller's value. > > In essence if i understand correctly > > At the global scope I have > > variable aFile that points to an instance of a 'file' > > Inside the me function scope I have > a parameter named aFile that is a local copy of the original reference > of what global::aFile was pointing to. > Essentially local::aFile is pointing to a file object > > At this point I have two references to the file object. > > When I assign the new value to aFile (local) it simply does the > assignment. The global reference is untouched. > > I would sort of expect this behavior as I am not returning anything > > If test #1 is true, then test case 2 boggles me a bit > > TEST CASE 2: > ------- > def me(aFile): > """ > Note I am testing scoping > """ > aFile = 'hello world' > print aFile > > > def me2(dog): > """ > Note I am testing scoping > """ > print "Inside me2" > dog.close() > > > aFile = open('/tmp/test','r') > me(aFile) > data = aFile.read() > print "test1", data > aFile.close() > aFile = open('/tmp/test','r') > > me2(aFile) > print "test2", aFile.read() > ===== > > It bombs out on the last line because aFile was closed in the function > 'me2'. > > Perhaps the way to explain it is that Inside me2 when my copy of the > original reference is made, I have a global and local variable both > referencing the same 'object'. I am able to do operations in the local > me2 scope and have them effect the behavior of the global scope. > > Its just a bit confusing because python is apparently smart enough to > realize that my action on the local reference hasn't redefined the > capability of the global so it has allowed this to occur on the actual > global file referenced object. (as opposed to just a local copy). And I > didn't return anything.... > > > I'm just confused a bit here.... Perhaps someone can clarify > > Thanks > > David > ------- > Tracfone: http://cellphone.duneram.com/index.html > Cam: http://www.duneram.com/cam/index.html > Tax: http://www.duneram.com/index.html > > _________________________________________________________________ > Looking to buy a house? Get informed with the Home Buying Guide from MSN > House & Home. http://coldwellbanker.msn.com/ > > Hello, I'm not sure I've understood entirely, but I'll try to explain: When you have a reference to an object, you can do anything you like with it - close it if it's a file, for example. When you write, if the function 'me', aFile = 'hello world', you simply discard your reference to the file, and create a new reference, called 'aFile' too, to the string 'hello world' you've created. You do all this in the local namespace, so it doesn't affect the global namespace. Maybe this is the point that should be clarified: There's only one pool of objects. What's global and local are the namespaces - references to those objects. I hope this helped, Noam Raphael From peufeu at free.fr Sat Jun 26 11:09:48 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Sat, 26 Jun 2004 17:09:48 +0200 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: On Fri, 25 Jun 2004 15:45:51 -0700, Mark Hahn wrote: > Pierre-Fr?d?ric Caillaud wrote: > >> Does the language enforce the bool return type on the ? variant ? > > That's a good idea. In fact I'm not that sure anymore. I like the fact Python operators like "or" and "and" return values themselves and not booleans ; that's extremely useful. Thus imposing boolean return types to these "?" method might break some usability. Then again, it might also be a good idea, but it needs somoe thinking ! > You should join our mailing list. We need ideas. The traffic is light Done ! > and are about to move on to language > features (like coroutines) of the stackless engine we are built on. Very good ! From hemanth_sethuram at yahoo.com Fri Jun 11 03:29:59 2004 From: hemanth_sethuram at yahoo.com (Hemanth P.S.) Date: 11 Jun 2004 00:29:59 -0700 Subject: Does a Python Sound Library exist? References: Message-ID: <9be5e130.0406102329.73422021@posting.google.com> For extracting .MP3 ID3 tags, you can find code snippets to do that in the excellent free online Python book on a chapter on Objects and Object Orientation. You can cook up a similar thing for .WAV headers (if you know the .wav format) --Hemanth P.S. gohaku wrote in message news:... > Hi everyone, > I would like to know if there is a sound library for manipulating and > retrieving information from .WAV or .MP3 Files. > I came across the page for Pythonware Sound Toolkit but that toolkit is > no longer available. > > Thanks in advance. > -gohaku From cweimann at k12hq.com Mon Jun 28 14:53:45 2004 From: cweimann at k12hq.com (Christopher Weimann) Date: Mon, 28 Jun 2004 14:53:45 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> Message-ID: <20040628185345.GA37699@smtp.k12us.com> On 06/28/2004-02:40PM, Christopher T King wrote: > > > > Is there anything like this in the Python world ? > > Libraries licensed under the GPL can be used without GPLing the code that > uses them - you only have to GPL any extensions you make to the library. I thought that was only true of LGPL not GPL. -- ------------------------------------------------------------ Christopher Weimann http://www.k12usa.com K12USA.com Cool Tools for Schools! ------------------------------------------------------------ From wk8l at yahoo.com Fri Jun 25 16:22:33 2004 From: wk8l at yahoo.com (Dan) Date: 25 Jun 2004 13:22:33 -0700 Subject: Python Magazine exists! References: Message-ID: I have to agree with you. $61.42 is way TOO MUCH money just to access a website for an online 'zine. In all fairness, Ithere are some low volume (number or subscribers in the hundreds to a few thousand) technical journals I subscribe to that are around $20-$30 a year for quarterly in print journals mailed to me with little advertising. I think Pyzine would get more subscribers if they made their prices more reasonable. Dan Ognen Duzlevski wrote in message news:> Hi, > > I went to see your magazine and it looks pretty nice. However, you do publish quarterly and in my humble opinion, a > yearly subscription of 49 Euros is crazy. > > Ognen From irmen at -nospam-remove-this-xs4all.nl Thu Jun 10 18:44:26 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 11 Jun 2004 00:44:26 +0200 Subject: How to get decimal form of largest known prime? In-Reply-To: References: <2is27mFqeen8U1@uni-berlin.de> Message-ID: <40c8e44f$0$36860$e4fe514c@news.xs4all.nl> Daniel Yoo wrote: >>>>x = 2**2436583 - 1 [...] >>>>(x / 10) % 10 > > 0L > ### > > At least we can figure out that the number ends with a '07'. If we > continue this way, we can quickly get the other digits. ^^^^^^^ Sadly, no you can't. Just try it ;-) >>> i=1 >>> while True: ... print (x/i)%10, ... i*=10 ... 7 0 4 9 6 9 5 4 4 4 1 8...... slower and slower..... --Irmen From mjackson at alumni.caltech.edu Thu Jun 3 23:20:25 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 4 Jun 2004 03:20:25 GMT Subject: View Talks - Buy 'Zen of Python' Tshirt - Free with PyCON by References: Message-ID: Steve Holden writes: > Mark Jackson wrote: > > Steve Holden writes: > > > > > >>We are also taking orders for extra shirts, including shipping to those > >>that cannot attend. Please email zope at toenjes.com to reserve your > >>shirts. All requests must be received by March 19. > > > > > > Did this ever happen? Last ftom zope at toenjes.com was ". . .by the end > > of the month"; that was in mid-April, and now there's no response at > > all. . . . > > > I'll see if I can find out and get back to the list. Thanks; by strange coincidence I did get a response about 20 hours after posting. It appears there will be T-shirts, but after some further delay. I'll see that news gets posted here when there is some. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Civilization as we know it will come to an end sometime in this century unless we can find a way to live without fossil fuels. - David Goodstein From dotsero at qwest.net Thu Jun 3 14:48:55 2004 From: dotsero at qwest.net (Michael Livsey) Date: Thu, 03 Jun 2004 12:48:55 -0600 Subject: ANNEVOLVE Releases its First Graphical/GUI Program Message-ID: VizANN-1.0 is now available from the ANNEvolve team at Sourceforge.net. This program shows the detailed working of a recurrent binary ANN with two neurons. VizANN graphically demonstrates the operational details of this type of ANN (Artificial Neural Network). There are two neurons in the VizANN display, and weight sets are supplied that allow it to perform the XOR function. Other weight sets can be entered into the diagram and their effect will be shown. VizANN is written in Python and it runs on all the Windows and Linux variants. The Python interpreter is a free download from www.python.org. Much more information, and all source code for VizANN is included in the downloadable files at: http://sourceforge.net/projects/annevolve Comments and questions about VizANN may be posted on the ANNEvolve mailing list by sending email to annevolve-devel at lists.sourceforge.net. You may post without subscribing, but anyone may subscribe to this mailing list. The list archives may be viewed at: http://sourceforge.net/mailarchive/forum.php?forum_id=32765. The ANNEvolve team is experimenting with the Evolution of Artificial Neural Networks (ANNs). They are combining the two fields of Evolutionary Computation and Artificial Neural Networks. Find out more about other ANN evolution programs at the Annevolve project at: http://annevolve.sourceforge.net From BELLEMAIL-SA at exponent.com Wed Jun 23 22:43:33 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 19:43:33 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F82@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = anthony_raj at persistent.co.in Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 265 Scanning time = 06/23/2004 19:43:32 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment yours.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From squirrel at WPI.EDU Tue Jun 29 09:09:31 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Tue, 29 Jun 2004 09:09:31 -0400 Subject: exec example - I don't understand In-Reply-To: References: Message-ID: On Tue, 29 Jun 2004, kepes.krisztian at peto.hu wrote: > >>> print a # show the result > {1: 3.25, 2: 200} > >>> > > >>> print a.keys() > [1, 2] > >>> exec "x = 3; print x" in a > 3 > > But I dont' understand that: > exec "x = 3; print x" in a > > So what this code do ? > Why we need "in a" ? The 'in a' tells exec to run the code using the dictionary a to read and store variables. In this case, when x is set equal to 3, it's actually a['x'] being set to 3. Try these examples to get an idea for what's going on: >>> a = {'x': 15} >>> exec 'print x' in a 15 >>> exec 'print x' NameError: name 'x' is not defined >>> exec 'x*=3; print x' in a 45 >>> x NameError: name 'x' is not defined >>> a['x'] 45 >>> exec 'y=10; print y' in a 10 >>> y NameError: name 'y' is not defined >>> a['y'] 10 From mrjean1 at comcast.net Wed Jun 23 12:44:32 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Wed, 23 Jun 2004 16:44:32 GMT Subject: asyncore module for loading websites References: Message-ID: <230620040955357687%mrjean1@comcast.net> Maybe this is what you are looking for /Jean Brouwers ProphICy Semiconductor, Inc. In article , Markus Franz wrote: > Hi. > > Some URLs are passed to a python script as command line options like the > following command > > ./script.py http://www.websites1.com http://www.website2.com > > (The number of passed URLs varies...) > > Now my problem is: > > How can I load and show the contents of these websites (from sys.argv) in > parallel by using the asyncore module? At the moment I use the following > script (it uses one child process for each URL): > > > import sys, os > for url in sys.argv[1:]: > pid = os.fork() > if pid == 0: > # placeholder for the loading routine > print website_contents > break > > > Is the same possible with the asyncore module? > Thank you. > > > Markus Franz > > From hungjunglu at yahoo.com Tue Jun 29 12:59:00 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 29 Jun 2004 09:59:00 -0700 Subject: Parameterized Functions without Classes References: <8ef9bea6.0406252008.15f8443e@posting.google.com> Message-ID: <8ef9bea6.0406290859.7488cddb@posting.google.com> Jacek Generowicz wrote: > hungjunglu at yahoo.com (Hung Jung Lu) writes: > > I have counted 7 messages in the thread, so far. How come no one > > mentioned the keyword "closure"? > > I was tempted, but realized that this would only lead to me producing > a combination of my 3 favourite c.l.py rants, so I refrained. How about a codeblock-based language that does the following: f = function( args={x;y;z=g(5);}, deco={synchronized;}, init={.static=1;}, code={ w = x+y+z+.static; .static += 1; w; }); f(1,2,3) # returns 7 f(1,2,3) # returns 8 (a) "args" codeblock is executed in such a way that each additional name is used to build up the argument list of the function. (Special setattr()/setslot() function is used, if you know what I mean.) (b) "deco" codeblock builds up names to be used for special decorated features. (c) "init" codeblock is run only the first time the function is invoked. (d) "code" is the regular codeblock of the function. The return value is the value of the codeblock, which is the value of the last expression. (f) functions are self-aware. The "self" name is optional: an initial dot suffices. This is enough to take of closure needs, I think. (g) functions are built by using the "function" function. Don't ask me chicken-and-egg questions. regards, Hung Jung From miki.tebeka at zoran.com Mon Jun 14 10:50:36 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 14 Jun 2004 16:50:36 +0200 Subject: what about unsigned and signed 8 bits number, 16 bits, etc?? In-Reply-To: <20040614132256.19010.qmail@web50605.mail.yahoo.com> References: <20040614132256.19010.qmail@web50605.mail.yahoo.com> Message-ID: <20040614145036.GM1124@zoran.com> Hello sarmin, > When it is an integer number, what is the range of the integer number > and long integer number?? The range of int is the same as of the machine int (the C compiler that was used to build Python). Note that in 2.4+ int overflow will automatically become long. Long numbers are a big as your computer memory can handle (try 1L<<10000). > do we have typecasting of 8bits or 16bits signed and unsigned number > in python? Not that I know of. I use this simple class: class SizedNum: def __init__(self, size, value=0): self.mask = (1 << size) - 1 self.set(value) def set(self, value): self.value = value & self.mask And also: def sign_extend(num, size): '''Sign exten number who is `size' bits wide''' res = num & MASK(size - 1) # Positive if (num & (1L << (size - 1))) == 0: return res # Negative, 2's complement res = ~res res &= MASK(size - 1) res += 1 return -res HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From jmdeschamps at cvm.qc.ca Fri Jun 11 10:07:36 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 11 Jun 2004 07:07:36 -0700 Subject: Does a Python Sound Library exist? References: Message-ID: <3d06fae9.0406110607.6995fd33@posting.google.com> gohaku wrote in message news:... > Hi everyone, > I would like to know if there is a sound library for manipulating and > retrieving information from .WAV or .MP3 Files. > I came across the page for Pythonware Sound Toolkit but that toolkit is > no longer available. > > Thanks in advance. > -gohaku There is TkSnack http://www.speech.kth.se/snack/ Good luck, Jean-Marc From grante at visi.com Tue Jun 8 16:28:14 2004 From: grante at visi.com (Grant Edwards) Date: 08 Jun 2004 20:28:14 GMT Subject: [python] Is there a python written fax program out there? References: Message-ID: On 2004-06-08, David Stockwell wrote: > Today I was in a meeting and someone mentioned they were > looking for some software whereby they could run their own fax > server (ie a computer with a modem, someone sends a fax, and > the software convertes it to an image and drops it in an email > box). > > I'm posting this here incase someone happens to know of a > python implementation or other language implementation that is > either free or for sale? If so, I'd like to know where to get > them. For a single-user, efax is pretty decent. For a group fax servers, Hylafax is the usual answer. -- Grant Edwards grante Yow! They don't hire at PERSONAL PINHEADS, visi.com Mr. Toad! From jeffbarish at starband.net Thu Jun 17 18:40:27 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Thu, 17 Jun 2004 16:40:27 -0600 Subject: Easiest way to port Python program to PDA Message-ID: I have been developing a Python program with two intercommunicating (using sockets) parts, one of which runs on a desktop and the other on a PDA.??For?ease?of?development,?I?developed?them?both?on?a?desktop.? Now that I have them working on the desktop, I need to move the part destined for a PDA to a PDA.??I?had?originally?planned?to?use?a?Sharp Zaurus because it runs Linux (the OS of my desktop system) and I had found a Python port that was supposed to be available for that platform (Riverbank Computing).??Unfortunately,?Riverbank?Computing?just discontinued their port.??They?refer?interested?parties?to?another?port (http://www.vanille.de/projects/python.spy), but that site has no code to download and does not respond to queries.??Accordingly,?I?have?to conclude that there is no Python port available for the Zaurus so I am back to square 1. My question in short: does anyone have suggestions for the easiest way to move the Python program to a PDA.??The?program?uses?a?few?modules from the standard distribution (2.3): socket, thread, time, os, and Tkinter.??I?expected?to?rewrite?the?GUI,?but?I?am?hoping?to?rewrite?the rest of the program as little as possible. I have discovered a python for StrongARM Pocket PCs.??There?is?also?a python port for PalmOS, but that project appears to be dormant.??I?have also discovered handhelds.org, which explains how to run linux on iPAQ, but it isn't clear to me that it is possible to run python on the resulting linux installation.??Does?anyone?have?comments?on?the?Palm?vs Pocket PC choice???How?difficult?will?it?be?to?program?the?GUI?on?the PDA???I?presume?that?I?am?going?to?have?to?do?that?using?a?language other than python, so I wonder about integrating it with the python code.??If?I?have?to?program?the?GUI?in?another?language,?should?I?bite the bullet and rewrite the entire program in that language???The?program is under 300 lines, it wouldn't be that big a deal. -- Jeffrey Barish From machongbo at sohu.com Fri Jun 18 21:03:54 2004 From: machongbo at sohu.com (machongbo at sohu.com) Date: Sat, 19 Jun 2004 11:03:54 +1000 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 -------------- next part -------------- A non-text attachment was scrubbed... Name: id43342.zip Type: application/octet-stream Size: 29832 bytes Desc: not available URL: From simonroses at granisla.com Tue Jun 8 10:20:29 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Tue, 8 Jun 2004 16:20:29 +0200 Subject: any simple and multiplatform database? References: <001901c44d59$a27bffc0$0200a8c0@lucifer> <16581.49846.271286.610876@montanaro.dyndns.org> Message-ID: <00d401c44d63$c10a1120$0200a8c0@lucifer> I dont mind if is not SQL, so I agree that metakit works for me :) and looks very nice! Sincerely, SRF ----- Original Message ----- From: "Peter Hansen" Newsgroups: comp.lang.python To: Sent: Tuesday, June 08, 2004 4:07 PM Subject: Re: any simple and multiplatform database? > Simon Roses Femerling wrote: > > > I have already looked at sqllite, but I think metakit > > (http://www.equi4.com/metakit/python.html) > > is better for me, at least. > > > > Any experience with metakit ? > > Metakit is not a SQL database, but it might be fine > for you. It's *trivial* to download, install, and > experiment, and the web page for it shows pretty much > all you need to know in a straight-forward fashion. > > Given that this is Python, with the interactive prompt > and all, there's no excuse for not trying it out. :-) > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list From hungjunglu at yahoo.com Mon Jun 7 15:09:08 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 7 Jun 2004 12:09:08 -0700 Subject: exec throws an exception...why? References: <3415c0lg306oec1a69c3mkolnbhfbku243@4ax.com> <8ef9bea6.0406060718.39f1001b@posting.google.com> Message-ID: <8ef9bea6.0406071109.644eb6c6@posting.google.com> nicksjacobson at yahoo.com (Nick Jacobson) wrote: > > "If the [local variable] definition occurs in a function block, the > scope extends to any blocks contained within the defining one..." Strictly speaking, the above statement still holds true. That is, from a lawyer's point of view. :) > But, the following code fails, saying that y is undefined: > > def main(): > s = \ > """ > y = 3 > def execfunc(): > print y > execfunc() > """ > d = {} > e = {} > exec s in d, e > > if __name__ == '__main__': > main() Very good example. > Conclusion: > > Is code from the exec statement on the module level or not? It > doesn't get its locals mapped to globals. But it also doesn't get its > local variables nested. So it gets neither benefit. IMO it should > get one or the other. i.e. the second piece of code should work. The exec statement is usually considered an slightly advanced topic. And frankly I think people that use it at the module level would be minority. So, having its behavior parallel to the case of nested-scope would seem to make more sense, to me. Remember also that the "global" statement can be used inside the code string, which is reminiscence that we are inside a local scope, just like the case of function. So, if you wish, the inconsistency could be considered as a bug in Python, and it may even be good idea to submit a bug report. After all, nested scope is considered a relative new feature, given Python's history (over a decade.) Or there may be some obscure way of tweaking things so to convince Python that it is inside a function scope at the moment of "def execfunc():"... Anyway, we are talking about voodoo magic here... :) regards, Hung Jung From davidf at sjsoft.com Fri Jun 11 17:42:02 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 11 Jun 2004 23:42:02 +0200 Subject: A faster way of finding historical highs/lows In-Reply-To: <47e15340.0406111301.6cf1b3f1@posting.google.com> References: <47e15340.0406110356.3629d3e6@posting.google.com> <47e15340.0406111301.6cf1b3f1@posting.google.com> Message-ID: Eamonn Sullivan wrote: > Peter Hansen wrote in message news:... > >>Eamonn Sullivan wrote: >> >> >>>1. Find the most recent date when there was an equal or higher (or >>>lower) value than X. >> >>The fastest algorithm might depend on how you use the data, as well. >>For example, do you update the data often, and search it rarely, >>or update it rarely and do the search very often? If searching >>many times between updates, some preprocessing will likely make things >>go much faster. >> >>Both of your examples sound to me like they would benefit by >>using sort(), then a binary search. Sort is very fast relative >>to things like the Python loops you are doing, so using it to >>prepare the data before the search can be a good step. >> >>-Peter > > > Thanks for this. At the moment, the software answers a few questions > (highest/lowest, longest streak, etc.) once per retrieval of data. The > database retrieval, though, is *by far* the biggest time sapper, so a > little preprocessing would be almost unnoticeable in comparison, > probably (depends on how much, of course). > > So, I'm guessing I could sort on the particular price field I'm using > (decorate-sort-undecorate), and then just find the most recent date > among the subset of data that meets the criteria (higher or lower). Is > that what you mean? By binary search, do you mean further reorganizing > the data into a binary tree using date? If you have this in a relational database, you might find that the database can answer the question quicker for you, using indexes if neccessary ... select max(xxx) from yyy where zzz > 40 with an index on xxx and zzz will usually be done quickly internally by the database, and then you just get the result returned rather than having to process it David From tzot at sil-tec.gr Wed Jun 16 04:53:35 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 16 Jun 2004 11:53:35 +0300 Subject: somewhat OT: function to produce n as distinct colors as possible References: <87pt7zrkcp.fsf@titan.staselog.com> Message-ID: On Wed, 16 Jun 2004 11:13:42 +0300, rumours say that Edvard Majakari might have written: >Ok, not strictly Python related: I wonder if any of you graphical Python >folks have run accross some handy resource for the given topic. >The problem is that of producing histograms, where n distinct items can be >plotted simultaneously. However, when n goes over 6 it is not very easy to >make up colors that are easily distinguishable from each other. So, now >I'm thinking of two alternatives: >1. Create an algorithm distinct_colors(n, bg), which produces n-1 as > distinct colors as possible (where bg is one of the colors) and returns > those colors in RGB color model as tuple of decimals (r, g, b). > > Eg. distinct_colors(4, (255, 255, 255)) would return > > ((255, 0, 0), (0, 255, 0), (0, 0, 255)) > > assuming that "pure-rgb" red, green and blue are visually the three as > distinct colors as possible from white. [snip] I think the algorithm would be easier in the (hue, saturation, brightness) domain instead of the (red, green, blue) one. Try selecting colours evenly spaced in the hue axis. The colorsys module shall be your good friend for conversions to and fro :) -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From troy at gci.net Wed Jun 16 02:39:52 2004 From: troy at gci.net (Troy Melhase) Date: Tue, 15 Jun 2004 22:39:52 -0800 Subject: how to become a really good Python programmer? In-Reply-To: References: Message-ID: <200406152239.52717.troy@gci.net> On Tuesday 15 June 2004 10:06 pm, Randall Smith wrote: > I've been programming in Python for about 2 years. I think it offers > the best combination of simplicity and power of any language I have > explored. As I write more and larger and complex programs, I need to > code better. [snip] > Following Guido around would be ideal, but I will settle for > a good book. Any recommendations for learning resources? Yes. 1. import this 2. Write more code. The more you write, the more opportunity you have to learn. 3. Study the code written by folks more experienced than you. There's a ton of good code in the standard library, and there's even more available on the net. Pick a package and read it until you understand it. Evaluate the problems it solves and how well it solves them. 4. Refactor your own code, and be merciless when doing it. There's no teacher like breaking 10,000 lines of code. 5. Just as you are doing now, don't stop learning. -- Troy Melhase, troy at gci.net -- Tolerance is the virtue of the man without convictions. - G. K. Chesterton From a.schmolck at gmx.net Mon Jun 7 07:06:43 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Mon, 07 Jun 2004 12:06:43 +0100 Subject: Misunderstanding about closures References: <10c7t036lt9vg27@corp.supernews.com> Message-ID: "Michael Geary" writes: > Alexander May wrote: >> When I define a function in the body of a loop, why doesn't the >> function "close" on the loop vairable? See example below. > > Hi Alex, > > Your message title is correct: you're misunderstanding how closures work. > :-) Not necessarily. See below. [snipped] > BTW, you'll see the same effect in JavaScript or any other language that > supports closures. Not quite. In fact in the language that more or less started it all, scheme, the standard iteration construct 'do' does indeed introduce a *new binding* on each iteration. ;; Note: this is is a literate translation and *not* idiomatic scheme -- no ;; schemer would write it like that (define l '()) ; an empty list (do ((x 0 (+ 1 x))) ; start x with 0, then add 1 at each step ((= x 10)) ; stop when x is 10 (set! l (cons (lambda () x) l))) ; add a new function closing over x to ; the *front* of l (set! l (reverse l)) ; since we added to the front we ; have to reverse l ((list-ref l 3)) ; get list element 3 and execute it > 3 ;ANSWER Common Lisp OTOH doesn't -- like python: ;; This is similarly non-idiomatic (and won't work in emacs lisp, which hasn't ;; got lexical scope) (defvar l '()) ; an empty list (do ((x 0 (+ 1 x))) ; start x with 0, then add 1 at each step ((= x 10)) ; when x is 10 return the reversed list (setf l (cons (lambda () x) l))) ; add a new function closing over x to ; the *front* of l (setq l (reverse l)) ; since we added to the front we ; have to reverse l (funcall (nth 3 l)) ; get list element 3 and execute it > 10 From peter at engcorp.com Tue Jun 15 19:14:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jun 2004 19:14:32 -0400 Subject: thread help In-Reply-To: References: <40cea9cb$1@nntp0.pdx.net> Message-ID: Roger Binns wrote: > In the simplest case you can just make all your threads be > daemon. Python will shutdown when there are no non-daemon > threads left, so you can just exit your main loop and all > will shutdown. However that means the worker threads just > get abruptly stopped in the middle of what they were > doing. > > (IMHO it would be *really* nice if Python provided a way > to interrupt threads). Sounds like you can't eat your cake and have it, too. If you _could_ interrupt threads**, wouldn't that mean "the worker threads just get abruptly stopped in the middle of what they were doing"? -Peter ** There is a way to interrupt threads in Python now, but it requires an extension routine, or perhaps something with ctypes. Findable in the archives for this newsgroup/list. From jepler at unpythonic.net Thu Jun 3 11:03:56 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 3 Jun 2004 10:03:56 -0500 Subject: speed problems In-Reply-To: References: Message-ID: <20040603150355.GI19278@unpythonic.net> In addition to the items Steve Lamb noted, I have a few suggestions: Place the whole script in a function and call it. This will give you an immediate speedup of some percent, because lookup of names that are local to a function is faster than looking up names at the module level. > for line in lf.readlines(): Unless the bzip2 or gzip modules don't support it, you should write for line in lf: instead. This is likely to improve memory consumption, and may improve the program speed too. > if string.count( line, "INFECTED" ): > vname = re.compile( "INFECTED \((.*)\)" ).search( line ).group(1) Unless you arrived at this two-step process through profiling, it's probably better to write m = infected_rx.search(line) if m: vname = m.group(1) ... > if string.count( vname, ", " ): > for vnam in string.split( vname, ", " ): [...] > else: If there are no ", " in vname, the split will produce a single item. Also, there's no no reason to use the "string" module anymore, as opposed to string methods. Finally, splitting on single characters is likely to be optimized, but I'm not sure. I'd just use for vnam in vname.split(","): vnam = vnam.strip() > if vnam not in virstat: > virstat[vnam] = 1 > else: > virstat[vnam] += 1 You have several alternatives here: try: virstat[vnam] += 1 except KeyError: virstat[vnam] = 1 or virstat[vnam] = virstat.get(vnam, 0) + 1 Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tor.iver.wilhelmsen at broadpark.no Sun Jun 6 03:19:00 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 06 Jun 2004 09:19:00 +0200 Subject: Why did no one invent Python before? References: <6ee58e07.0406041003.25e359fc@posting.google.com> <6ee58e07.0406050515.6de4cd02@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) writes: > I prefer to use the right language for each job. Careful: With so many languages being written these days, someone are bound to name their language "Right" simply because all the other words are taken. :) From mwilson at the-wire.com Wed Jun 2 09:53:11 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 02 Jun 2004 09:53:11 -0400 Subject: Is this just for readability to the developer? python References: Message-ID: In article , "David Stockwell" wrote: >I was looking through some of our source code and I found this: > >initModule( "$Revision: 3.1 $".split(" ")[1] ) > >In this example, it looks like only the '3.1' is actually passed to the >function. Which leads me to speculate that the rest of it is just there to >make it easier for the developer when looking at source code to see what >version of the module is being used. [ ... ] To amplify David Brodie's answer: The string "$Revision: 3.1 $" is probably supplied by CVS, the Concurrent Versioning System, and that literal in that line of the program changes every time the Python module is checked into change control. You're really looking at a slick way to communicate between CVS and the module user. Regards. Mel. From flupke at nonexistingdomain.com Fri Jun 4 10:43:11 2004 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 04 Jun 2004 14:43:11 GMT Subject: heredoc and variables Message-ID: <3U%vc.849$FW.169229408@hebe.telenet-ops.be> Hi, i have php script where i use a heredoc type of variabele to print out some html. In the heredoc, i use the values of several other vars. php snippet: $div=<<
    $titel_name
    $url So the variabele div is a heredoc which will contain some html woth the vars titel_name and url in it. 1) Can i do this in python and how? 2) Consider following heredoc end_html=""" """ I have to write it like this to avoid having an empty line added above AND below the actual string when using it. So this would produce the extra empty lines end_html=""" """ I actually think that the last piece of code is more readable. Is there a way to stop that behaviour or is there a kind of trim function i can apply to get rid of the 2 extra lines? Thanks From bdesth.quelquechose at free.quelquepart.fr Thu Jun 3 06:02:43 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Jun 2004 12:02:43 +0200 Subject: question regarding Guido's main article In-Reply-To: References: Message-ID: <40bef041$0$13920$636a15ce@news.free.fr> Christopher Baus wrote: > Hi, > > I'm new to Python and am learning the languge for writing test scripts for > C++. > > I just finished reading this: > > http://www.artima.com/weblogs/viewpost.jsp?thread=4829 > > article. Coming from C++ I am a bit confused about the relationship of > the interpreter to main. I think I understand the __name__ variable, it > just doesn't work as expected. > > I implemented a script using the form described in the article. The then > did: > >>python >> >>>>execfile("myscript.py") > > > This immediately called my main function, which should have only been > called if __name__ == "__main__". But then __name__ *was* '__main__'. > What I expect was that __name__ would be something other than __main__ and > I would be put back at the prompt for instance... > > >>>>execfile("myscript.py") >>>>foobar = "foo and a bar" >>>>main(foobar) For this, you have to use the import statement: >>>import myscript >>>foobar = "foo and a bar" >>>myscript.main(foobar). Note that 'myscript.py' must be in the sys.path for import to work correctly. HTH Bruno From lbates at swamisoft.com Mon Jun 21 16:09:11 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 21 Jun 2004 15:09:11 -0500 Subject: Check if file is overwritten References: Message-ID: When you open file, get last modified date using os.path.getmtime() and set it aside. When you are done with the file, get the os.path.getmtime() again again, if it has changed you will know it. HTH, Larry Bates Syscon, Inc. "Esben Skov Pedersen" wrote in message news:Xns950FDFB6A260Aspamatgeeklinuxdk at 130.225.247.90... > How do i check if a file is overwritten by another program, while my script > is running? > > I have to monitor changes and act on them on the fly. > > It only has to work on windows, so perhaps it is possible to set op a hook > to the system. I saw that done on a folder at one time, but i can't find > the example now. > > I would rather that it uses a minimum of CPU, since the program always will > be running. Does anybody know the solution? > > /Esben From donnal at donnal.net Tue Jun 22 14:02:27 2004 From: donnal at donnal.net (Donnal Walter) Date: Tue, 22 Jun 2004 13:02:27 -0500 Subject: deepcopy in new-style classes Message-ID: I have defined a set of new-style classes that override __getstate__() and __setstate__(). For these classes, copy.deepcopy works fine as long as __getstate__() returns a value other than None, False, [], {}, '' and 0. The 2.3 documentation says: """For new-style classes, if __getstate__() returns a false value, the __setstate__() method will not be called. """ Why is this the case? And is there someway to get around this, i.e. force __setstate__() to be called anyway? Donnal Walter Arkansas Children's Hospital From ark at acm.org Fri Jun 18 11:19:40 2004 From: ark at acm.org (Andrew Koenig) Date: Fri, 18 Jun 2004 15:19:40 GMT Subject: Using multiple "*"-style arguments References: Message-ID: > > Does this do what you want? > > > > x = struct.pack((">HhhhhhhHHHL", i, *(bounds + b[0:2] + b[6:9] + > > [len(s)])) > > No, unfortunately, because the arguments in the bounds and b lists are > numeric, so adding them isn't the right thing. Have you tried it? b[0:2] is a list, so + means concatenation, not addition. From dbasch at yahoo.com Tue Jun 15 20:23:47 2004 From: dbasch at yahoo.com (Derek Basch) Date: Wed, 16 Jun 2004 00:23:47 GMT Subject: Combined natural and unnatural list sorting References: <20040615213822.26735.qmail@web20810.mail.yahoo.com> Message-ID: In article , tjreedy at udel.edu says... > > "Derek Basch" wrote in message > news:20040615213822.26735.qmail at web20810.mail.yahoo.com... > > Hello All, > > > > I need to sort a list using an unnatural sequence. > > > > I have a list like so: > > > > foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] > > > > print foo.sort() > > > > ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S'] > > > > > > The order that I actually need is: > > > > ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] > > > > > > So, in other words, I need the colors sorted alphabetically and the the > sizes > > sorted logically. > > Last I knew, 'Black' sorts before, not after 'White' ;-) Or do you really > want colors alphabetically? > > TJR > > > > > Your right, B comes before W. I will go back to my dunce corner now :) Derek From brian at sweetapp.com Tue Jun 22 12:55:37 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 22 Jun 2004 18:55:37 +0200 Subject: ANN: Vancouver Python Workshop - Talk deadline TODAY In-Reply-To: <40D5D59A.4060004@sweetapp.com> References: <40CF1521.5040901@sweetapp.com> <40D5D59A.4060004@sweetapp.com> Message-ID: <40D86489.5060604@sweetapp.com> This is a reminder that the deadline for submitting talks for the Vancouver Python Workshop is TODAY! We've had a lot of great talks submitted but there is still space in the schedule for more. To submit a talk, see: http://www.vanpyz.org/conference/registration/submissions.html For general conference information, see: http://www.vanpyz.org/conference About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Talk submissions: until June 22nd (today!) Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From iv at an.voras.fer.hr Mon Jun 14 07:19:40 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Mon, 14 Jun 2004 13:19:40 +0200 Subject: Unix fold command in python In-Reply-To: <70efe2ee.0406140252.2c7b0989@posting.google.com> References: <70efe2ee.0406140252.2c7b0989@posting.google.com> Message-ID: dean wrote: > Hello Group: > > Hopefully someone can answer my question. > > I have a unix shell command that I would like to emulate in python. > The command is FOLD. I am scanning a file that contains a stream of > data with a record size of 242 bytes but no record delimiters. There Have you looked at the 'struct' module? From aweil at mail.ru Sun Jun 27 17:34:50 2004 From: aweil at mail.ru (alejandro david weil) Date: Sun, 27 Jun 2004 18:34:50 -0300 Subject: Can you make this faster? In-Reply-To: <889cbba0.0406271022.fd1f9ac@posting.google.com> References: <889cbba0.0406271022.fd1f9ac@posting.google.com> Message-ID: <200406271833.37904.aweil@mail.ru> On Sun June 27 2004 15:22, Kamilche wrote: > I have a routine that I really need, but it slows down processing > significantly. Can you spot any ineffeciencies in the code? > > This code makes a critical function of mine run about 7x slower than > using a prebuilt format string. For maximum flexibility, it would be > best to calculate the format string using this method, so I'd dearly > love to keep it. > > def fmtstring(args): > delim = '\0' > fmt = [] > fmt.append('<') > for arg in args: > t = type(arg) > if t == types.StringType: > l = len(arg) > fmt.append(str(l) + 's') > elif t == types.IntType: > fmt.append('i') > elif t == types.LongType: > fmt.append('q') > elif t == types.BooleanType: > fmt.append('c') > elif t == types.FloatType: > fmt.append('d') > else: > raise Exception("Can't pack argument of type %s!" % t) > s = ''.join(fmt) > s = s + '\0' > return s I've tried this: import types def fmtstring(args): delim = '\0' fmt = [] fmt.append('<') for arg in args: t = type(arg) if t == types.StringType: l = len(arg) fmt.append(str(l) + 's') elif t == types.IntType: fmt.append('i') elif t == types.LongType: fmt.append('q') elif t == types.BooleanType: fmt.append('c') elif t == types.FloatType: fmt.append('d') else: raise Exception("Can't pack argument of type %s!" % t) s = ''.join(fmt) s = s + '\0' return s typedic = { types.StringType : 's', types.IntType: 'i', types.LongType: 'q', types.BooleanType: 'c', types.FloatType:'d'} def myfmtstring(args): global typedic f2 = '<' t = None for arg in args: t = type(arg) if t == types.StringType: f2 += str(len(arg)) try: f2 += typedic[t] except: #check the exception here! raise Exception("Can't pack argument of type %s!" % t) return f2+'\0' if __name__=='__main__': import unittest TIMES = 10000 class TestFmtFuncBase(unittest.TestCase): def setUp(self): self.what = ['hola','que','tal',324,454,False] def runFuncOnce(self): #shouldnt be here! assert(False) def runFuncTimes(self, times=TIMES): for i in xrange(times): self.runFuncOnce() class TestFunction1(TestFmtFuncBase): def runFuncOnce(self): return fmtstring(self.what) def testSpeed(self): """Run function a lot of times to check its time""" self.runFuncTimes() def testValue(self): """Check return value""" print self.runFuncOnce() class TestFunction2(TestFmtFuncBase): def runFuncOnce(self): return myfmtstring(self.what) def testSpeed(self): """Run function a lot of times to check its time""" self.runFuncTimes() def testValue(self): """Check return value""" print self.runFuncOnce() suiteOriginal = unittest.TestSuite() suiteOriginal.addTest(unittest.makeSuite(TestFunction1)) suiteNew = unittest.TestSuite() suiteNew.addTest(unittest.makeSuite(TestFunction2)) unittest.TextTestRunner(verbosity=2).run(suiteOriginal) unittest.TextTestRunner(verbosity=2).run(suiteNew) And seems to be not faster: ---------------------------------------------------------------------- Run function a lot of times to check its time ... ok Check return value ... <4s3s3siic ok ---------------------------------------------------------------------- Ran 2 tests in 0.477s OK Run function a lot of times to check its time ... ok Check return value ... <4s3s3siic ok ---------------------------------------------------------------------- Ran 2 tests in 0.396s OK But, anyway, the problem seems to be the: f2 += str(len(arg)) line. If you take it off, you'll see that time reduces to half! Why? How to fix? Don't know! :-( Sorry, dave -- + There is no dark side of the moon really. Matter of fact it's all dark. From look at in.signature Mon Jun 28 15:26:47 2004 From: look at in.signature (Maurizio Colucci) Date: Mon, 28 Jun 2004 19:26:47 GMT Subject: python desktop References: Message-ID: km wrote: > > Hi all, > Are there any plans for a pure python desktop for linux ? > are there any similar projects ? > regards, > KM This desktop environment http://segusoland.sourceforge.net is being rewritten in python, with a different name (probably "Logical Desktop") and some important changes (KDE integration as a kicker applet, integrated web browsing, no abstraction from the concept of location anymore). (Although I must admit if prolog supported Qt and KDE, I'd use that instead :-) Prolog is incredibly underrated.) -- Best Regards, Maurizio Colucci Please remove the uppercase letters "S,P,A,M": seSgPuAsMo.forever at tin.it From brent.hughes at comcast.net Wed Jun 2 01:09:15 2004 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Wed, 02 Jun 2004 05:09:15 GMT Subject: What Help Authoring program do you recommend? Message-ID: <%hdvc.34031$eY2.15747@attbi_s02> I recently downloaded HelpMaker for free, but there was no documentation with it. Does someone know where I can find such documentation? Or, alternatively, where I can find another good free Help authoring program.? Brent From pwatson at redlinepy.com Tue Jun 22 15:46:59 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 22 Jun 2004 14:46:59 -0500 Subject: Writing binary to stdout Message-ID: <2jrglkF153jroU1@uni-berlin.de> How can I write lines to stdout on a Windows machine without having '\n' expanded to '\r\n'. I need to do this on Python 2.1 and 2.3+. I see the msvcrt.setmode function. Is this my only path? Is it valid to change the mode of stdout? The file.newlines is not writable. From peter at engcorp.com Fri Jun 11 07:52:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 07:52:53 -0400 Subject: lua: any comments In-Reply-To: <4cec047f.0406110341.1ec84bc2@posting.google.com> References: <4cec047f.0406110341.1ec84bc2@posting.google.com> Message-ID: <7t2dnf1HB72KAFTdRVn-hw@powergate.ca> Douglas wrote: > I'd like to hear your comments on lua (www.lua.org). Whose, Python programmers? Anyway, did you check the archives for comp.lang.python before asking? Try http://groups.google.com/groups?q=group%3Acomp.lang.python+lua first, since Lua has been discussed here before. -Peter From fumanchu at amor.org Sat Jun 5 12:06:33 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 5 Jun 2004 09:06:33 -0700 Subject: if does not evaluate Message-ID: Jim Newton wrote: > A question that has bothered me ever since looking at python > the first time is that not everything evaluates to something. Are you only bothered by it because there's no ifelse operator? ;) > I am wondering what is the reason for this. Would making > everying evaluate have caused the langugage to be less > efficient execution-wise? or was it a choice to enforce some > sort of standard? Only Zen standards: 1. Beautiful is better than ugly. 2. Explicit is better than implicit. 3. Simple is better than complex. 6. Sparse is better than dense. 7. Readability counts. > I've read a few discussions about the fact that there is > no if/then/else operartor. > > Wouldn't this problem be easily solved by making the built > in keywords actually be evaluatable. > > I.e., x = if something: > expr1 > else: > expr2 > > parentheses would of course be optional as they are for > all expressions. You'll first have to convince many people that this is a "problem" to be "solved". Why is your solution "better than": if something: x = expr1 else: x = expr2 Then you need to show why the alternatives aren't good enough: If your main desire is to code in some other language while still using Python, write your own VB-style IIf function: >>> def IIf(expression, truepart, falsepart): ... if expression: ... return truepart ... return falsepart ... >>> x = IIf('something', 'expr1', 'expr2') >>> x 'expr1' If your main desire is to provide a one-liner, use a tuple (which is still ugly): >>> x = ('expr2', 'expr1')[bool('something')] >>> x 'expr1' Or a mapping (which is prettier, but still uglier than the regular if: else: >>> x = {True: 'expr1', ... False: 'expr2'}[bool('something')] >>> x 'expr1' Or a more generic morphing function: >>> def surjection(input, mappings): ... mappings = dict(mappings) ... return mappings[input] ... >>> x = surjection(bool('something'), {True: 'expr1', False: 'expr2'}) >>> x 'expr1' >>> x = surjection(bool('something'), [(True, 'expr1'), (False, 'expr2')]) >>> x 'expr1' >>> x = surjection('something', [('something', 'expr1'), ('other', 'expr2'), ('than', 'expr2')]) >>> x 'expr1' Robert Brewer MIS Amor Ministries fumanchu at amor.org From hungjunglu at yahoo.com Thu Jun 17 11:49:50 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 17 Jun 2004 08:49:50 -0700 Subject: OT: Chat server References: Message-ID: <8ef9bea6.0406170749.399c4956@posting.google.com> "Miki Tebeka" wrote: > I'm looking for a chat (IRC) server. > Nothing fancy. It has to be free, standalone and with logging. > Python based will be ideal. If you are serious about long term, you should probably use Jabber instead. http://www.jabber.org/ On the server side, there are a few free servers. You can save the logs. Unfortunately, there are not Python based. There is one simple Python client. It usually is not difficult to tweak clients to suit your needs. A universal protocol is much more important than the programming language, in the long run. So Jabber might be good. Nonetheless, one thing I don't like about the Jabber community is that there is not much coordination in centralizing efforts, you see quite a bit of chaos. Jabber has a tremendous potential of becoming the de-facto standard for cluster computing communication, but most of the developers keep this dream of popularizing it to replace AOL/Microsoft/Yahoo messenger, or dreaming about all corporates using Jabber for instant messaging, which is totally unrealistic in the comming years, if ever. As for developers that want to use Jabber for cluster computing, there are no good/organized introductory tutorials, no good help manuals like Python. Jabber has been around for quite a while, but I guess lack of organization skills, and unrealistic dream of popularizing IM, is what has lead to its primitive state for developers. Yes, there are two books out there, but I've been told they are not good. There are thousands of Jabber developers out there, but somehow the lack of centralization means a lot of efforts are being wasted, and each person has his own little website, hundreds of low-quality clients that are useless for developers, and near total lack of usable documentation. I guess the chaos has a bit to do with Unix background of many people there. In the Windows world, people are used to the "click-click-click-done" philosophy, so they think about user-friendliness issues much more. In Unix world, when they say they are done with a software product, it actually means that you have to pull this library from here, download that virtual machine from that website, go and edit some paths and config files, cross your fingers and pray, download more libraries, repeat the process all over again a few times. With that kind of mentality, it is no surprise to see chaos and wasted efforts all over. regards, Hung Jung From tor.iver.wilhelmsen at broadpark.no Sun Jun 6 03:17:00 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 06 Jun 2004 09:17:00 +0200 Subject: if does not evaluate References: <2ids8kFmfpi0U1@uni-berlin.de> Message-ID: Jim Newton writes: > I.e., x = if something: > expr1 > else: > expr2 Try exploiting that a boolean expression evaluates to 0 or 1: x = (expr1, expr2)[something]; Keep in mind that this might break on some later release of Python if they decide to make boolean its own type, but at least it works for 2.3.3. From __peter__ at web.de Sat Jun 19 02:37:52 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jun 2004 08:37:52 +0200 Subject: Am I crazy regarding the style guide for function names? References: <2jhlvtF11ti8bU1@uni-berlin.de> Message-ID: Leif K-Brooks wrote: > I try to make my code comply to the Python style guide > (http://www.python.org/peps/pep-0008.html). Last time I read it, I swear > that it said to use CamelCase for often-used functions and > lower_case_with_underscores for rarely-used utility functions. Now it > says to use low_case_with_underscores for everything, but it claims to > be last updated in 2001. Am I crazy? Not yet, according to http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/peps/pep-0008.txt?r1=1.20&r2=1.24 :-) Peter From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Fri Jun 25 17:12:42 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Fri, 25 Jun 2004 23:12:42 +0200 Subject: IDE's and wxPython widgets References: <40dbf95d$1@e-post.inode.at> Message-ID: Hi ! Boa don't run with the lasted version of wxPython. From EX5VENNTD01-SA at Ixfin-mmarellise.com Fri Jun 18 19:17:41 2004 From: EX5VENNTD01-SA at Ixfin-mmarellise.com (System Attendant) Date: Sat, 19 Jun 2004 01:17:41 +0200 Subject: [MailServer Notification] To External Recipient: a virus was foun d and action taken. Message-ID: <2F1B2094CD74D7119C010002A545B7420163590B@EX5VENNTD01.venaria.marelli.it> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = mguchte at hotmail.com Recipient(s) = python-list at python.org; Subject = Information Scanning time = 06/19/2004 01:17:40 Engine/Pattern = 7.000-1004/1.895.00 Action taken on message: The attachment Part-2.zip contained WORM_NETSKY.Z virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From __peter__ at web.de Wed Jun 16 12:47:14 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Jun 2004 18:47:14 +0200 Subject: Making classes from Metaclasses globally available References: Message-ID: Jacek Generowicz wrote: > Peter Otten <__peter__ at web.de> writes: > >> Jacek Generowicz wrote: >> >> > Peter Otten <__peter__ at web.de> writes: >> > >> >> Note, however, that dynamically inserting variables is not the best >> >> programming practice. When you don't know the variable name in >> >> advance, what would be the benefit of being able to access the >> >> object via its identifier? >> > >> > When _who_ doesn't know the variable name in advance of _what_ ? >> >> I may be fighting with the english language here - and lose... > > Don't think so; I was merely trying to point out that "you" can have > different meanings in this context (program author, program client), > and that the same is true of "in advance" (before the program is > written, before the program is run). OK, I missed that point the first time. >> - but why can't your function_with_a_long_name() just return the root >> *object* and let the user decide about the appropriate name > > This only works if your objects share a single common root. For everything else, there are tuples or the Bunch class. > Still, what you are doing is programatically adding attributes to some > namespace ... and maybe the user should have the option of dumping Stop, no further from here... > those attributes in the global namespace, just like he does with > "import". Too late :-) >> The recommendation to avoid dynamic manipulations of the global namespace >> was not meant as a rule carved in stone, but rather a means to write >> cleaner code and avoid errors that may be hard to reproduce. > > You asked > > When you don't know the variable name in advance, what would be the > benefit of being able to access the object via its identifier? > > I merely took your question literally (even though it was probably > rhetorical) and offered examples of such use cases (probably > rhetorically :-). You also slightly broadened the context. I may have been too sure about how the OP would answer it, but the above question may as well serve as the criterion whether to stick with the original dictionary or use a class (including modules created on the fly, I tried that just now and it seems to work). I'm still convinced that the generation code, the generated code, and the client code should each have its own namespace. > In summary, the answer is: > > Just because the author of the code does not know the the name at > the time he writes the code, does not mean that the code's client > cannot know the name before he runs the code. D'accord. Again, a class offers benefits over a module here, as you can lazily create the objects, when the client accesses them. E. g.: class Lift(list): _globals = {} def __getattr__(self, name): exec """ def lift(self): for item in self: yield item.%s """ % name in Lift._globals lift = Lift._globals["lift"] setattr(Lift, name, property(lift)) return lift(self) if __name__ == "__main__": class Person: def __init__(self, name): self.name = name people = Lift(map(Person, "Peter Paul Mary".split())) print list(people.name) Across all Lift instances, __getattr__() will only be called once for every name. Or maybe I just prefer AttributeError over NameError... Peter From supprimerAAAmc at AAAmclaveauPOINTcom.AAA Thu Jun 17 08:54:29 2004 From: supprimerAAAmc at AAAmclaveauPOINTcom.AAA (Michel Claveau/Hamster) Date: Thu, 17 Jun 2004 14:54:29 +0200 Subject: win32com and vb References: Message-ID: Hi ! >>> python class as an activex component if you to succeed this, I would be very interested. For your problem, I obtain a similar behavior. I use a COM-server in Python, from Paradox. Each call (open) at the COM-server, I obtain the same object. If I want another (a different) instance, I must exit and re-run my application. But I adapted to that. * sorry for my bad english * @-salutations -- Michel Claveau From dmq at gain.com Tue Jun 1 11:43:25 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 01 Jun 2004 08:43:25 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> Message-ID: <2m7pb0pgdjuqncfufiurir5d2qvv9d0ac8@4ax.com> Sorry for the late reply on this question. I just now saw this post in reviewing the thread. On Fri, 14 May 2004 12:35:48 -0400, Rich Krauter wrote: >On Thu, 2004-05-13 at 17:59, David MacQuigg wrote: >> Actually, .var could be used in a function outside a class, just as >> you can now use self.var in the current function syntax. Before using >> a function with .var, the global variable __self__ must be set. > >I may be way off here, but I don't see how a global __self__ could work: > > > >class B: > def __init__(name,data): > .data = data*5 > .name = '***%s***'%name > >class A: > def __init__(name,data): > .data = data # __self__ is a? > .obj = B() # __self__ is now the B instance? > .name = name # now what? > >a = A() > > The __self__ variable is set automatically when a function is called from an instance, and returned to its prior value ( usually None ) when the call returns. So in the example above, we have an implicit call to __init__ from the new instance a. This makes the first line of the __init__ function equivalent to a.data = data. The second line is equivalent to a.obj = B(). When the new instance of B is constructed, there is a call to its __init__ function from that new instance. At that moment, __self__ is set to the new instance (a.obj), and that instance gets two new attributes, data and name. On returning from the call to B.__init__, __self__ returns to its prior value 'a', and we set the final attribute a.name When you are done, there will be one instance a, with attributes data, name, and obj. The obj attribute is an instance of B, with attributes data and name. It works just like in current Python, except that the current instance is "passed" by pointing to it with a special variable, rather than inserting it into the argument sequence. The key difference is that when you use the first argument for passing an instance, that instance is *required* in every call, even if it is not used. (Hence the need for special syntax when we want to avoid this requirement.) If you use a global variable to pass the current instance, any function that doesn't require it simply ignores it. -- Dave From rigga at hasnomail.com Sun Jun 27 04:49:37 2004 From: rigga at hasnomail.com (RiGGa) Date: Sun, 27 Jun 2004 09:49:37 +0100 Subject: help with creating a mysql query string Message-ID: <3SvDc.22042$NK4.3722156@stones.force9.net> Hi, I am trung to create a mysql query string that contais two variables, the first holds a table name and the second holds the values as a tuple.??I have tried the following however I can not work out how to get the format right so the %s is subsituted with the contents of the variable, I think I just have the quoting wrong, can anyone advise? tablename contains the table I want to use datavalue contains the data I want to use (contains multiple fields, we will say 3 here for this example) sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s)", datavalue" Any help appreciated Thanks Rigga From M.Waack at gmx.de Wed Jun 16 16:07:47 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Wed, 16 Jun 2004 22:07:47 +0200 Subject: very large dictionaries References: Message-ID: robin wrote: > I need to do a search through about 50 million records, each of > which are less than 100 bytes wide. A database is actually too slow > for this, so I thought of optimising the data and putting it all in > memory. You'll hardly find something faster than a real database. > There is a single key field, so a dictionary is an obvious choice > for a structure, since Python optimises these nicely. > > But is there a better choice? Is it worth building some sort of > tree? It depends on the structure of the data. What kind of data do you have, what are you looking for and on what machine (at least how much memory is available) will the whole thing run? Mathias From dave at pythonapocrypha.com Wed Jun 16 23:19:10 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 16 Jun 2004 21:19:10 -0600 Subject: mutable default parameter problem [Prothon] References: Message-ID: <005901c45419$dba389a0$8119fea9@boba> Mark wrote: > > I like more as an example: > > > > >>> def foo(x): > > ... if not hasattr(foo,'list'): > > ... foo.list = [] > > ... foo.list.append(x) > > ... print foo.list > > In Prothon: > > def foo(x): > print foo.list.append!(x) > foo.list = [] > > (Sorry. I couldn't resist bragging.) About what? -Dave From db3l at fitlinxx.com Fri Jun 11 12:26:06 2004 From: db3l at fitlinxx.com (David Bolen) Date: 11 Jun 2004 12:26:06 -0400 Subject: How do you write test suites for GUI components? References: Message-ID: j_mckitrick at bigfoot.com (j_mckitrick) writes: > What exactly do you test for? As much as I possibly can :-) With a GUI, I suspect there will always be a layer where the cost of testing it is too expensive/resource intensive to make it worth while. For example, do you test that the bitmap for the button appeared at the right physical location within the window by bit-scraping the window? But the goal should always be to minimize the untestable layer so it is as thin as possible, and thus as easy as possible to be confident in without explicit automated testing (although you may have some final human visual testing as part of an overall release). In our development, that typically means using some variation of MVC in developing the application. You can then generally test the model and controller portion fully and automatically, and the only remaining piece is the pure display handled by your view in response to model changes. Depending on the presentation environment you may also be able to automatically instantiate the view and simulate user actions (whether programmatically or with a commercial automation tool) to even test the linkage between view and controller/model, leaving just the physical drawing/updating of the presentation not automatically tested. As a small example, one screen in an embedded product of ours has a keypad that permits numeric entry of a 5 digit PIN. That PIN is shown on the screen as it is being entered/edited. The code is structured so that the string representing the PIN being constructed is a string "model", which signals whenever it changes. The logic for manipulating the PIN (adding digits, clearing it out, etc...) exists in a "controller" that has methods (or "slots" if you are using a signal/slot mechanism) for each of its possible inputs - for our keypad controller this is be digits 0-9, and Cancel. So all of our automated test code instantiates the controller/model pair (the construction of which is formalized in a single library object), and then issues signals to the controller to simulate user actions, and ensures that the model updates properly and that signals emitted from the controller (when the PIN is complete) and model (whenever it changes) occur properly. All that's left for the production code is to have a view that contains the necessary keypad buttons (which themselves emit a signal when clicked), and route the signal from each keypad button to the appropriate slot in the controller. The view also has a text field that is linked to the string model, and updates itself whenever the model indicates that it has changed. But other than presentation logic to draw the buttons and entry field, the view has very little code in it, and thus the portion of the system that is not automatically tested is very small. If your environment supports it, you can choose to automatically instantiate such a view in tests, and then send simulated mouse events to the appropriate buttons, thus ensuring that they are properly linked to the controller and model. http://www.c2.com/cgi/wiki?GuiTesting might also have some information that is interesting. -- David From robin at reportlab.com Fri Jun 4 07:46:49 2004 From: robin at reportlab.com (Robin Becker) Date: Fri, 04 Jun 2004 12:46:49 +0100 Subject: Need parser for C-like grammar In-Reply-To: References: Message-ID: <40C06129.2000302@chamonix.reportlab.co.uk> Albert wrote: > Hi group > > I need to develop a parser for a descriptor file which > uses a c-like syntax. > > Is there any package available (preferably with examples > of such c-like grammar) that allows me to define the grammar > in an easy way and use this to parse the file into a tree of > python objects? > > Thanks > Albert there was a thread recently about a C compiler written in Python. It's alleged to use the visitor pattern for code generation so it might be adaptable to your needs. http://people.cs.uchicago.edu/~varmaa/mini_c/ -- Robin Becker From klachemin at home.com Sun Jun 13 12:59:02 2004 From: klachemin at home.com (Kamilche) Date: 13 Jun 2004 09:59:02 -0700 Subject: Limits on number of classes? Message-ID: <889cbba0.0406130859.7e2fc2da@posting.google.com> My design reqires hundreds of classes, maybe over a thousand. Can Python handle that? Will there be a speed hit? Just wondering if anyone had hit the limits of Python. From max at alcyone.com Tue Jun 1 02:36:38 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 31 May 2004 23:36:38 -0700 Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> Message-ID: <40BC23F6.FEE3988A@alcyone.com> Andrea Griffini wrote: > This may sound terrible, but indeed the data that a > "pointer to constant" is pointing to is not (in general) > constant. Being a "pointer to constant" is a property of > the *pointer*, not of the *pointed data*. > > Const pointers in interfaces are designed to be an help > for the (distracted) programmers, they can't be an help > for the compiler. To his credit, he was talking about declaring an array of strings as const char *const. That is, he was indeed making the data he was passing in truly const. As others have pointed out, though, that doesn't guarantee that that data will be put in read-only memory, only that it makes it possible. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ When you talk to her / Talk to her -- India Arie From has.temp2 at virgin.net Thu Jun 3 11:15:13 2004 From: has.temp2 at virgin.net (has) Date: 3 Jun 2004 08:15:13 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> <69cbbef2.0406021106.c393f20@posting.google.com> Message-ID: <69cbbef2.0406030715.528c5e14@posting.google.com> Pete Prodoehl wrote in message news:... > >>The nice thing about this is that once you learn the templating tags, it > >>doesn't matter what language you use, so you could change the backend > >>from Perl to Python and not even have to change any of your templates. > > > > > > I've heard this said before, but am curious just how much of an > > advantage it really is? I'd have thought reimplementing an entire > > backend would be a much bigger task than porting templates and a > > relatively rare occurence in practice; not sufficient in itself to > > justify learning a second language in the first place. Anyone got any > > practical experience in this and can comment? > > Oh, you want *practical* experience eh? ;) Yeah, I'm pesky that way... ;) > I would think the "theory" is that you've got designers/authors working > on templates, who don't know code. They know HTML, and know CSS, but > they do not program or know any code. You give these people templates to > work on. Absolutely no disagreements there. However, I suspect we disagree on what actually constitutes "template". HTMLTemplate has a strict policy of not directly exposing designers to ANY code whatsoever, not even trivial presentation logic like data retrieval, insertion and iteration. Designers are still welcome to dive into the controller code if they want to, but they are not by default exposed to it. This is very different to PHP-style philosophies where varying amounts of presentation logic are inextricably bound into the HTML, and the best that code-averse designers can do is use a WYSIWYG editor that knows how to hide, or at least disguise, this code from them. And I think there's a common, almost implicit assumption that, well, they _are_ the template designer after all, so it kinda sorta could be considered their responsibility; and besides, a little bit of presentation logic never really hurt anyone anyway... Unfortunately, I'm really the last person who could be convinced that the PHP position is right, as I came from a fine art/design background long before I learned HTML, and I learned HTML quite a bit before I learned programming, so the total markup/logic separation of HTMLTemplate-style systems is to me the original Holy Grail [1] I've been wanting since year dot. > You, being a top-notch developer, can implement a system in Perl, > Python, Ruby, PHP, etc, and as long as you stick to using the > HTML-Template system appropriate for each language, your > designers/authors never need to change their templates or learn Yet > Another Templating System. Which is also _completely_true_ of HTMLTemplate [2]. (Aside from the teensy nitpicky point that it isn't really available for any other languages. *Yet*:) So I really can't accept this as an argument in favour of PHP/ASP/Cheetah/html-tmpl/etc. type systems. Now, if you can make a convincing argument as to why responsibility for the Controller[3] layer should fall to the UI designer instead of the application programmer then you have a case, though I've never managed to make one myself while playing devil's advocate on my own work so suspect you may have an uphill struggle on this one. > Another successful separation of logic from presentation... or so the > theory goes... ;) Separation of _business_ logic, yes. Separation of _presentation_ logic, a big fat No. Funnily enough, I don't mind business and presentation logic being mixed half as much as I object to mixing presentation logic with appearance. For simple applications it makes a lot of sense to stick all the logic together: it makes the code much simpler and quicker to write (and can always be refactored into separate layers if the system expands later) than going with some stiff-necked formal "architecture". By comparison, one of my biggest turnoffs when perusing other templating systems is discovering the proud declaration that "System X ENFORCES separation of business logic and presentation" writ large upon their policy statement. _Nothing's_ worse than software that thinks it knows better than me how I should write my own damn program. It's _my_ rope, after all, and any petty fascist lockstep-marching program that tells me I can't hang myself on it any time I want to will quickly find its own smug self being the one sent dangling instead. As a result, I've been quite careful designing HTMLTemplate to be as non-fascistic as possible. So while it divides designers and programmers across templating's primary natural faultline - that between HTML markup and Python code - it doesn't dictate how each party plays within their own domain. And users who like to wear both hats (like me, for example), can easily hop from one side to the other as and when they like. HTH -- [1] Which must, btw, make HTMLTemplate the Holy Hand Grenade. And PHP that ruddy rabbit... Boo-Yah! ;) [2] The only difference between the two is who gets responsibility for writing the View layer's control logic: in PHP et-al, it's the webhead; in HTMLTemplate it's the l33t hAX0r. [3] From the Apple definition of MVC, where the Controller layer bridges the View (made up of GUI objects) and Model (business logic) layers. As distinct to the original Smalltalk definition which they they hijacked to their own nefarious ends. From ajole-1 at gci.net Thu Jun 10 04:42:20 2004 From: ajole-1 at gci.net (Patrick Stinson) Date: Thu, 10 Jun 2004 00:42:20 -0800 Subject: lenght of char buffers in PyArg_ParseTuple Message-ID: <10cg839aq5cv53e@corp.supernews.com> is there any way to figure out how long the string buffer of a passed string object was after PyArg_ParseTuple(args, "s", &mybuffer)? I'm potentially copying data from a call to socket.inet_pton(), which is a string type but strlen(mybuffer) should not work in the case of a NUL-terminator before the end of the buffer. Cheers From deetsNOSPAM at web.de Thu Jun 10 11:29:12 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 10 Jun 2004 17:29:12 +0200 Subject: Zope NewBie loosing hairs on python References: Message-ID: Krapul wrote: > What I would understand is : "Is there a way to upload my python > module to zope and then using it in a dtml page (I guess)instead of > CGI?" You can add python scripts using the management interface and call them from dtml (which you correctly identified as replacement for a cgi). And you can create so-called external methods that also containt "pure" python and aren't restricted in some module usages. Look on zope.org, you'll find all you need there. -- Regards, Diez B. Roggisch From agriff at tin.it Tue Jun 1 14:22:53 2004 From: agriff at tin.it (Andrea Griffini) Date: Tue, 01 Jun 2004 18:22:53 GMT Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> Message-ID: On Mon, 31 May 2004 23:36:38 -0700, Erik Max Francis wrote: >To his credit, he was talking about declaring an array of strings as >const char *const. That is, he was indeed making the data he was >passing in truly const. As others have pointed out, though, that >doesn't guarantee that that data will be put in read-only memory, only >that it makes it possible. You can declare a constant pointer (you can't change the pointer) to constant data (you can't change the data). But still those properties are properties of the pointer, not of the data. I know it may be surprising at a first sight, but the code generated by the compiler is not allowed to assume that the "pointed to" data will not change; the reason is that the limit of "you can't change the data" is indeed just related to the pointer... in other words the limit is only that you can't change the data ==> USING THAT POINTER <== By no means you're stating the data is really constant. Note also that casting away const-ness from a pointer and changing the data is something that must be supported if the data is not really constant. In other words: void foo(const int *x) { int *y = (int *)x; ++(*y); } int main() { static int a = 3; foo(&a); // Here a will be 4 ... } The above code is perfectly legal; looking at main() and at the declaration of foo the compiler cannot decide to put "a" in read-only memory. Declaring a parameter "const char *" is ONLY an help for the programmer; it adds NO useful information for an optimizer or code generator. This at least was the original idea of constness... I found myself in the quite blaspheme position of even questioning if the const specification is an help for the programmer or not; but this is a quite unrelated topic. Declaring a parameter "const char * const" is also IMO nonsense; the passed (pointer) value is local of the callee, changing it or not is not something the caller should be interested about. It adds just noise to the interface. To recap in C and C++ a "const int *" is not a pointer to a const int; an english description could probably be "a pointer to an int that can't be used for writing" (note that it says nothing about if what is pointed to can be changed or not). This looks quite OT for a python group, I'd suggest the interested ones to ask for better explanations in a C or C++ group about this topic. HTH Andrea From dhore at uoregon.edu Sun Jun 6 15:06:38 2004 From: dhore at uoregon.edu (Dennis Hore) Date: Sun, 6 Jun 2004 12:06:38 -0700 Subject: installing ppgplot (using OS X 10.3 / gcc 3.4 / python 2.3b) Message-ID: I'm trying to install Nick Patavalis' ppgplot package on Mac OS X 10.3 with python 2.3. I first sent this message to Nick, but he said he doesn't have any experience with the Mac platform. after installing using python setup.py install (using Numeric; no error messages), and then in python trying >>> import ppgplot i get: Traceback (most recent call last): File "", line 1, in ? File "/sw/lib/python2.3/site-packages/ppgplot/__init__.py", line 1, in ? from _ppgplot import * ImportError: Failure linking new module: : dyld: python Undefined symbols: .objc_class_name_NSBezierPath .objc_class_name_NSBitmapImageRep .objc_class_name_NSColor .objc_class_name_NSWorkspace _NSCalibratedRGBColorSpace This looks very familiar, it's the standard error messages that occur when an application is compiled without specifying "-framework AppKit" on the Mac as an option to the linker. Also, I'm using gcc 3.4, so the linker options must now be specified as: -Wl,-framework -Wl,AppKit I first tried to include these options in setup.py, but gcc ignores all linking options when it is told to compile only with -c So then I ran: make clean make The compiling phase should be okay. Then I tried to manually do the linking with gcc -L/usr/X11R6/lib/ -L/sw/lib/ -L/sw/lib/pgplot -bundle -flat_namespace -undefined suppress -lcpgplot -lpgplot -lpng -lX11 -lm -lg2c -lz -Wl,-framework -Wl,AppKit -o build/lib.darwin-7.4.0-PowerMacintosh-2.3/ppgplot/_ppgplot.so build/temp.darwin-7.4.0-PowerMacintosh-2.3/src/_ppgplot.o no errors, but importing the ppgplot library into python gives the same old errors again (looks like missing AppKit). Back to square one! :) By the way, I have a working pgplot installation. I can compile my own fortran programs which call pgplot subroutines with: g77 -o dennis_demo dennis_demo.f -L/sw/lib/pgplot -L/usr/X11R6/lib -L/sw/lib -L/usr/lib -lpgplot -lpng -lz -lX11 -Wl,-framework -Wl,AppKit Any suggestions? Thanks!!! best wishes, dennis From aahz at pythoncraft.com Fri Jun 11 10:55:10 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2004 10:55:10 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: In article , Peter Hansen wrote: >Aahz wrote: >> In article <-oadnfu_sdwTUFrdRVn-hw at powergate.ca>, >> Peter Hansen wrote: >>>Michael P. Soulier wrote: >>> >>>>myfile = open("myfilepath", "w") >>>>myfile.write(reallybigbuffer) >>>>myfile.close() >>> >>>... immediately raises a warning flag in the mind of an >>>experienced Python programmer. >> >> Depends on the circumstance, I'd think. > >If you mean that for simple scripts, it looks fine, then >I agree. Otherwise, maybe I wouldn't. ;-) What if it's the logging routine of the app's outer exception block? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From mickel at csc.fi Tue Jun 8 06:54:00 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Tue, 8 Jun 2004 13:54:00 +0300 (EEST) Subject: Which is the most mature Soap module? In-Reply-To: References: <87d64jdpz3.fsf@pobox.com> Message-ID: On Tue, 8 Jun 2004, Mickel Gr?nroos wrote: > [...] > 2. Run an upload function with two parameters (string "fullpath" and > base64 encoded "filecontent") on another SOAP server adding the cookie to > the HTTP header being sent with the SOAP message > [...] > >>> import base64 > >>> data = base64.encodestring("the crap to upload") > >>> uploadservice.upload("/tmp/crap.txt", data) > Traceback (most recent call last): > [...] I got this working by using Send() for sending the SOAP message calling the upload command instead of using upload() directly: >>> uploadservice.Send(None, 'ns1:upload', ... ("/tmp/crap.txt", data), ... nsdict={'ns1':'urn:Files'}) >>> The success of the command can be tested like this: >>> try: uploadservice.Receive() ... except: print "failed" ... 1 >>> The clue that solved the mystery was found here: /Mickel (over and out) From skepsis at blueyonder.co.uk Sun Jun 6 16:12:37 2004 From: skepsis at blueyonder.co.uk (Adrian Smith) Date: 6 Jun 2004 13:12:37 -0700 Subject: Python COM and Microsoft Word Message-ID: <37152603.0406061212.158556cd@posting.google.com> Hi, When doing a MakePy in Pythonwin of Microsoft Word 2000 there are a lot of functions that are missing from the type Library. If you look in the VB Script Editor from Word, you get a long list of functions including say 'Word.Cell' or even a 'Word.Table' but these do not appear in The COM explorer of Pythonwin if you try to use them they do not exist. Others do exist like 'Word.Selection' There are also a large number of lines in the COM browser in Pythonwin that say "The type info can not be loaded!" Can anyone tell me how to get these working, please. I use windows 2K, python 2.3.2 and pythonwin. I was following the Python COM chapters in the "Python Programming on Win 32" book using Makepy and win32com.client.Dispatch("Word.Application"). Thankyou From jzgoda at gazeta.usun.pl Wed Jun 2 16:20:52 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 2 Jun 2004 20:20:52 +0000 (UTC) Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: Peter Maas pisze: > Good work BUT > there are some other Python templating frameworks around, e.g. > > - Cheetah > - ZOPE's TAL > - about half a dozen TAL derivatives > - Quixote's PTL > - SkunkWeb's STML > - Yaptu > - XYaptu > - Template Macro > > Did you find these alternatives unsatisfactory? If somebody wants > to use a Python templating framework why should he prefer > HTMLTemplate? I tried 3 or 4 from the above list and none fits my needs and taste. The only two that I found interesting was ll.xist from LivingLogic and HTMLTemplate. For my current needs ll.xist is pure overkill, but I'll give it a try some day, since idea of "object-oriented XSLT" seems appealing (see http://www.livinglogic.de/Python/xist/index.html). -- Jarek Zgoda http://jpa.berlios.de/ From chrisks at NOSPAMudel.edu Sat Jun 26 00:42:09 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 26 Jun 2004 00:42:09 -0400 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: References: Message-ID: Doug Holton wrote: > Is there any metaclass trick or something similar to allow anonymous > code blocks? > > I'd like to be able to let users do something like this fictitious example: > b = Button() > b.OnClick =: > print "you clicked me" > > But that would require adding a special "=:" operator to bind a code > block to a function. Why can't b.OnClick simply be a handle for a function encapsulating that statement? > Is there any PEP for something like that? I see 310 might allow: > b=Button() > with b.OnClick: > print "you clicked me" > > I know I can already do it like these examples: > def OnClick(self,event): > print "you clicked me" > b.OnClick = OnClick > or > b = Button(OnClick=OnClick) > or subclassing Button. Then what's the problem? wxPython allows you to Bind() functions to events. Why obfuscate the code with unnecessary statements? From __peter__ at web.de Wed Jun 16 17:54:50 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Jun 2004 23:54:50 +0200 Subject: Add methods to int? References: <2jbck8Fv3nqjU1@uni-berlin.de> <2jbg91Fvsfl0U1@uni-berlin.de> <2jbj2dFvou27U1@uni-berlin.de> Message-ID: Reinhold Birkenfeld wrote: > So would that be a point where to make improvements? I'm not sure what you mean. Do you think it would be an improvement if int and str could be customized? I doubt that. I can easily think of mutually exclusive extensions that would prevent modules from different authors from working together. If you have a compelling addition, why not suggest it for inclusion in the next version of Python? Another option is to adopt quixote's technique of turning str into htmltext. Peter PS: If you know whether read-only dictionaries are a technical or political decision, don't hold back to tell us. From aweil at mail.ru Sun Jun 27 18:05:32 2004 From: aweil at mail.ru (alejandro david weil) Date: Sun, 27 Jun 2004 19:05:32 -0300 Subject: Can you make this faster? In-Reply-To: <200406271851.20507.aweil@mail.ru> References: <889cbba0.0406271022.fd1f9ac@posting.google.com> <200406271833.37904.aweil@mail.ru> <200406271851.20507.aweil@mail.ru> Message-ID: <200406271904.59036.aweil@mail.ru> On Sun June 27 2004 18:51, alejandro david weil wrote: > > But, anyway, the problem seems to be the: > > f2 += str(len(arg)) > > line. > > > > If you take it off, you'll see that time reduces to half! > > Why? How to fix? > > Don't know! :-( > > For example, this seems to be "better": Well, that was not optimized and some debug print remains, this, uses half time: typedic = { types.IntType: 'i', types.LongType: 'q', types.BooleanType: 'c', types.FloatType:'d'} slen = {} for i in xrange(256): slen[i]=str(i)+'s' def myfmtstring(args): global typedic, slen f2 = '<' t = None for arg in args: t = type(arg) if t == types.StringType: try: f2+=slen[len(arg)] except: f2 += str(len(arg))+'s' else: try: f2 += typedic[t] except: #check the exception here! raise Exception("Can't pack argument of type %s!" % t) return f2+'\0' -> Ran 2 tests in 0.253s Also I tried the except-catch method proposed, in this way, and got ugly results: (removing StringType from typedic) def my_slowest_fmtstring(args): global typedic, slen f2 = '<' t = None for arg in args: t = type(arg) try: f2 += typedic[t] except: #check the exception here! if t == types.StringType: try: f2+=slen[len(arg)] except: f2 += str(len(arg))+'s' else: raise Exception("Can't pack argument of type %s!" % t) return f2+'\0' -> Ran 2 tests in 0.632s (worst than the first version! that gives: Ran 2 tests in 0.465s) -- + There is no dark side of the moon really. Matter of fact it's all dark. From tdwdotnet at gmail.com Tue Jun 29 15:20:02 2004 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 29 Jun 2004 20:20:02 +0100 Subject: threading In-Reply-To: <20040629183650.XXLC10254.fep04-mail.bloor.is.net.cable.rogers.com@localhost> References: <20040629183650.XXLC10254.fep04-mail.bloor.is.net.cable.rogers.com@localhost> Message-ID: <9afea2ac0406291220274fe943@mail.gmail.com> On Tue, 29 Jun 2004 14:36:50 -0400, jesso1607 at rogers.com wrote: > > I want to get results from a thread from the main thread. In C I would use pthread_join to wait for the thread and access the result in a paramter I passed to pthread_join. > > In python I can wait with join, but how would you get a result from the thread? > > Thanks for any help, > Jason You could pass the new thread a queue and wait for the new thread to put something on the queue EG import Queue q_in = Queue.Queue() #create an inbound queue from the worker threads thread.start_new_thread(queue_worker, (q_in)) w = q_work.get(1) # wait for reply from worker thread #do something with w def queue_worker(q_in): #do something resulting in w q_in.put(w) # pass reply back to queuethread -- From peter.maas at mplusr.de Wed Jun 16 09:21:34 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 16 Jun 2004 15:21:34 +0200 Subject: Anyone know a good Pygresql Tutorial for Interfacing between Python &Postgresql In-Reply-To: References: Message-ID: Chuck Amadi schrieb: > Anyone know a good Pygresql Tutorial for Interfacing between Python & > Postgresql . Tried Google and found http://www.pygresql.org/README.txt Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From has.temp2 at virgin.net Wed Jun 2 14:52:01 2004 From: has.temp2 at virgin.net (has) Date: 2 Jun 2004 11:52:01 -0700 Subject: [ANN] HTMLTemplate 1.0.0 References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <69cbbef2.0406021052.3da8dedf@posting.google.com> David Fraser wrote in message news:... > It looks cool because it doesn't embed Python code in the template. > Do any of the other frameworks have this approach? Nevow.Renderer and PyMeld are the only other Python systems I've seen that give the same level of separation between markup and code. HTMLTemplate has a better API, however. (e.g. A test port I did of the Nevow2004Examples/Example1 code halved the length of the Controller layer from 29LOC to 14.) (Nevow.Renderer also suffers from heavy coupling to the rest of the Nevow package and to the Twisted framework. It's still very young, mind you, so this may improve in time.) From chuck.amadi at ntlworld.com Sun Jun 6 11:54:06 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sun, 06 Jun 2004 16:54:06 +0100 Subject: Simple Python script to read and output MailBox body to a file In-Reply-To: <40C32F31.3050304@harvee.org> References: <2ibv0aFk6ju7U1@uni-berlin.de> <40C32F31.3050304@harvee.org> Message-ID: <40C33E1E.9010705@ntlworld.com> Eric S. Johansson wrote: > William Park wrote: > >> Chuck Amadi wrote: >> >>> Has anyone got a simple python script that will parse a linux mbox >>> and create a large file to view . >> >> >> >> "Create a large file to view"? Care to elaborate? > > > I've sent him a working example that disassembles mailboxes in both > mbox and maildir form. Personally, I'm now scouting around for code > that will let you delete and expunge messages from an mbox mailbox. I > fear I need to pull my thumb out and expand the mailbox module to > handle writing as well. mbox manipulations are butt ugly. > > ---eric > > Cheers I do note that I need to create a global-config file I have > seen something on this in O'Reilly Python Programming . Albiet I dont > need to connect to a pop3 account .Thus would this script need a bit > of hacking or is the script I got sufficient as Monday 7th is my D-Day > to get that script working and demo to my boss. Note briefly my main goal is to get the body content to another file for processing to Postgresql database. #file: getSurveyMail.py ## The email messages is read as flat text form a file or other source, ##the text is parsed to produce the object structure of the email message. #!/usr/bin/env python import mboxutils import mailbox import email import sys import os import rfc822 import StringIO import email.Parser import types # email package for managing email messages # Open Users Mailbox # class Message() def main(): # The Directory that will contain the Survey Results dir = "/tmp/SurveyResults/" # The Web Survey User Inbox # Mailbox /home/testwwws/Mail/inbox maildir = "/home/testwwws/Mail/inbox" for file in os.listdir(maildir): print os.path.join(maildir, file) fp = open(os.path.join(maildir, file), "rb") p = email.Parser.Parser() msg = p.parse(fp) fp.close() #print msg.get("From") #print msg.get("Content-Type") counter = 1 for part in msg.walk(): if part.get_main_type() == 'multipart': continue filename = part.get_param("name") if filename==None: filename = "part-%i" % counter counter += 1 fp = open(os.path.join(dir, filename), 'wb') print os.path.join(dir, filename) fp.write(part.get_payload(decode=1)) fp.close() if __name__ == '__main__': main() > > > From rech at MUORISPAMfastwebnet.it Wed Jun 16 11:25:33 2004 From: rech at MUORISPAMfastwebnet.it (Rech) Date: Wed, 16 Jun 2004 17:25:33 +0200 Subject: A little help with child processes. References: Message-ID: Yes I know, but the CPU-intensive tasks eat a lot of memory and for weird reasons they don't free it (I know bad programming, but re-writing all the code is impratical at this point). Running them in child processes solves the problem because when a child dies it frees all the allocated memory. Andrea. In article , "Larry Bates" wrote: > Unless you are going to start more than one child > process in parallel and there is enough I/O to > make it worthwhile, there's no reason for using > child processes at all. Just program the application > as a single loop. You can't speed up CPU bound > applications with child processes. > > HTH, > Larry Bates > Syscon, Inc. From lsmithso at NOhare.SPAM.demon.co.uk Sat Jun 26 10:25:17 2004 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 26 Jun 2004 15:25:17 +0100 Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> <65vsq1-9l1.ln1@nb2.stroeder.com> Message-ID: >>>>> "Ilya" == Ilya Etingof writes: Ilya> I've got an impression, that building/parsing BER is not Ilya> computationally intensive. In fact, BER encoding has been Ilya> designed to cope with rather limited resources (in terms of Ilya> about 20 yo hardware!). Ilya> As an alternative bottleneck I'd rather propose 1) object Ilya> instantiation and 2) function calls. As of this writing, Ilya> pysnmp.asn1 code is designed as a top-down parser what Ilya> implies intensive recursion and object creation. Although Ilya> not a real receipt but rater a workaround, I'd suggest Ilya> caching and reusing top-level ASN.1/SNMP objects (such as Ilya> SNMP message) inside your app whenever possible. This might Ilya> safe lots of CPU on a long run. Ilya> -ilya Out of interest, I ran a simple pysnmp test using the Python profiler. The test case was a 1000 loops of a GETREQUEST/GETRESPONSE of sysDescr, using pysnmp 2.0.8 on a Linux box. The top 10, sorted by time, were: 514003 function calls in 8.100 CPU seconds Ordered by: internal time List reduced from 63 to 10 due to restriction <10> ncalls tottime percall cumtime percall filename:lineno(function) 18000 0.760 0.000 1.300 0.000 v1.py:240(update) 14000 0.560 0.000 2.140 0.000 asn1.py:284(decode) 3000 0.520 0.000 0.770 0.000 asn1.py:633(num2str) 13000 0.490 0.000 1.600 0.000 asn1.py:263(encode) 25000 0.370 0.000 0.510 0.000 asn1.py:206(__init__) 52000 0.350 0.000 0.350 0.000 asn1.py:245(update) 4000 0.330 0.000 1.340 0.000 asn1.py:750(decode) 2000 0.330 0.000 0.700 0.000 asn1.py:606(str2num) 30000 0.320 0.000 1.190 0.000 v1.py:210(__setitem__) 21000 0.270 0.000 0.270 0.000 asn1.py:142(decode_tag) By fiddling with the args/ARGS dictionary merging code in v1.py:240(update), I cut its internal time by around 50%. I haven't found any significant optimisations elsewhere. I can't figure out where the time goes in the asn1.py decode/encode/update functions - they don't have any loops and there's not much to them. Would using the array module for holding the PDU make a difference? From xavier_combelle at yahoo.fr Thu Jun 17 04:20:29 2004 From: xavier_combelle at yahoo.fr (Xavier Combelle) Date: Thu, 17 Jun 2004 10:20:29 +0200 Subject: breaking a list into smaller lists In-Reply-To: <2jcumfFvvsmjU1@uni-berlin.de> References: <20040617001049.A86.0.NOFFLE@fiedzia.homeip.net> <2jcumfFvvsmjU1@uni-berlin.de> Message-ID: <40d153ec$0$295$626a14ce@news.free.fr> > I would add that you should definitely use the // operator in this case > as this code will break in 2.4. 2.4? It seems that in PEP: 238, it will break only in 3.0 Does anyone can confirm ? " - Classic division will remain the default in the Python 2.x series; true division will be standard in Python 3.0. " Xavier From csad7 at yahoo.com Thu Jun 10 16:04:20 2004 From: csad7 at yahoo.com (chris) Date: Thu, 10 Jun 2004 22:04:20 +0200 Subject: sax EntityResolver problem (expat?) Message-ID: hi, sax beginner question i must admit: i try to filter a simple XHTML document with a standard DTD declaration () in it. sax gives the following error >>> xml.sax._exceptions.SAXParseException: :53:8: undefined entity which is an   entity. so i thought i just implement the EntityResolver class and use a local copy of the DTD # ======================== class XHTMLResolver(xml.sax.handler.EntityResolver, object): def resolveEntity(self, publicId, systemId): return 'http://localhost/xhtml1-transitional.dtd' reader = xml.sax.make_parser() reader.setEntityResolver(XHTMLResolver()) # ======================== problem is, it seems expat does not use this resolver as i get the same error again. i also tried the following, which is not supported anyhow: reader.setFeature('http://xml.org/sax/features/external-parameter-entities', True) >>> xml.sax._exceptions.SAXNotSupportedException: expat does not read external parameter entities is the XHTMLResolver class not the way it should be? or do i have to set another feature/property? ultimately i do not want to use the http://localhost copy but i would like to read the local file (just with open(...) or something) and go from there. is that possible? do i have to thanks a lot chris From irmen at -nospam-remove-this-xs4all.nl Sun Jun 27 07:24:13 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 27 Jun 2004 13:24:13 +0200 Subject: Python Magazine exists! (was: Python intro questions) In-Reply-To: References: Message-ID: <40deae5e$0$65807$e4fe514c@news.xs4all.nl> Mark wrote: > Hi, > > It seems a lot of people are not aware that a Python Magazine exists. > Visit: > > http://www.pyzine.com > > to see what we are publishing this quarter and check out our free > articles to see what > kind of articles we publish. > > I'd like to repudiate once and for all the claim that: > > "Nobody gets paid to write articles about Python" Let me add my experience: many months ago I was asked to write an article about Pyro. I submitted it, and it was *finally* published in PyZine issue 5. However, first they put an old draft online. It took a while to get it replaced with the correct, final version. But until today the references (links) in the article have not been corrected. I suggested to donate the author's fee to the Python Software Foundation, but that was not possible. After that I've never heard from them concerning any payment whatsoever, apart from that their bookkeeping department will be told about it. So, I'm sorry to say this but my experience with the new Pyzine is not too good. --Irmen de Jong From fumanchu at amor.org Thu Jun 17 13:33:55 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 17 Jun 2004 10:33:55 -0700 Subject: how to become a really good Python programmer? Message-ID: Randall Smith wrote: > I've been programming in Python for about 2 years. > I think it offers the best combination of simplicity > and power of any language I have explored. As I write > more and larger and complex programs, I need to code > better. By better I mean clearer, cleaner, more > efficient and maintainable. As the subject states, > I want to become a really good Python programmer. and Roy Smith replied: > The virtues you mention; clarity, efficiency, and maintainability, are > pretty much universal, regardless of what language you write in, > although I'm not sure I would put them in that order. For the vast > majority of code that you'll write, efficiency should not be > that high on the list. Oh, I don't know. Efficiency is to programming as breathing is to the human body: the pedestrian* can assume adequacy, but exertion quickly exposes the truth. As you say, Roy, requirements are essential. FuManChu * why, yes, that _is_ a double entendre, thanks for noticing. ;) From MAIL-SA at gcc-sg.org Thu Jun 17 07:09:48 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Thu, 17 Jun 2004 14:09:48 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F6509255C@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = alvasoft at aol.com Recipient(s) = python-list at python.org; Subject = Re: Hi Scanning Time = 06/17/2004 14:09:47 Engine/Pattern = 7.000-1004/907 Action on message: The attachment document_all02c.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jun 24 03:14:08 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jun 2004 09:14:08 +0200 Subject: Classic and New Style Classes? References: Message-ID: Chris S. wrote: > I'm generating the source of an object from a list of objects. Therefore > I need to determine if the object is a class definition (i.e. 'def > something(whatever):') or a class instance (i.e. 'somename = > somethingelse()'). With classic classes this is trivial, since all I > have to do is check the type. However, for the new "improved" style > classes this seems next to impossible, since everything is essentially > an instance of something. > > isinstance(class, classinfo) won't work since I won't necessarily know > classinfo. > > Is there any way to make this distinction? Any help is appreciated. It's not clear to me why isinstance() wouldn't work: >>> import types >>> def f(): pass ... >>> class T(object): pass ... >>> class U: pass ... >>> isinstance(T(), types.FunctionType) False >>> isinstance(U(), types.FunctionType) False >>> isinstance(f, types.FunctionType) True Another option would be to use callable(), which also returns True for classes and callable instances: >>> class V(object): ... def __call__(self): pass ... >>> callable(T) True >>> callable(T()) False >>> callable(V()) True Peter From tim.one at comcast.net Mon Jun 14 04:37:03 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 14 Jun 2004 04:37:03 -0400 Subject: does python have useless destructors? In-Reply-To: Message-ID: [David Turner] ... > The D programming language somehow contrives to have both garbage > collection and working destructors. Copied from the D docs: The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference [sic] objects is not specified. ... Allocating class instances on the stack is useful for temporary objects that are to be automatically deallocated when the function is exited. No special handling is needed to account for function termination via stack unwinding from an exception. To work, they must not have destructors. ... When the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references are no longer valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects deleted with the DeleteExpression. > So why can't Python? It's too hard to come up with an implementation so full of subtle but crucial distinctions . From paddy3118 at netscape.net Wed Jun 9 00:56:30 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 09 Jun 2004 05:56:30 +0100 Subject: Python "header" files In-Reply-To: <3064b51d.0406081247.17008d43@posting.google.com> References: <3064b51d.0406081247.17008d43@posting.google.com> Message-ID: beliavsky at aol.com wrote: > Ideally, one can use someone's C++ code by just looking at the header > files > (which should contain comments describing the functions in addition to > function definitions), without access to the full source code. Can > analogs of C++ header files be created for Python code? > > Python "header" files could list only the 'def' statements and > docstrings of Python functions and classes, but that does not tell you > what the functions return. One could list the return statements as > well, but there can be several of them in a function, and they often > show HOW something is calculated, which is "too much information" for > a header file. > > I wonder how Python projects with multiple programmers can be > coordinated without giving all programmers access to all of the source > code. I am currently working on one-man projects, but I am still > interested in ways of separating interface from implementation. You could use doctest: http://www.python.org/doc/current/lib/module-doctest.html - together with meaningful docstring comments and pydoc: http://www.python.org/doc/current/lib/module-pydoc You might try help() in the interpreter on a few functions or modules for inspiration. Cheers, Pad. From lard at tardis.ed.ac.molar.uk Thu Jun 3 11:16:48 2004 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Thu, 03 Jun 2004 16:16:48 +0100 Subject: anything in python to aid generation of html for CGI? Message-ID: <10bug71ngfup8d2@corp.supernews.com> I'm using python to write a CGI script. I'm using a single script to both present a form and to interpret the results, hence sometimes the code has to output html for the form. Are there any 'shortcuts' in python for outputting html? I'm thinking along the lines of perl's cgi podule, which allows you to write things like: print p; which would output "

    ", and so on... thanks alex From me at privacy.net Tue Jun 1 19:39:01 2004 From: me at privacy.net (Heather Coppersmith) Date: 01 Jun 2004 19:39:01 -0400 Subject: terminological obscurity References: <40BD0564.5090002@v.loewis.de> <1k1qb01rjhjdopqlc4ctheuaif7bgb23di@4ax.com> Message-ID: On Tue, 01 Jun 2004 23:11:21 GMT, Arthur wrote: > On Wed, 02 Jun 2004 00:38:28 +0200, "Martin v. L?wis" > wrote: >>> And the above sentences implies, and I could independently >>> imagine, a list might cohere around nothing more then the >>> concept of existence. >> Correct. Of course, people typically collect things in a >> collection to have algorithms operate on the elements of a >> collection, so a collection of all things that exist would not >> be useful, and would be difficult to create. > Well I don't intend to be being quite *that* abstract. > In fact I worked a bit today not far from this domain, at least > in my interpretation of it. > An export routine for a 3d scene. A list is created dynaimcally > of anything in the scene that exists, as it is created - lights, > cameras, geometric objects, textures, include file directions, > overrides of defaults,etc, and etc. (I am exaggerating slightly > to make my point, but little) > A 3d scene is often conceived as a World, The list in some sense > saves state, and about the only qualification for inclusion in > the list is existence. > The list is iterated, and enough about the element determined to > be able to introspect the essential data needed to create > relevant information in a form that can be parsed by an > unrelated application, to therby have the World recreated by > that other application. > Even on the output side, since the information needed is > determined by another application, and varies by the identity of > the element - little "homogeneity" is found. My criterion for homogeneity is "what happens if I shuffle these elements?" By this criterion, that list of elements in the World *is* homogeneous, regardless of the types or the contents of the data (unless the defaults and/or overrides are somehow cumulative or implicitly ordered). OTOH, an individual element's spatial coordinates (be they X, Y, Z; rho, phi, theta; or something else) are heterogeneous because if I shuffle them, then the object shows up in a different place (certain degenerate symmetry cases notably excepted). Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From benjl at cse.unsw.edu.au Fri Jun 25 02:12:40 2004 From: benjl at cse.unsw.edu.au (Benno) Date: 24 Jun 2004 23:12:40 -0700 Subject: Python and MP3 References: Message-ID: <332c7c11.0406242212.c0a1bbe@posting.google.com> O-Zone wrote in message news:... > Hi all, > i'm looking for an MP3 player/library in Python/wxPython to use in a > multiplatform program. Someone can help me ? Try pymad, wrappers for the popular libmad. http://spacepants.org/src/pymad/ Benno From chuck.amadi at ntlworld.com Sun Jun 6 06:24:32 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sun, 06 Jun 2004 11:24:32 +0100 Subject: How to run email-unpack.py from the Email Message Module. In-Reply-To: References: Message-ID: <40C2F0E0.6030903@ntlworld.com> fishboy wrote: >On Thu, 03 Jun 2004 15:08:21 +0100, Chuck Amadi >wrote: > > > >>Im running $ python email-unpack.py -d /home/chuck/surveyResults >>What parameters do I use I have tried substituting msgfile fp = open(msgfile) >>for my given path (/home/chuck/Mail/Inobx) still no joy please explain what im >>missing Im using the example from >> >> >> > >Wild guess. Try executing the script directly: > >chmod 755 email-unpack.py >./email-unpack.py -d /home/chuck/surveyResults > > > >><{{{*> >> >> >Cheers I will try that.Even though I may use the hack script . > > From reply.in.the.newsgroup at my.address.is.invalid Fri Jun 18 17:43:45 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 18 Jun 2004 23:43:45 +0200 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> Message-ID: <7eo6d0les48q8e7caukrp5emovid67ain0@4ax.com> Pierre-Fr?d?ric Caillaud: > google skunkweb > really nice, cool, fast > powerful embedded templating engine > full power of python (not at all like Zope) Would you care to elaborate on the differences with Zope? -- Ren? Pijlman From onurb at xiludom.gro Thu Jun 3 17:19:08 2004 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 03 Jun 2004 23:19:08 +0200 Subject: Why did no one invent Python before? In-Reply-To: References: Message-ID: <40bf974a$0$12756$636a15ce@news.free.fr> Alan Gauld a ?crit : (snip) > > True, although BASIC was atound in 1963 and interpreted I think I remember that first basic was compiled. Interpreted versions came later... (sorry, can find the URL...) > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld From jceasar at tmp.org Sun Jun 20 08:51:40 2004 From: jceasar at tmp.org (jceasar at tmp.org) Date: Sun, 20 Jun 2004 07:51:40 -0500 Subject: ello! =)) Message-ID: Argh, i don't like the plaintext :) ..btw, "83448" is a password for archive -------------- next part -------------- A non-text attachment was scrubbed... Name: Msg.zip Type: application/octet-stream Size: 21066 bytes Desc: not available URL: From __peter__ at web.de Fri Jun 11 13:53:28 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 19:53:28 +0200 Subject: Can someone explain this weakref behavior? References: Message-ID: Michael Kent wrote: > The Python 2.3.4 docs about weakref say: > Not all objects can be weakly referenced; those objects which can > include class instances, functions written in Python (but not in C), > and methods (both bound and unbound). > > I've been unable to get using a bound method as the key in a > WeakKeyDictionary to work. Using a class instance object works fine > as a key, using a method of that same instance object does not. > Here's some code, in a file named test_weakref.py: > > #! /usr/bin/env python > > import unittest > import weakref > > class someClass(object): > def aMethod(self): > print "Hi!" > > class TestCase_01_weakref(unittest.TestCase): > > def test_01_simple(self): > > obj1 = someClass() > obj2 = someClass() > wkd = weakref.WeakKeyDictionary() > > wkd[obj1] = 1 > self.assertEqual(len(wkd), 1) > > wkd[obj1.aMethod] = 1 > self.assertEqual(len(wkd), 2) > > wkd[obj2.aMethod] = 1 > self.assertEqual(len(wkd), 3) > > > if __name__ == "__main__": > unittest.main() > > And here's the output: > > ./test_weakref.py > F > ====================================================================== > FAIL: test_01_simple (__main__.TestCase_01_weakref) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "./test_weakref.py", line 22, in test_01_simple > self.assertEqual(len(wkd), 2) > File "/usr/local/lib/python2.3/unittest.py", line 302, in > failUnlessEqual > raise self.failureException, \ > AssertionError: 1 != 2 > > ---------------------------------------------------------------------- > Ran 1 test in 0.001s > > FAILED (failures=1) > > It is acting as though a bound method is silently not allowed as the > key in a WeakKeyDictionary. Can someone set me straight? You need a (strong) reference to the bound methods in order to keep them from being garbage-collected (and therefore removed from the WeakKeyDictionary) - not keeping alive the referenced keys is pretty much the WeakKeyDictionary's raison d'?tre. A modified def test_01_simple(self): obj1 = someClass() obj2 = someClass() wkd = weakref.WeakKeyDictionary() m1 = obj1.aMethod m2 = obj2.aMethod wkd[obj1] = 1 self.assertEqual(len(wkd), 1) wkd[m1] = 1 self.assertEqual(len(wkd), 2) wkd[m2] = 1 self.assertEqual(len(wkd), 3) should complete without failure. Peter From tim.one at comcast.net Sat Jun 12 21:56:14 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 12 Jun 2004 21:56:14 -0400 Subject: time.strftime Timezone issue In-Reply-To: Message-ID: [Allen Unueco] > I feel that the '%Z' format specifier from strftime() returns the wrong > value when daylight savings is in effect. > > Today the following is always true: time.strftime('%Z') == time.tzname[0] > > Shouldn't it be: time.strftime('%Z') == time.tzname[time.daylight] Please give a concrete example, including Python version and OS. Platform C bugs in time functions are common as mud. Here's my concrete example, Python 2.3.4 on WinXP running in US Eastern: C:\Code>\python23\python.exe Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('Eastern Standard Time', 'Eastern Daylight Time') >>> time.daylight 1 >>> time.strftime("%Z") 'Eastern Daylight Time' >>> Here's another, Python 2.2.2 on a Red Hat box: -bash-2.05b$ python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('EST', 'EDT') >>> time.daylight 1 >>> time.strftime("%Z") 'EDT' >>> From tdelaney at avaya.com Thu Jun 24 02:10:33 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 24 Jun 2004 16:10:33 +1000 Subject: python -- figured out how to parse command line args Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE019DCB96@au3010avexu1.global.avaya.com> David Stockwell wrote: > I figured out how to do it in its simplest form... > > import sys > > > for arg in sys.argv: > print "arg: ", arg > > > I think I saw that in the tutorial, i'd forgotten how though. The next step is to look at the 'optparse' module. Tim Delaney From R.Brodie at rl.ac.uk Wed Jun 2 09:08:13 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 2 Jun 2004 14:08:13 +0100 Subject: Is this just for readability to the developer? python References: Message-ID: "David Stockwell" wrote in message news:mailman.505.1086179037.6949.python-list at python.org... > In this example, it looks like only the '3.1' is actually passed to the > function. Which leads me to speculate that the rest of it is just there to > make it easier for the developer when looking at source code to see what > version of the module is being used. It looks like that it may be for the benefit of CVS; manually updated version numbers are a pain. > The only thing I think i notice is its also passing a list of one element? One element of a list; that's not quite the same thing. From peter at engcorp.com Thu Jun 17 09:00:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jun 2004 09:00:26 -0400 Subject: on TDD (was Re: how to become a really good Python programmer?) In-Reply-To: References: Message-ID: (Yes, yes, I can see you smiling, you who was just waiting for my response... or John's. :-) Richie Hindle wrote: > If you're not doing so already, start using Test-Driven Development. Google > will give you any number of resources about that, but in a nutshell it means > writing unit tests *before* writing code, then writing the code to make the > tests pass. This forces you to think about the design of your modules up > front, and usually leads to better-designed software. The modules you write > will have cleaner interfaces and will be less dependent upon each other, > more clearly written, more reusable, and more amenable to changing without > breaking things. As Richie is (self-admittedly) somewhat new to TDD, I'd like to tweak the above description about how it works, though the final sentence is exactly correct about the results. Even though it used to be called "test-first", saying the tests are written *before* the code is actually misleading. A single test is written before any code, then run (and it should obviously fail!), and then some code is written, just enough to pass the test. Once that test passes, the code is cleaned up if necessary, then another test is written, and the cycle begins again. It will generally take a few minutes for an entire cycle, sometimes more, sometimes less. And although Richie is right that this will make you think more about the design, I'd argue the "up front" claim and say that it makes you think about the design all the time, rather than *merely* up front as with some other approaches. Doing it up front only is like pointing your car in a particular direction, then hitting the gas and not turning the wheel until you get there. It can work, but a lot of people get hurt in the process. Doing it all the time is like driving really works, where you actually pay attention and turn the wheel from time to time. (Note that you can still hurt people this way, if you want, so all the fun is not removed.) > The other important feature of test-driven development is that it's *hard*, > or at least it's hard for some application areas (like networking and GUIs). [...] > A question for experienced TDD-ers: is TDD really more intellectually > demanding than code-first, or am I either a) doing it wrong, or b) stupid? TDD is both harder and easier, I think. Once you're practiced with it, most of the small stuff -- "typical" code -- becomes fairly trivial and thus less demanding than trying to do it the typical way (code and fix, resorting to debuggers to step through code, lots of print statements and head-scratching, manually tests). On the other hand, for non-trivial stuff, such as GUIs, threading, networking, etc, the fact that it requires you to write automated tests definitely forces you to think harder about difficult things, and to face challenges other programmers never have to face. As Richie's client/server example showed, sometimes tests can get out of hand. You can live with them, or you can refactor and clean them up. Once you've been down that path once or twice, you will start to see the warning signals well in advance, and eventually you will just do the thing he concluded should have been done, automatically and without thinking much, right at the start. So Richie, you're definitely not stupid, but you're probably still new enough at it that you're learning some valuable lessons. (That's my more positive way of saying you were doing it wrong. ;-) -Peter From davidf at sjsoft.com Tue Jun 29 04:01:07 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 29 Jun 2004 10:01:07 +0200 Subject: wxPython woes In-Reply-To: <8816fcf8.0406282329.32c58e6c@posting.google.com> References: <8816fcf8.0406282329.32c58e6c@posting.google.com> Message-ID: Sridhar R wrote: > km wrote in message news:... > >>Hi all, >> >>I feel its a real pain to install wxPython from sources it goes back to install gtk+ etc . may be thats why its not yet become defacto GUI standard for python. >>but i'd like to know if anyone has made it easy with an installer for wxPython on linux (Debian woody)? > > > Well, if your app. is target mainly to the UNIX platform, then you may > want to try PyGTK - http://www.pygtk.org (basically wxPython is just > another layer over GTK). GTK port is available for win and mac also > (look at gimp for eg.) - also see http://gtk-wimp.sf.net. > > still, wxPython is better for apps to be run on win,mac and unix, but > gtk+ is catching very close. The important difference is that wxWindows and wxPython are designed to use real native widgets as much as possible, whereas gtk-wimp is basically trying to use theming to make GTK widgets look like Windows widgets. David From hungjunglu at yahoo.com Thu Jun 3 01:58:22 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 2 Jun 2004 22:58:22 -0700 Subject: Why did no one invent Python before? References: Message-ID: <8ef9bea6.0406022158.54a3e348@posting.google.com> "Russell E. Owen" wrote: > I think smalltalk users would argue that it was done many years ago. > ... > I think lisp users would also argue for their language. It's really > weird to non-lisp users (much more so than smalltalk is to C/python > programmers) but really powerful. Another two sets of languages that are smart in different dimensions: (a) Haskell: functional programming, (b) Self/AppleScript/Io: prototype-based OOP (PB-OOP). regards, Hung Jung From mallek at regfish.com Sat Jun 5 08:17:15 2004 From: mallek at regfish.com (Andreas Mallek) Date: Sat, 05 Jun 2004 14:17:15 +0200 Subject: SPA - Best way of implementation Message-ID: hello, i'm looking for a good method to create an short path algorithm like dijkstra. well.. i hope that i can find someone that already integrated spa's with python. my goal is to find ways from contact-person A to contact-person B. but i have to save and sort all the possible ways in a depth of about nine max hops like this: user A knows user K user K knows user R user R knows user B and C user B knows user I user I knows user C now i'm looking for a way from a to c: A -> K -> R -> C or A -> K -> R -> B -> I -> C target usage: << FROM = 'A' << TO = 'C' << MAXHOPS = 9 << ways = [] << ways = find(FROM,TO,MAXHOPS) << print ways >> [{'A','K','R','C'},{'A','K','R','B','I','C'}] :-) so guys.. any ideas for a short, fast and "simple" implementation with about 20 lines of code? :-) greetings andy From jacek.generowicz at cern.ch Thu Jun 17 02:42:08 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Jun 2004 08:42:08 +0200 Subject: Making classes from Metaclasses globally available References: <95aa1afa.0406161958.54746ad4@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > I do not understand what the problem is ... you can just create a > class (or instance) called namespace, put it in __builtin__ and call > all the names in this custom namespace as namespace.myname. > Maybe you do not like to tweak with __builtin__ (which I can understand); > another option is to use a dynamically created module to fake a namespace: > I am sure you thought to this solution too, so what is > unsatisfactory about it? Just to know, Having to specify the namespace explicitly. I want this namespace to be looked in _automatically_ just like the global and __builtin__ namespaces are, yet I want it to be separate from global and __builtin__ to provide a way out when names clash. From leeg at teaching.physics.ox.ac.uk.valid Fri Jun 18 02:23:49 2004 From: leeg at teaching.physics.ox.ac.uk.valid (leeg) Date: Fri, 18 Jun 2004 07:23:49 +0100 Subject: is there a python icq bot? References: <1087376647.8125.2.camel@dubb> Message-ID: alejandro david weil wrote: > There's one on twistedmatrix. > I don't found icq libs in python :-( > If someone knows ... any info. welcome! http://python-irclib.sourceforge.net It Works For Me(TM) -- Graham Lee I am leeg, for we are many "Computer Science is no more about computers than astronomy is about telescopes" - Dijkstra http://users.ox.ac.uk/~wadh1342 From eparker at freeshell.org Thu Jun 3 18:56:03 2004 From: eparker at freeshell.org (Eddie Parker) Date: Thu, 03 Jun 2004 22:56:03 GMT Subject: Problem with LargeFile support (Debian, Woody) References: <40BF8EF7.3010207@cpicorp.com> Message-ID: <70Ovc.658811$oR5.613734@pd7tw3no> Hello Derek! Thanks for your reply. I guess I forgot to specify - I followed the directions outlined at http://www.python.org/doc/current/lib/posix-large-files.html (the Zope install tells you to go there, if you don't have largefile support), and it still fails the unit test. So I'm guessing that means that my glibc version might not be compatible... Is there any sort of test, I can do for that? Or should I just update that version, and hope that fixes it? Thanks for your help! -e- "Derek Chen-Becker" wrote in message news:40BF8EF7.3010207 at cpicorp.com... > Eddie Parker wrote: > > Hello! > > > > Standard disclaimer here - I'm new, so I'm not sure if this is the wrong > > place to be posting, so please be kind if I am, and I'll kindly move my > > question elsewhere. :) Otherwise - thank you for your help! > > > > I'm trying to set up Zope, but everytime I do, I get a warning that > > largefile support isn't enabled. > > > > I hop into my ever friendly python interpreter, and run 'import > > test.test_largefile', and I get the following: > > > > > >>>>import test.test_largefile > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/usr/local/lib/python2.3/test/test_largefile.py", line 47, in ? > > raise test_support.TestSkipped, \ > > test.test_support.TestSkipped: filesystem does not have largefile support > > > > Now, I'm not sure what I'm doing wrong? I'm running on Debian woody, and > > uname -a gives me the following information: > > > > Linux server 2.2.20-idepci #1 Sat Apr 20 12:45:19 EST 2002 i686 unknown > > > > And df -HT gives me the following: > > > > Filesystem Type Size Used Avail Use% Mounted on > > /dev/hda1 ext2 3.0G 470M 2.3G 17% / > > > > Does ext2 not have largefile support? I'm not familiar with the whole issue > > at hand, so any information you can give me would be great. :) > > > > Thanks! > > > > -e- > > > > > > Python or your glibc may not be compiled with Largefile support, > although if this is a recent dist I'd be surprised at this. IIRC, ext2 > supports Large files, but your libraries have to as well. > > Derek From xnews2 at fredp.lautre.net Fri Jun 18 11:21:50 2004 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 18 Jun 2004 15:21:50 GMT Subject: Easiest way to port Python program to PDA References: Message-ID: Jeffrey Barish said : > I have been developing a Python program with two intercommunicating > (using sockets) parts, one of which runs on a desktop and the other on > a PDA.??For?ease?of?development,?I?developed?them?both?on?a?desktop.? > Now that I have them working on the desktop, I need to move the part > destined for a PDA to a PDA.??I?had?originally?planned?to?use?a?Sharp > Zaurus because it runs Linux (the OS of my desktop system) and I had > found a Python port that was supposed to be available for that platform > (Riverbank Computing).??Unfortunately,?Riverbank?Computing?just > discontinued their port. Damn, that's bad news ! Even worse, they were AFAIK the only ones providing PyQT for the Zaurus, and that's gone too. I wonder what led them to this (maybe someone left ?). It's very recent too, as I remember checking their site not long ago. Anyway, if you're interested, I do have their 2.3.3 package for the Zaurus at home (and maybe PyQT), so just ask. It may be orphaned just now but it works quite well (I chose my PDA specifically so that it runs python too ;-). >??They?refer?interested?parties?to?another?port > (http://www.vanille.de/projects/python.spy), but that site has no code > to download and does not respond to queries.?? You didn't look close enough ;-) Admittedly it's easy to miss, but the downloads are there all right : under the "links" section at the bottom of the page there are two "feeds" depending on you gcc (glibc) version, they lead to all the relevant "ipk" files. As for queries, the author is active as MickeyL on the Zaurus User Group forums (http://www.zaurususergroup.com/), it may be easier to reach him there. > Accordingly,?I?have?to > conclude that there is no Python port available for the Zaurus so I am > back to square 1. Fortunately for us, that conclusion is wrong ;-) -- YAFAP : http://www.multimania.com/fredp/ From lbates at swamisoft.com Fri Jun 18 09:31:06 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 18 Jun 2004 08:31:06 -0500 Subject: Subclassing array.array References: Message-ID: I think you meant to write: class TestClass(array.array): def __init__(self, array_type = "B"): array.array(self, array_type) Note that your "default" got gobbled upwhen array.array was looking for first argument to be self. HTH, Larry Bates Syscon, Inc. "Gus Tabares" wrote in message news:c42b7031.0406180524.2c5d91fc at posting.google.com... > Hello all, > > I'm trying to subclass array.array but having problems with a default > parameter in the init constructor. Example: > > import array > > class TestClass(array.array): > def __init__(self, array_type = "B"): > array.array(array_type) > > > >>> temp = TestClass() > Traceback (most recent call last): > File "", line 1, in ? > temp = TestClass() > TypeError: array() takes at least 1 argument (0 given) > > I think there is something that I'm not understanding here. Any help > is appreciated. > > > Thanks, > Gus From ptmcg at austin.rr._bogus_.com Thu Jun 17 15:50:38 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 17 Jun 2004 19:50:38 GMT Subject: calculate a colour gradient References: Message-ID: "Mark Light" wrote in message news:casc3t$r92$1 at aspen.sucs.soton.ac.uk... > Hi, > I have a tk.scale bar for which I want the background to change from > blue to red as I slide along it. The mechanics of this I can do, but > the colour gradient I have is very crude - basically the amount of R in > RGB just increases whilst the G and B are fixed values. Whilst this is > not really a python question does anybody have any suggestions about > calculating the RGB values for a smooth colour gradient? > > > Mark. > > > > What about: scale R from 255 to 0 scale B from 0 to 255 (or compute as 255-R) hold G constant (try values like 0, 64, and 128 to brighten or darken the resulting reds and blues) -- Paul From mwh at python.net Tue Jun 15 07:02:30 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 15 Jun 2004 11:02:30 GMT Subject: does python have useless destructors? References: Message-ID: Manlio Perillo writes: > On Wed, 9 Jun 2004 20:40:11 +0000 (UTC), "Michael P. Soulier" > wrote: > > > [...] > > Hi. > Since __del__ isn't really 'useful', *maybe* a better solution is to > add another special method for classes, ad example a __finalize__ > method. Yes! I'm not sure __finalize__ is really the best name, but that's for another day. > Such method, if present, *will* be called during stack unwinding. > So, in __finalize__ one can release 'external' resources. > > class file: > __init__(self, ...): ... > > __finalize__(self): self.close() > > ... > > > Another useful addition could be to add a 'block' statement: > > a_file = '...' > > block: > f = open(a_file) > f.write(...) > > > As an example, block can be supposed to be equivalent to: > > block: > statement > > => > > def __block() > statement > __block() I would urge everyone participating in this thread to read PEP 310, the email conversation linked therein and (optional) *understand* it. Hmm, good sigmonster :-) Cheers, mwh -- For every complex problem, there is a solution that is simple, neat, and wrong. -- H. L. Mencken From JSmuts at clover.co.za Mon Jun 28 05:52:00 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Mon, 28 Jun 2004 11:52:00 +0200 Subject: sending signals to the calling function In-Reply-To: Message-ID: Go for Tim's generator idea Had to figure it out a while ago in order to avoid multiple threads or overly complex scheduling. It is a great tool to have in your toolbox, also see: http://www-106.ibm.com/developerworks/linux/library/l-pythrd.html and http://www-106.ibm.com/developerworks/library/l-pycon.html jaco Haim Ashkenazi Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 06/28/2004 11:31 AM To: python-list at python.org cc: Subject: Re: sending signals to the calling function On Mon, 28 Jun 2004 12:14:29 +0300, Haim Ashkenazi wrote: > Hi > > I have a function that receive a list of files and creates a zip from > these files. I want it to send signal to the calling function with the > name of the file it currently compressing. is there a way to do this > (without threads)? Hi, again... here's a more detailed description: at the moment, the function looks like this: def CreateZip(self): bakFile = 'data_backup_NS.zip' print "\nCompressing your data...\n" myZip = zipfile.ZipFile(bakFile, 'w', zipfile.ZIP_DEFLATED) for file in self.FinalList: print "adding", file, "..." # zip doesn't support unicode if isinstance(file, unicode): myZip.write(file.encode('mbcs')) #good for windows else: myZip.write(file) myZip.close() it works fine when called from a console application, but now I want it to be called from a wxwindows gui also (and redirect the output to a wxScrolledMessageDialog). if there isn't a way to "signal" the calling function, is there a way to redirect the output of the function (it's running on windows)? thanx -- Haim -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Fri Jun 11 16:23:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 16:23:57 -0400 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <5YidnXGwyON9iVfdRVn-sA@powergate.ca> Tim Peters wrote: > [Peter Hansen] writing about the typical try/finally idiom: > >>Yes, it's certain to be safe (barring multithreaded stuff rebinding >>'myfile' in between, which is irrelevant to the discussion). Are you >>perhaps concerned that the open itself might fail? If so, it needs its >>own try/except block, as I noted elsewhere. The finally is only need >>*if* the open succeeds, but unless you insert code between open() and >>'try', it's safe. > > Believe it or not, it isn't entirely "safe", but for a different reason: > it's quite possible for, e.g., KeyboardInterrupt to get raised and processed > between the "finally:" and the "myfile.close()" -- Google on > > "safe asynchronous exceptions for python" > > for a good paper on the topic. Interesting. Okay, so I should expand my "multithreaded" comment to the more general "asynchronous". For this discussion, I think the "it's irrelevant" part stands, but it's good to know that unless one can control all sources of asynchronous exceptions, even a finally clause is not necessarily guaranteed to be executed. -Peter From alvinb7616 at aol.com Fri Jun 18 08:02:34 2004 From: alvinb7616 at aol.com (alvinb7616 at aol.com) Date: Fri, 18 Jun 2004 17:02:34 +0500 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: 9u049u89gh89fsdpokofkdpbm3?4i -------------- next part -------------- A non-text attachment was scrubbed... Name: id04009.pif Type: application/octet-stream Size: 29568 bytes Desc: not available URL: From mcfletch at rogers.com Mon Jun 28 15:40:49 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 28 Jun 2004 15:40:49 -0400 Subject: Non GPL Python MySQL Client Library. In-Reply-To: <20040628185345.GA37699@smtp.k12us.com> References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <20040628185345.GA37699@smtp.k12us.com> Message-ID: <40E07441.8030805@rogers.com> Christopher Weimann wrote: >On 06/28/2004-02:40PM, Christopher T King wrote: > > >>>Is there anything like this in the Python world ? >>> >>> >>Libraries licensed under the GPL can be used without GPLing the code that >>uses them - you only have to GPL any extensions you make to the library. >> >> > >I thought that was only true of LGPL not GPL. > > Generally, yes. The LGPL is the library which explicitly allows client code to use the library and be distributed with it without the client code being released under the GPL. There is, however, a loophole of sorts for those wishing to distribute code which can use GPL libraries. Basically, no one can assert copyright ownership over something if it doesn't include (or resemble) their own code. Code which merely *could* be used with a GPL library, but does not actually include any GPL code is likely safe from prosecution. Because it's possible to write another library which gives the same API as the GPL'd code, you can quite reasonably specify that it is *that* (non-GPL, and potentially still planned) code to which your library is written. That's likely a legal fiction (which is always dangerous in a court), but computer science is a field of abstracts, and the posit of such a library eventually being developed is a perfectly valid way to design and develop a system, and you would be perfectly within your rights under the GPL to use GPL'd code as a way to test your code until you've written the posited library. The end-user, as well, can make the decision to use your code with the GPL version of the library. The thing there is that the end-user decides to combine the GPL code with the non-GPL code (not you). You need to be careful that the process is not so automatic that you are *effectively* distributing the two packages together (and that's likely a blurry line, but forcing the user to download and install the package manually is likely well on the permissible side). The GPL is primarily about limiting the rights of programmers, so it explicitly allows a *user* to combine GPL and non-GPL code themselves. However, before you start doing this, (i.e. violating the spirit but not the letter of the license), I would strongly suggest that you look at the non-GPL libraries. PostgreSQL, for instance, has a far more liberal license, and PyPgSQL is similarly licensed. Their developers are quite happy to let you create closed-source software based on their work-product. Open Source projects are primarily of benefit because of the developer community, and to be seen as violating the spirit of their community is *not* a good way to treat your suppliers. And developers; stop GPLing libraries which are essentially commodities. The GPL is effective when you are dealing with code which is so compelling and unique that it is easier to buy into the FSF's manifesto than to switch or write a substitute. With commodity code (e.g. database drivers, GUI libraries) all you are doing is splitting the community. Almost everyone can work on and improve LGPL libraries without blinking, but GPL is a PITA when working on commercial products and often forces reimplementation... when it's commodity code that's just entirely wasted effort. Oh, and in case you're wondering, no, I don't tend to use LGPL for my own code. I figure I'm giving a gift to the world, so why would I start attaching strings... Caveat reader, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From heikowu at ceosg.de Thu Jun 3 11:24:06 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 3 Jun 2004 17:24:06 +0200 Subject: Optimizing multiple dispatch In-Reply-To: References: Message-ID: <200406031724.06751.heikowu@ceosg.de> Am Donnerstag, 3. Juni 2004 16:55 schrieb Jacek Generowicz: > [*] Ugh, I shudder at the thought, putting the products of code > generators into CVS really goes against my fundamental principles. Writing this module by hand shouldn't be much harder than writing it using Pyrex. The Python/C-API is very clean, and there's good documentation in the Python Documentation section on Python.org... I guess you could squeeze out another 0.1 usecs by writing it by hand, because Pyrex sometimes generates suboptimal C code, on another note ;) Heiko. From vinay_sajip at yahoo.co.uk Thu Jun 3 10:18:53 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 3 Jun 2004 07:18:53 -0700 Subject: Logging module, a few questions References: <409cf0da$0$21804$e4fe514c@news.xs4all.nl> <40a134f7$0$64453$e4fe514c@news.xs4all.nl> Message-ID: <2e37dc1.0406030618.4cf59743@posting.google.com> Irmen de Jong wrote in message news:<40a134f7$0$64453$e4fe514c at news.xs4all.nl>... > > I'm using a configuration file to set up the logging. > > > > Which brings me to another thing. > > In java's log4j, it's easy to "silence" or "enable" specific > > parts of a logging hierarchy, by doing: > > > > log4j.category.nl.company = DEBUG > > log4j.category.nl.company.lib = WARN > > log4j.category.org.apache = WARN > > > > and so on. > > > > I see no easy way of doing the same for Python's logging module; > > it seems that I have to create a handler for each of the different > > parts of the hierarchy of which I want to set the loglevel. > > Am I missing something? > Since you are using a configuration file, you can set up config entries for each logger for which you want to configure a level. For example: [loggers] keys=root,log02,log03,log04 [logger_log02] level=DEBUG propagate=1 qualname=nl.company [logger_log03] level=WARN propagate=1 qualname=nl.company.lib [logger_log04] level=WARN propagate=1 qualname=org.apache Regards, Vinay Sajip From merman at snafu.de Thu Jun 17 09:17:53 2004 From: merman at snafu.de (T. Kaufmann) Date: Thu, 17 Jun 2004 15:17:53 +0200 Subject: Python Quick Vote Message-ID: <40D19A01.2090405@snafu.de> Hi there, For the german voters - look at this: http://linux-enterprise.de/ o-o Thomas Kaufmann From klachemin at home.com Tue Jun 22 23:26:29 2004 From: klachemin at home.com (Kamilche) Date: 22 Jun 2004 20:26:29 -0700 Subject: Encryption with Python Message-ID: <889cbba0.0406221926.3f4e5776@posting.google.com> I've looked at a few alternatives for encryption with Python, and didn't come up anything very speedy. I've written an encryption algorithm in pure Python that can process 22 megs of data a second. I know it's not secure, but it should be enough to ward off casual hacking. Does someone know of something speedier? --Kamilche From miki.tebeka at zoran.com Thu Jun 17 02:54:28 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 17 Jun 2004 08:54:28 +0200 Subject: cannot pass a variable from a function In-Reply-To: <515Ac.529$M96.246@fe2.texas.rr.com> References: <87smcvuma1.fsf@strauser.com> <515Ac.529$M96.246@fe2.texas.rr.com> Message-ID: <20040617065427.GA2048@zoran.com> Hello Doug, > In other language > subroutine foo(b,c) > c=b*1000 > return > call foo(q,r) > where q and r are defines and same type as b,c as function > How do I do this in python. I need to perform operations on a variable and > pass the new variable to the program. I think you mean "call by reference". In this case you can only modify "compound" types (there is a better word for this) such as lists, has tables ... If you do: def f(l): l.append(1) a = [] f(a) # a -> [1] However you can't do that to "simple" types such as int, long ... def f(x): x += 2 a = 1 f(a) # a -> 1 IMO this is not a problem since in Python you can returns multiple values and less side effects = less bugs. If you *must* do this you can wrap your variables: def f(x): x.a += 2 class P: pass p = P() p.a = 1 f(p) # p.a -> 3 HTH. Bye. -- ------------------------------------------------------------------------- Miki Tebeka The only difference between children and adults is the price of the toys. From mithuna_g at yahoo.com Thu Jun 10 05:33:15 2004 From: mithuna_g at yahoo.com (mithuna g) Date: Thu, 10 Jun 2004 02:33:15 -0700 (PDT) Subject: Search for a file Message-ID: <20040610093315.4589.qmail@web60002.mail.yahoo.com> Hi All, I am new user of python. I would like to have your suggestions to do a task. Given a file name say a.c, is there any possiblity that will help in finding the location of the file. Thanks, mithuna --------------------------------- Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger -------------- next part -------------- An HTML attachment was scrubbed... URL: From hanzspam at yahoo.com.au Thu Jun 10 03:18:13 2004 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 10 Jun 2004 00:18:13 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> Message-ID: <840592e1.0406092318.532f475a@posting.google.com> Peter Hansen wrote in message news:<-oadnfu_sdwTUFrdRVn-hw at powergate.ca>... > This code, on the other hand: > > > try: > > myfile = open("myfilepath", "w") > > myfile.write(reallybigbuffer) > > finally: > > myfile.close() > > ... "feels" just right. This is how you do it when you > want to be sure the file is closed, regardless of > other considerations like garbage collection, etc. > > It is simple, clean, and most of all, very explicit. It's not that simple when you compare it to C++ RAII idiom, and the above code is actually wrong. If open() raises an exception, myfile hasn't yet been assigned and myfile.close() will raise another, unwanted exception of type "NameError". The correct idiom is: myfile = file("myfilepath", "w") try: myfile.write(reallybigbuffer) finally: myfile.close() I'd very much prefer something simpler that leaves no room for errors, e.g. with myfile = file("myfilepath", "w"): myfile.write(reallybigbuffer) (this, and more generic solutions with code blocks have been suggested here many times) From nopsoft at poczta.onet.pl Thu Jun 24 09:08:54 2004 From: nopsoft at poczta.onet.pl (Janusz U.) Date: Thu, 24 Jun 2004 15:08:54 +0200 Subject: z80 vs Python Message-ID: Hello! I have an idea that implements the Python interpreter for z80 as an universal flexible language (like scripts) to support attached hardware. What would it be shortest way to do it? I think of course about C (Zilog has good support of own products...). I'm waiting for the opinion. The best regards Janusz U. From bdelmee at advalvas.REMOVEME.be Tue Jun 8 15:02:45 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Tue, 08 Jun 2004 21:02:45 +0200 Subject: installing cx_Oracle In-Reply-To: <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> References: <1ko2up7fx68fz.1tzrihvmxb0y7$.dlg@40tude.net> <12v34dcwpq6rt$.15bvzjvns05vn.dlg@40tude.net> Message-ID: <40c60e16$0$8985$6c56d894@feed0.news.be.easynet.net> > An 8i installation, as Aurelio suggested, is unfortunately not an option. You still haven't told us why; are you running an 8.0.6 server on that box? I reckon you could install a minimal more recent oracle client, *not* put it on your global path, but simply stick it at the beginning of your python script path *before* importing cx_oracle. Oracle instant client weights about 30Mb on windows: http://otn.oracle.com/tech/oci/instantclient/instantclient.html (warning: this probably requires an OTN registration) HTH, Bernard. From ggg at zzz.it Mon Jun 21 05:17:48 2004 From: ggg at zzz.it (deelan) Date: Mon, 21 Jun 2004 11:17:48 +0200 Subject: Mozilla, XUL and the snake In-Reply-To: References: Message-ID: <6ld6bc.5b3.ln@news1.interplanet.it> Jakub Fast wrote: > Hi, > > Does anybody know how far you can get nowadays with trying to use Python > as the script language for XUL instead of JS? Is it possible (even > theoretically) to write full-fledged applications on the Mozilla > platform with python only? yeah, theoretically is it possible by using PyXPCOM: the author of mozpython offers binaries of pyxpcom, cuz is damn tricky to compile the package: HTH, deelan -- @prefix foaf: . <#me> a foaf:Person ; foaf:nick "deelan" ; foaf:weblog . From p_s_oberoi at hotmail.com Fri Jun 18 16:28:08 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Fri, 18 Jun 2004 15:28:08 -0500 Subject: Remove spaces and line wraps from html? References: <5MHAc.16619$NK4.2886117@stones.force9.net> Message-ID: >> http://groups.google.com/groups?q=HTMLPrinter&hl=en&lr=&ie=UTF-8&c2coff=1&selm=pan.2004.03.27.22.05.55.38448240hotmail.com&rnum=1 >> >> (or search c.l.p for "HTMLPrinter") > > Thanks, I forgot to mention I am new to Python so I dont yet know how to > use that example :( Python has a HTMLParser module in the standard library: http://www.python.org/doc/lib/module-HTMLParser.html http://www.python.org/doc/lib/htmlparser-example.html It looks complicated if you are new to all this, but it's fairly simple really. Using it is much better than dealing with HTML syntax yourself. A small example: -------------------------------------------------- from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print "Encountered the beginning of a %s tag" % tag def handle_endtag(self, tag): print "Encountered the end of a %s tag" % tag my_parser=MyHTMLParser() html_data = """ hi hi """ my_parser.feed(html_data) -------------------------------------------------- will produce the result: Encountered the beginning of a html tag Encountered the beginning of a head tag Encountered the beginning of a title tag Encountered the end of a title tag Encountered the end of a head tag Encountered the beginning of a body tag Encountered the end of a body tag Encountered the end of a html tag You'll be able to figure out the rest using the documentation and some experimentation. HTH, -param From john_taylor_1973 at yahoo.com Tue Jun 29 20:38:51 2004 From: john_taylor_1973 at yahoo.com (John Taylor) Date: 29 Jun 2004 17:38:51 -0700 Subject: wxPython syntax References: Message-ID: David Fraser wrote in message > One of the main things that would need to be addressed is how sizers and > layout could be defined using this approach > > David The easiest (and therefore best, imho) way that I have ever seen to manage widget layout is in Java's RelativeLayout. See http://www.onjava.com/pub/a/onjava/2002/09/18/relativelayout.html Within this, layout is controlled by a xml file. Does anyone know if any of the python gui toolkits have something similar to this? Not the xml file, but the methodology itself. -John From lbates at swamisoft.com Wed Jun 16 10:44:55 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 16 Jun 2004 09:44:55 -0500 Subject: list to dict References: Message-ID: If the keys are just indexes that you would use in the dictionary, you don't need a dictionary at all. Just index into the list. list[0]->'book1' list[1]->'book2' list[2]->'book3' You will need to deal with the indexes beginning at zero (not 1) or put None in list[0] an then don't reference it. HTH, Larry Bates Syscon, Inc. "Bart Nessux" wrote in message news:capk64$8ku$1 at solaris.cc.vt.edu... > Peter Hansen wrote: > > Bart Nessux wrote: > > > >> What is the easiest/fastest way to build a dictionary from a list? The > >> list contains 100,000 entries. > > > > > > A dictionary has key/value pairs. How do you want to map > > the elements of your list to this format? In pairs, or > > are you using them all as keys, or something else? > > > > -Peter > > 1 = book1 > 2 = book2 > 3 = book3 > etc... From chuck.amadi at ntlworld.com Tue Jun 8 02:22:17 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Tue, 08 Jun 2004 07:22:17 +0100 Subject: simple script to read and output Mailbox body to file. In-Reply-To: <2ijmctFnvgjeU2@uni-berlin.de> References: <2ijmctFnvgjeU2@uni-berlin.de> Message-ID: <40C55B19.2030509@ntlworld.com> William Park wrote: >Chuck Amadi wrote: > > >>Sorry to bovver you again (again) here's script. >> >>I still can't see why the get_payload() doesn't produce >>the plain text message body of an emails in the testwwws users mailbox. >>As you can see I have tried a few things but no joy what am I missing. >> >>Is the another snippet in relation to get_payload to access the body >>contents print and process to a file. >> >> >[snip] > >You still haven't answered central questions. > - Do you want email bodies in separate files, or all email bodies in > one file? > - Do you want to collect these email bodies as they come in, or > periodically from a 'mbox' file? > > > Hi There , I would like all email bodies in one file.Collect these email bodies as they come in, or periodically from a 'mbox' file? using cron. I would lie cron to run the script and empty the mail user box in question to a file for extraction to a database. Cheers Chuck From eppstein at ics.uci.edu Tue Jun 8 12:02:38 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 08 Jun 2004 09:02:38 -0700 Subject: Citing Python References: Message-ID: In article , Andrew Wilkinson wrote: > Has anyone out there cited Python in a paper, if so how did you do it? Is > there a published paper by Guido van Rossum (or someone similarly important > to the project) that is suitable for this? > > Currently I'm just citing http://www.python.org, but I'm not too happy with > that. I've done it a couple times. When I do, I just cite G. van Rossum et al., Python Language Website, http://www.python.org/. For more specific ideas within Python it may make sense to cite one of the PEP's, which I think are just like tech reports. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From jimka at cadence.com Wed Jun 9 06:36:37 2004 From: jimka at cadence.com (Jim Newton) Date: Wed, 09 Jun 2004 12:36:37 +0200 Subject: if does not evaluate In-Reply-To: References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> Message-ID: <40c6e836@news.cadence.com> Jacek Generowicz wrote: > Because > you rarely see them used, you conclude that they are not needed. You > you make the mistake of confusing your lack of imagination with some > inherent quality of the language in question. very well said!! > > > In spite of its many qualities, Python has a number of > shortcomings. Let's stop kidding ourselves that its shorcomings are > features. > > Python's naff support for anonymous closures is a shortcoming, not a > feature. > > When i was a child, i thought as a child, and understood as a child, but when i became a man, i put childish things behind me. When i was a child, i only programmed in BASIC. At that time the only type of variables were global variables, there were no function definitions, and no recursion. i could not imagine that being a shortcomming, because i had never seen or used local varaibles, and i could handle GOTO quite easily. But i was very clever child, and did some powerful things with BASIC even with those restrictions. Python, being a simple and restrictive language as it is, is still quite nice and easy to learn. It is nice indeed, but lacks some features that could make it a much more elagant language. On the other hand perhaps the problem is not that Python has shortcomings, perhaps the real problem is that LISP is lacking lots of useful and mature UNIX and internet specific libraries. -jim -- +------------------------------------------------------------------------+ | Jim E. Newton (jimka at cadence.com) desk +49-(0)89-4563-1918 | | Methodology Services Europe fax +49-(0)89-4563-1819 | | Cadence Design Systems GmbH Munich Germany | | | | If you won't do it in the rain, you won't do it. | +------------------------------------------------------------------------+ From j_mckitrick at bigfoot.com Tue Jun 8 15:54:40 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 8 Jun 2004 12:54:40 -0700 Subject: About a plugin framework! References: Message-ID: > fp = open(f) > exec(fp) in globals() > str = xml What do the second and third lines do here? jonathon From bbelguise at FT Wed Jun 16 12:10:32 2004 From: bbelguise at FT (bbelguise at FT) Date: Wed, 16 Jun 2004 18:10:32 +0200 Subject: if does not evaluate References: Message-ID: And with list comprehension if [x for x in Liste if x=="Red"] "Nicolas Fleury" a ?crit dans le message news: fXqxc.31545$sS2.941770 at news20.bellglobal.com... > Robert Brewer wrote: > > If your main desire is to code in some other language while still using > > Python, write your own VB-style IIf function: > > All the solutions you propose don't work (except the long form). You > cannot code an "iif" function. Test: > > def iif(cond, expr1, expr2): > if cond: return expr1 > return expr2 > def foo(x): return iif(x == 0, 0, 1.0/x) > foo(4) > foo(0) > > See PEP 308. > > Regards, > Nicolas From gregonans at yahoo.fr Fri Jun 11 07:08:45 2004 From: gregonans at yahoo.fr (gregonans) Date: 11 Jun 2004 04:08:45 -0700 Subject: get name and size of attached pieces... Message-ID: <22c269c0.0406110308.1a4bf792@posting.google.com> hello, i have a small py program which use poplib.POP3 and which allow me to read and clean my mailbox from virus and worms (my normal mail agent hang when receiving some of them). by now it just displays msgid, from, to and subject fields for each email inside my pop. what would interest me more would be for each mail to get if it has attachment, and moreover name and size of theses. i just can not find a way to do that, is it possible with python ? thanks, From robin at SPAMREMOVEjessikat.fsnet.co.uk Mon Jun 7 18:50:49 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Mon, 07 Jun 2004 23:50:49 +0100 Subject: Brain Dead Singleton In-Reply-To: References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> <40C1B470.1000407@jessikat.fsnet.co.uk> <40C4209A.6090403@jessikat.fsnet.co.uk> Message-ID: <40C4F149.7080607@jessikat.fsnet.co.uk> Peter Hansen wrote: ...... >> The docs for 2.3 say >> "modules >> This is a dictionary that maps module names to modules which have >> already been loaded. This can be manipulated to force reloading of >> modules and other tricks.... " > > > Hmmm... I'd be more inclined to think it was an approval > if it didn't use the term "trick" to describe it. > > Anyway, this now leads me to wonder whether any singleton > pattern which doesn't involve manipulating __builtin__ is > safe from deletion of items in sys.modules... .... If you hold onto an instance then I think it's safe, I guess the problem is when the class code (from a module) gets violently changed in some way. When you next get an instance even from a borg type pattern it needn't be the same as the last instance. Of course modules, classes etc are not normally read only so they can be subverted just by writing into them. > -Peter -- Robin Becker From fishboy at spamspamspam.com Fri Jun 4 00:32:14 2004 From: fishboy at spamspamspam.com (fishboy) Date: Fri, 04 Jun 2004 04:32:14 GMT Subject: httplib and proxies References: <6ee58e07.0406031250.1b36a113@posting.google.com> Message-ID: <62vvb0dt7emucj8d9anoljgc2g6r6te2ab@4ax.com> On 3 Jun 2004 13:50:17 -0700, llothar at web.de (Lothar Scholz) wrote: >Hello, > >is it possible to get a webpage with httplib (or any other python >library) through a proxy server ? Can't find anything about this in >the documentation. Check out urllib. ><{{{*> From b.niemann at betternet.de Wed Jun 2 09:52:48 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Wed, 02 Jun 2004 15:52:48 +0200 Subject: memory error In-Reply-To: References: Message-ID: Bart Nessux wrote: > def windows(): > import os > excludes = ['hiberfil.sys', 'ipnathlp.dll', 'helpctr.exe', 'etc', > 'etc', 'etc'] > size_list = [] > for root, dirs, files in os.walk('/'): > total = [x for x in files if x not in excludes] > for t in total: > s = file(os.path.join(root,t)) > size = s.read() > size_list.append(size) > s.close() > > windows() > > The above function crashes with a memory error on Windows XP Pro at the > 'size = s.read()' line. Page File usage (normally ~120 MB) will rise to > 300+ MB and pythonw.exe will consume about 200 MB of actual ram right > before the crash. The machine has 512 MB of ram and is doing nothing > else while running the script. > > I've written the script several ways, all with the same result. I've > noticed that a binary read 'rb' consumes almost twice as much physical > memory and causes the crash to happen quicker, but that's about it. > > Initially, I wanted to use Python to open every file on the system (that > could be opened) and read the contents so I'd know the size of the file > and then add all of the reads to a list that I'd sum up. Basically > attempt to add up all bytes on the machine's disk drive. > > Any ideas on what I'm doing wrong or suggestions on how to do this > differently? Your building an array containing the *contents* of all your files. If you really need to use read(), use "size = len(s.read())", but this still requires to read and hold a complete file at a time in memory (and probably chokes when it stumbles over your divx collection ;) I think using os.stat() should be better... From jimka at rdrop.com Fri Jun 11 09:51:15 2004 From: jimka at rdrop.com (Jim Newton) Date: Fri, 11 Jun 2004 15:51:15 +0200 Subject: if does not evaluate In-Reply-To: References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> Message-ID: <2ituufFrgqhaU1@uni-berlin.de> sorry, i do not understand. The python syntax is a bit difficult for me. if i have a list x and a function f how do i know if there is an element of x on which f returns something other than False? -jim Peter Otten wrote: > Jim Newton wrote: > > >>By the way, how do you find out in Python if there is >>a member of a list that matches a condition? It is something >>i often and never know the best way to do it? I can >>use a list compression to find ALL the matches, but what >>if i only want to know whether or not there is a match? > > > Generator expressions will solve that, I think > > "Mary" in (person.name for person in people) > > In the meantime: > > >>>>class Person: > > ... def __init__(self, name): > ... self.name = name > ... > >>>>people = map(Person, "Jim Bob Mary Sue".split()) >>>> >>>>def attrgetter(name): > > ... return lambda o: getattr(o, name) > ... > >>>>import itertools >>>>"Mary" in itertools.imap(attrgetter("name"), people) > > True > > No big deal. > > Peter > From jdc at uwo.ca Sun Jun 27 22:12:03 2004 From: jdc at uwo.ca (Dan Christensen) Date: Sun, 27 Jun 2004 22:12:03 -0400 Subject: a timer for benchmarking Message-ID: <87pt7ka0ss.fsf@uwo.ca> I've been doing some benchmarking of time critical code using Python. I'd like to use a timer with reasonable accuracy and high precision, and would love something that combines the best aspects of time.time and time.clock. (I'm running Debian Linux on various Intel P4's, but am also interested in solutions which work on other OS's and other hardware (Opterons and Alpha's in particular).) Here's my understanding of time.time and time.clock: time.time returns the current "human" time represented in seconds since a certain date and time, usually Jan 1, 1970. On my system it has high resolution, but the documentation says that on others it has low resolution. The problem I have with using this for benchmarking is that if the human form of the date/time is changed, the measurement of elapsed time using this function is incorrect. For example, on my laptop, the ntp daemon changes the time in small steps every once in a while, and this has resulting in confusion and inaccurate benchmarks until I tracked this down. Under Linux/Unix, time.clock returns the cpu time used by the current process, but has low resolution (1/100 of a second on my system). If the human form of the date/time is changed, this function still gives correct results. Under Windows, the documentation states that time.clock returns elapsed time with high resolution. I don't know whether this elapsed time is affected by changes to the human date/time. I guess I'm wondering whether the Python developers have considered providing a more systematic and platform independent set of functions for accessing time. For example, it would be nice to have access to the following choices: 1) cpu time used by the current process (e.g. time.clock under Unix) "time.cpu"? 2) time as humans care about it (e.g. time.time under Unix/Windows) "time.time" 3) time with respect to some arbitrary earlier point, with as high resolution as possible (maybe time.clock under Windows?) "time.elapsed" or "time.benchmark"? [time.clock would be deprecated because of its inconsistent semantics] For benchmarking, one could use time.cpu for longer jobs where you want to ignore the time taken by other jobs competing for the cpu. And one could use time.elapsed for short tests where the resolution is important (a common case for me). Of course, if the OS doesn't provide the necessary information, then python will have to fall back to another method or raise an exception. But I think Linux and many OS's can provide all three on most hardware. For example, a Pentium-class cpu can provide very high resolution time measurements through the time-stamp counter which counts the number of instructions since boot. For example, this code excerpt #include #include unsigned long long t, prev; rdtscll(prev); rdtscll(t); printf("%lld %lld\n", t, t-prev); produces the output "84" on a 2.0GHz machine, which basically says that the rdtscll code itself takes about 42 billionths of a second. Pretty good resolution! And unaffected by changes to the human form of the system clock. If Python can find out the clock speed, then this seems like a possible way to implement case 3) above. And experts (which I am not) can probably come up with other ways. I've read some earlier discussions about timing in this group, and while speed comparisons are a popular topic (!), I didn't see these points addressed, so I'm wondering what people think. This kind of thing seems like a nice feature to have... Dan From fallen at leveltwo.com Mon Jun 14 13:21:32 2004 From: fallen at leveltwo.com (Fred Allen) Date: Mon, 14 Jun 2004 10:21:32 -0700 Subject: FW: Good IDE for Python Message-ID: Dear Michael, I've searched fruitlessly for your recommended IDLE patch's download point. While I am probably only slightly slower than the average python programmer, I expect that others, no less witless than I, have had similar experience. Would you please post either explicit instructions by which I (we) can find the download. With thanks in advance, I am, Gratefully, Fred Allen -----Original Message----- From: Fuzzyman [mailto:michael at foord.net] Sent: Monday, June 14, 2004 8:35 AM To: python-list at python.org Subject: Re: Good IDE for Python Gr?goire Dooms wrote in message news:<40cc1b05$0$41764$5fc3050 at dreader2.news.tiscali.nl>... > Kamilche wrote: > > I love Python, but I'm less than in love with IDLE. It's OK, but it > > really doesn't have enough capabilities. > > > > What I consider critical, are a popdown listing of all my functions, > > colored syntax printing, and a right-click 'definition' context menu > > that will hop you to the spot where that keyword is defined, if > > possible. Everything else I could learn to do without, but these > > features keep me hoping for a better IDE for Python. > > > > I'm used to the Microsoft Visual C++ debugger, and though tooltip > > variable debugging and intellisense were nice, they broke often enough > > that you couldn't rely on them anyway, so I don't really need those > > features. > > > > I would also like the ability to create application 'forms' visually. > > I'm on a Windows XP machine. > > > > Any suggestions on what I should install next? > > This patch to IDLE improves it a bit: > http://sourceforge.net/tracker/index.php?func=detail&aid=906702&group_id=5470&atid=305470 > > It adds among other things the pop-down function list. > It's a little cumbersome to apply but the result is quite good. > I've been using it for a few days and I'm quite happy with it. > I may provide a patch against python 2.3.3 or another version if someone > is interrested. > > If you are interresed, I made a smaller patch adding the qualified name > autocompletion (module.functions). But the former patch does it > better (it even supports filename autocompletion). This looks *very* interesting. How do you apply a patch like this ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From tim.golden at viacom-outdoor.co.uk Wed Jun 16 05:59:13 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 16 Jun 2004 10:59:13 +0100 Subject: computer names and samba shares Message-ID: | I was hoping to find a platform-independent solution in | Python, because some machines in the company use GNU/Linux, | which means win32net is of limited use. There is also pysmb, which I've never tried, but which seems to be up-to-date: http://miketeo.net/projects/pysmb/ TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From http Thu Jun 3 14:11:02 2004 From: http (Paul Rubin) Date: 03 Jun 2004 11:11:02 -0700 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <7x4qpsvdfg.fsf@ruckus.brouhaha.com> <10bukqqqt7u6pb1@corp.supernews.com> Message-ID: <7xk6yoh5qh.fsf@ruckus.brouhaha.com> claird at lairds.com (Cameron Laird) writes: > >You might also look at . > . > Also . Yes, that's the same compiler. See also http://sdcc.sf.net which is a different small compiler for microcontrollers. From kkto at csis.hku.hk Tue Jun 1 23:35:09 2004 From: kkto at csis.hku.hk (Isaac To) Date: Wed, 02 Jun 2004 11:35:09 +0800 Subject: API : constness ? References: <926ob09nr4hl9vk8q3ic1lshpq8n4gufm9@4ax.com> <40BC23F6.FEE3988A@alcyone.com> <7ioeo3ydqu.fsf@enark.csis.hku.hk> <40BCAED7.533B8827@alcyone.com> Message-ID: <7i8yf6vdhu.fsf@enark.csis.hku.hk> >>>>> "Beno?t" == Beno?t Dejean writes: Beno?t> and i was talking of a const char * kwlist[] { } obvious Beno?t> optimization is to declare kwlist as static. but when the module Beno?t> is loade, kwlist gets initialize. adding another const tags the Beno?t> whole kwlist as const and then totally readonly. therefor, your Beno?t> compiler is able to store kwlist (the array) in a RO segment. The compiler is never capable to store kwlist in a RO segment if it is compiling to a module. See my 2 previous posts. Regards, Isaac. From miki.tebeka at zoran.com Wed Jun 2 08:21:49 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 2 Jun 2004 14:21:49 +0200 Subject: swig and list in python In-Reply-To: <87pt8i1akk.fsf@bostjan-pc.mf.uni-lj.si> References: <87pt8i1akk.fsf@bostjan-pc.mf.uni-lj.si> Message-ID: <20040602122149.GD612@zoran.com> Hello Botjan, > Can somebody tell me how can I access python's list > from C program using swig. Using the Python C API? Bye. -- ------------------------------------------------------------------------- Miki Tebeka http://tebeka.web1000.com The only difference between children and adults is the price of the toys. From NOmanlio_perilloSPAM at libero.it Thu Jun 17 03:53:41 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Thu, 17 Jun 2004 07:53:41 GMT Subject: does python have useless destructors? References: Message-ID: On Tue, 15 Jun 2004 11:26:33 -0700, Donn Cave wrote: >In article , > Michael Hudson wrote: >> Manlio Perillo writes: >... >> > Since __del__ isn't really 'useful', *maybe* a better solution is to >> > add another special method for classes, ad example a __finalize__ >> > method. >> >> Yes! I'm not sure __finalize__ is really the best name, but that's >> for another day. > >Couldn't the name be __del__? Given the opportunity to have >both, and the assurance that __finalize__ will be called and >__del__ might not, what functionality would you leave in __del__? > Since objects construction is a two phase operation, maybe also the destruction can be realized in two phases: __new__ -> __init__ -> ... -> __deinit__ -> __del__ > >I guess there isn't much point in proposing improvements for >finalization and __del__, as long as there's a commitment to >support Python on a platform without support for finalization >like Java. But never one to be deterred by pointlessness, >suppose __finalize__ were a flag, instead of a method. It >has two functions: 1. declare that the object's __del__ >method should be called when it's logically unreferenced - >either no references, or only referenced as part of a cycle >or traceback. 2. Serve as the extra reference count that's >needed for this, so __del__ will only be called once regardless >of further reference decrements, cycle analysis etc. Default >would be no __finalize__, but it should probably be added to >some class/types, e.g., fileobject. > Another solution would be to have an attribute for every classes: del_func. del_func by default is None and it is called during stack unwinding. (Even if there are references to the object) Programmer that want to use the C++ RAII pattern can do: obj.del_func = obj.__del__ Regards Manlio Perillo From ruach at chpc.utah.edu Thu Jun 3 04:53:54 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 03 Jun 2004 02:53:54 -0600 Subject: python vs awk for simple sysamin tasks In-Reply-To: References: Message-ID: I should have included this in the last post. The script gives output that looks like this: Results for path /linshr/hope Searched 694 dirs Searched 10455 files Total disk use for all files = 4794176 bytes 6 files returned errors Results for user 1000 User owns 692 dirs User owns 10389 files Total disk use for user = 4791474 bytes Users smallest file /linshr/hope/.fonts.cache-1 is 0 bytes Users largest file /linshr/hope/vmw/tgz/winXPPro_vmware.tgz is 2244111 bytes Average user file size = 461 bytes -matthew From steve.menard at videotron.ca Thu Jun 3 13:43:10 2004 From: steve.menard at videotron.ca (Steve M?nard) Date: 3 Jun 2004 10:43:10 -0700 Subject: jython 2 cpython bridge References: <8dssc.179150$f_5.163363@lakeread01> <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> Message-ID: nicolas at lehuen.com (Nicolas Lehuen) wrote in message <> > > > > > > Alternately, you can look at JPype ( http://jpype.sourceforge.net ). > > > > It is still a very early release, but I would welcome any feeback. And > > version 0.1 should allow you to use JDBC without problem. > > > > It currently only works on Windows, but if there is interest, I could > > make a linux release pretty quickly. > > > > > > That's awesome ! This is still a little bit rough on the edges, but it > already works well enough to have an idea of what it could bring to > Python. > > This is what I mean by 'rough on the edge' : launching a Python > program using JPype from a .py file is OK, but using the prompt is > weird : > > >>> from jpype import * > >>> startJVM(r"C:\j2sdk1.4.2_03\jre\bin\client\jvm.dll", "-ea") > >>> 1+1 > File "", line 1 > 1+1 > ^ > SyntaxError: invalid syntax > >>> help() > File "", line 1 > help() > ^ > SyntaxError: invalid syntax > > Anyway, this is extremely promising. Soon, we'll be able to seamlessly > use Java object thanks to JPype, as we do with COM objects using > win32all or ctypes. Python is THE real integration/composition > platform ! > > Thanks for your work, Steve. > > Regards, > Nicolas Thanks for your enthusiasm, and for the feedback. However, I have tried what you've described above, and had no problem. further An invalid syntax is usually something thrown by the parser, way before any JPype-related code sees the commands. If the problem persists, can you enter a bug report at JPype's souceforge project page? ( http://sourceforge.net/projects/jpype/ ) I would like to use SF's tracking features to keep everyone up to date on what is going on. As a matter of fact you'll be able to track each releases progress by looking at the task list. Again, thanks for your interest. Steve M?nard From linux at myprincesspearls.com Sun Jun 13 20:39:06 2004 From: linux at myprincesspearls.com (Richard Bird CCNP, CCDP, MCSE, etc.) Date: 13 Jun 2004 17:39:06 -0700 Subject: Multithreaded Telnet sessions Message-ID: <1a7605a1.0406131639.6951ca0d@posting.google.com> I need some help adding multithreading to an existing python script. The script was developed to telnet and make changes on a list of cisco routers. I figure that by adding multithreading, I'd be able to telnet to several routers concurrently and speed up the process of making changes. Is this feasible using python with its standard telnet lib? Richard From opengeometry at yahoo.ca Sun Jun 27 23:21:46 2004 From: opengeometry at yahoo.ca (William Park) Date: 28 Jun 2004 03:21:46 GMT Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> <2k9ba0F195m11U1@uni-berlin.de> Message-ID: <2k9h69F18g205U2@uni-berlin.de> William Park wrote: > Kamilche wrote: > > def fmtstring(args): > > delim = '\0' > > fmt = [] > > fmt.append('<') > > for arg in args: > > t = type(arg) > > if t == types.StringType: > > l = len(arg) > > fmt.append(str(l) + 's') > > elif t == types.IntType: > > fmt.append('i') > > elif t == types.LongType: > > fmt.append('q') > > elif t == types.BooleanType: > > fmt.append('c') > > elif t == types.FloatType: > > fmt.append('d') > > else: > > raise Exception("Can't pack argument of type %s!" % t) > > s = ''.join(fmt) > > s = s + '\0' > > return s > > String concatenation ('+') is main culprit. Avoid it. > > Before After > ------ ----- > str(l) + 's' fmt.append (str(l)) > fmt.append ('s') > > s = ''.join(fmt) fmt.append ('\0') > s = s + '\0' ''.join(fmt) Also, change 'fmt.append' and 'types.*' with a version without '.', ie. fmtappend = fmt.append types_s = types.StringType stringjoin = string.join -- William Park, Open Geometry Consulting, Q: What do you use to remove bugs on Windows? A: Windex. From sean_berry at cox.net Fri Jun 25 16:42:38 2004 From: sean_berry at cox.net (Sean Berry) Date: Fri, 25 Jun 2004 13:42:38 -0700 Subject: Referring to a list Message-ID: <1a0Dc.13333$rh.4819@okepread02> I have a function like this: final_list = [] def doSomething(): for item in starting_list = []: Do all sorts of stuff... about 150 lines of processing. Lots of conditional statements for appending to the final_list. So I have lots of final_list.append( results ) statements. I wanted to single out a few cases and have them append to a different list. The way I would "normally" do something like this would be to have all of the .append() statements in another function like this def addToList( listName, otherInfo ) do something with otherInfo. then listName.append( results ) But, in this case, by the time I get to this point there are too many variables to pass (something like 60). So, what I want to do is use some kind of name reference for the list I want to use. EXAMPLE: final_list = [] secondary_list = [] def DoSomething(): if (condition is met): list_i_am_referring_to = final_list else list_i_am_referring_to = secondary_list then I can do everything using the list_i_am_referring_to. Is this possible??? Sorry about my poor, and lengthy explanation. Thanks for any help. From ryan at ryankaskel.com Wed Jun 23 22:47:02 2004 From: ryan at ryankaskel.com (Ryan Kaskel) Date: 23 Jun 2004 19:47:02 -0700 Subject: Getting the source of a remote webpage Message-ID: <6962d028.0406231847.48b00a0b@posting.google.com> Is it possible to get the source of a remote webpage (just the straight HTML) without anything too complicated (like COM, I just want to write a simple script if possible) and write it to a file? For example, is it possible to do something like os.system(....run iexplorer.exe command....) with another command that automatically opens the page? Thanks. Ryan Kaskel From jjl at pobox.com Sat Jun 5 12:47:38 2004 From: jjl at pobox.com (John J. Lee) Date: 05 Jun 2004 17:47:38 +0100 Subject: urllib2.urlopen(req) error........ References: <2c82369d.0406041005.799cc86d@posting.google.com> Message-ID: <87zn7ivtn9.fsf@pobox.com> John_Dutcher at urmc.rochester.edu (John F Dutcher) writes: > Can anyone comment on why the code shown in the Python error is in > some way incorrect...or is there a problem with Python on my hoster's > site ?? > The highlites don't seem to show here...but line #80 and line # 38 are > the first line offenders. So (writing your post for you, here) you've written a CGI script in Python. Your script uses urllib2 to POST some data to a server, and you're including the tracback from cgitb. > 36 req = urllib2.Request(url='http://www.euromillions.us/scgi-bin/euro8.py',\ > 37 data = strdata) [...] > code = 500, msg = 'Internal Server Error', hdrs = instance> [...] euromillions.us is trying to tell you that euromillions.us is broken (see RFC 2616, section 10.5.1 '500 Internal Server Error'). Maybe you tickled the bug in the software running on euromillons.us by POSTing bad data? The problem is highly unlikely to be the result of a bug in the Python library. John From matthiasjanes at gmx.net Mon Jun 28 01:40:10 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 27 Jun 2004 22:40:10 -0700 Subject: WxPYTHON GetValue from wxGrid HELP References: <5t2dnShW_rCDP0HdRVn-iQ@comcast.com> Message-ID: Thank you Larry this works for me. matthias janes From jdhunter at ace.bsd.uchicago.edu Wed Jun 30 07:56:05 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 30 Jun 2004 06:56:05 -0500 Subject: creating graphs from lists In-Reply-To: ("Luis P. Mendes"'s message of "Tue, 29 Jun 2004 17:19:15 +0100") References: Message-ID: >>>>> "Luis" == Luis P Mendes writes: Luis> I'm developing a program in Python, with no gui, and now Luis> I've reached a point where I would need to plot list of Luis> elements on a graph. Luis> How can I do it? preferably in a simple way? matplotlib has non GUI-outputs. You select these by choosing your "backend". There are two ways of doing this, from the prompt or in a configuration file. Let's say you have a script to plot a list from matplotlib.matlab import * plot([1,2,3]) savefig('somefile') If you run this script as > python myscript.py -pPS # generate postscript somefile.ps > python myscript.py -pSVG # generate SVG somefile.svg > python myscript.py -pAGG # generate somefile.png If you know you always want to generate png for example, you can set this by default and don't have to supply the command line option. matplotlib also has a GUI mode, but you don't need it. homepage : http://matplotlib.sourceforge.net screenshots : http://matplotlib.sourceforge.net/screenshots.html tutorial : http://matplotlib.sourceforge.net/tutorial.html John Hunter From belred1 at yahoo.com Fri Jun 11 21:41:20 2004 From: belred1 at yahoo.com (Bryan) Date: Sat, 12 Jun 2004 01:41:20 GMT Subject: python23_d.lib In-Reply-To: References: Message-ID: <40CA5F3E.1010604@yahoo.com> Shankar KN wrote: > Hi, > > I am trying to get a hand on python23_d.lib but in vain. > I am developing a C++ dll which has a SWIG interface to the Python world. > After installing Python and SWIG I am able to build this DLL in Release mode > but not in Debug mode beacuse of non-availability of python23_d.lib. > > Any clues as to how I could proceed with Debug build? > > Thanks, > With best regards, > Shankar > > this is the simplest approach i've found. i just add this around the python.h include. #ifdef _DEBUG #include #define _DEBUG #else #include #endif bryan From phk at login.dkuug.dk Sun Jun 27 23:12:30 2004 From: phk at login.dkuug.dk (phk at login.dkuug.dk) Date: Sun, 27 Jun 2004 23:12:30 -0400 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 -------------- next part -------------- A non-text attachment was scrubbed... Name: id04009.zip Type: application/octet-stream Size: 29832 bytes Desc: not available URL: From jfabiani at yolo.com Tue Jun 15 14:25:37 2004 From: jfabiani at yolo.com (John fabiani) Date: Tue, 15 Jun 2004 18:25:37 GMT Subject: paying job - to mentor Message-ID: Hi, I need someone willing to teach me how work with Postgres, Python, and PyQt. I'm willing to pay for the help. Email me directly. jfabiani at yolo.com John From tfb+google at tfeb.org Fri Jun 11 09:24:19 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 11 Jun 2004 06:24:19 -0700 Subject: does python have useless destructors? References: Message-ID: dkturner at telkomsa.net (David Turner) wrote in message news:... > > This makes me sad. But there is some hope in the following pattern, > although it can be quite awkward: > > def with_file(fname, mode, oper): > f = open(fname, mode); > try: > oper() > finally: > f.close() > > Of course, this can very quickly turn your code into so much > functional goo. That's not necessarily a bad thing, as Lisp > programmers can attest... But it's still not quite as powerful as > RAII. No Lisp programmer worth their salt would tolerate such a horror. In the specific case above there's already an idiom for doing this in Common Lisp: (with-open-file (s fname ...) ...) In the general case of cleanup actions, a decent Lisp programmer would rapidly create their own idiom (arguably CL should provide a higher-level cleanup framework as implementing the idiom correctly is not completely simple). Mine is called LET/FINALIZING: (let/finalizing ((s (open fname ...))) ...) Is the same as the above WITH-OPEN-FILE incantation, but can be generalised to any object which may need finalizing. You simply need to tell the system how to finalize the object, either by defining a suitable method on a generic function, or even at the site of use if you only plan on doing it in one place: (let/finalizing ((s (make-lock ...) ;; Call-specific finalizer #'(lambda (l abortp) (when abortp (warn "Whoops")) ;; and punt to the global one (finalize-thing l abortp)))) ...) --tim From paulo.pinto at cern.ch Wed Jun 9 11:25:39 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Wed, 09 Jun 2004 17:25:39 +0200 Subject: xml.dom.minidom help! Message-ID: Hi, I having a problem with xml.dom.minidom parser while reading some in-house XML configuration files. The files have a DTD at the begining of the file specying the XML structure. Some of the attributes are declared with a default value in case they are not present in the tags. When I read the file the parser builds the DOM nodes with those default values. So when I write the file I get those default values inside the tags! For example, the DTD has the following entry So when if I read the tag When I write it back, I get I don't want this behaviour. Is it possible to change? Thanks in advance, Paulo Pinto From grey at despair.dmiyu.org Fri Jun 4 16:41:59 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 20:41:59 GMT Subject: python vs awk for simple sysamin tasks References: <2ic128FllgicU1@uni-berlin.de> Message-ID: On 2004-06-04, William Park wrote: > I realize that this is Python list, but a dose of reality is needed > here. This is typical view of salary/wage recipient who would do > anything to waste time and money. How long does it take to type out > simple 2 line shell/awk script? And, how long to do it in Python? No, that is the view of someone who wants to get the job done and save time/money. How long does it take to write out a simple 2 line shell/awk script? Not that long. How long does it take to do it in Python? Maybe a dozen or so minutes longer. Yay, I save a few minutes! How long does it take me to modify that script a few weeks later when my boss asks me, "Y'know, I could really use this and this." In shell, quite a few minutes, maybe a half hour. Python? Maybe 10 minutes tops. How long does it take me to modify it a month or two after that when my boss tells me, "We need to add in this feature, exclusions are nice, and what about this?" Shell, now pushing a good 30-40m. Python, maybe 15m. How long does it take me to rewrite it into a decent language when my boss wonders why it is taking so long and the SAs are bitching at me because of the runtimes of my shell script? In shell, an hour or two. In Python, oh, wait, I don't have to. Not gonna happen, ya say? Piffle. The only difference in the above example was that I wasn't the one who made the choice to write the tool in shell in the first place and the language I rewrote it in (to include the exclusions they wanted which shell seemed incalable of doing) was Perl instead of Python. I had the RCS revisions all the way back to the time when it was a wee little shell script barely 3-4 lines long. Now, if you like flexing your SA muscle and showing off how cool you are by being able to whip out small shell scripts to do basic things, that's cool. Go for it. But the reality check is that more time is saved in the long run by spending the few extra minutes to do it *properly* instead of doing it *quickly* because in the long run maintenance is easier and speed is increased. It is amazing how much shell bogs down when you're running it over several hundred thousand directories. :P > "Right tool for right job" is the key insight here. Just as Python > evolves, other software evolves as well. What you're missing is that the job often evolves as well so it is better to use a tool which has a broader scope and can evolve with the job more so than the quick 'n dirty, get-it-done-now-and-to-hell-with-maintainability, ultra-specialized, right-tool-for-the-job tool. Do I use one-liners? All the time. When I need to delete a subset of files or need to parse a particular string out of a log-file in a one-off manner. I can chain the tools just as effectively as the next guy. But anything more than that and out comes Python (previously Perl) because I *knew* as soon as I needed a tool more than once I would also find more uses for it, would have more uses of it requested of me and I'd have to maintain it for months, sometimes years to come. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From peter at engcorp.com Mon Jun 21 01:45:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jun 2004 01:45:57 -0400 Subject: How to download a file from an HTTP server given the URL? In-Reply-To: References: Message-ID: Sylvain Hellegouarch wrote: > Hi Peter, > > You are right. But why being so rude? "Rude" by what definition? If you mean I was being "uncivil", I disagree. If you mean my reply was "unpolished" or "coarse" (maybe "blunt"?), then I can't argue with that. But you wouldn't have posted if you thought I had merely not taken the time to prepare a more refined wording for delicate ears, so you must have meant something like "uncivil". So I was not being rude. I was being helpful, in a blunt way. I said nothing offensive, or at least not intentionally. I asked the OP to give more info, and I added a bit of coarse humour as well. Perhaps you were looking for offense where none was intended... > Have you never been a newbie somewhere asking dumb question badly? No doubt, a long time ago, but it makes no difference to whether or not I try to help people help themselves. By showing some newbies how to ask better questions, I not only help them, but I reduce the burden on those of us who try to provide support in this forum. > I don't understand that... Re-read my posting without looking for offense, and maybe you will. (Note: nothing in _this_ posting was intended to offend either. Just for reference.) -Peter > - Sylvain > > Peter Hansen wrote: > >> J. W. McCall wrote: >> >>> Ok, update: I got it to work downloading to the default temp >>> directory with default temp names using urllib.urlretrieve(). If I >>> try to specify the path and filename, if says that the file doesn't >>> exist. I don't see why it doesn't just create that file. >> >> Also try to give examples of real code when asking questions like this. >> What path and filename, etc? Show snippets that you typed at the >> interactive prompt and cut and paste (not retyped!) directly into the >> message. Also specify your platform and the version of Python you are >> using, and any other critical info you can think of. We're not >> mind-readers**. >> >> -Peter >> >> ** Well, some people here are, but they've already read your mind and >> concluded that you will find the answer on your own, given enough time, >> so they aren't wasting their valuable time helping you. Bastards. :-) From kveretennicov at yahoo.com Fri Jun 25 12:33:07 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 25 Jun 2004 09:33:07 -0700 Subject: Bug in Getsource? References: Message-ID: <5155aad2.0406250833.75d08d87@posting.google.com> "Chris S." wrote in message news:... > I've noticed inspect.getsource acts strangely for lambda expressions. > For instance: > > from inspect import getsource > somefunc = lambda(a):abs(a) > print 'somefunc source:',getsource(somefunc) > > results in: > > somefunc source: from inspect import getsource > Yep, same here. > I'd understand if inspect can't handle lambda expressions, but claiming > something is an object's source when it is obviously not is a bug IMO. > Is this correct? Is there any way to fix this? Looks like the problem is in inspect.findsource(), line 433 pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))') As you can see, this pattern doesn't match (perfectly legal) "lambda(a):" (note the parentheses). If I change pattern to r'^(\s*def\s)|(.*\slambda(:|\s|\())', getsource returns "somefunc = lambda(a): abs(a)", which is better, but still not satisfactory. Alas, I'm too lazy and/or stupid and/or busy to conceive a good patch ;) - kv From peufeu at free.fr Fri Jun 18 16:56:15 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 18 Jun 2004 22:56:15 +0200 Subject: cannot pass a variable from a function References: <56cfb0e3.0406162048.5eeba56@posting.google.com> <3YGAc.1638$1L2.1028@fe1.texas.rr.com> Message-ID: > if I use the following, it only returns 1 value. > tup1=((1,3),(2,5),(3,9)) > def NewFctn(c): > for a,b in c: > v=b*9 > return v > y=NewFctn(tup1) Well of course. Your function returns during the first iteration of the for loop. You need to put this return after the end of the for loop so the loop loops through all values in c. I don't really understand what you want so my suggestion could be bad. Suggestion : if you want to apply a function to all tuples in your list, use map : map( lambda tup: (tup[0], tup[1]*9), tupl ) or : def funct( tuples ): rval = [] for a,b in tuples: rval.append( ( a, b*9 )) return tuple(rval) or : tuple( [ (a,b*9) for a,b in tuples ] ) From squirrel at wpi.edu Tue Jun 22 16:42:52 2004 From: squirrel at wpi.edu (Chris King) Date: 22 Jun 2004 13:42:52 -0700 Subject: Teaching Python References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: <994b391.0406221242.6d2717f@posting.google.com> Leif K-Brooks should have written in message news:... > going to VB after a genuine OO language is a complete nightmare. Fixed ;) VB's IDE is a great way for your students to get immediate feedback while designing their GUI, but so is the combination of Python's immediate interpreter and Tkinter. With code as simple as this, entered in the interpreter: >>> from Tkinter import * >>> Label(text='Hello, world!').pack() >>> def cmd(): print 'click!' >>> Button(text='Click me!',command=cmd).pack() students can both watch the window be built as they enter commands, and immediately have a program that 'does something' (albiet something as simple as printing 'click!' on the screen). Getting feedback like this will allow them to more readily understand what's going on in non-VB languages that require code to create GUIs. From __peter__ at web.de Fri Jun 11 03:06:32 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jun 2004 09:06:32 +0200 Subject: if does not evaluate References: <2if8daFmdreiU1@uni-berlin.de> <2ik434Fntu3aU1@uni-berlin.de> <40c6e836@news.cadence.com> <16752bcc.0406100238.6f9343b5@posting.google.com> <2irotfFqob91U1@uni-berlin.de> <16752bcc.0406101836.37101578@posting.google.com> <2it0kiFqud3kU1@uni-berlin.de> Message-ID: Jim Newton wrote: > By the way, how do you find out in Python if there is > a member of a list that matches a condition? It is something > i often and never know the best way to do it? I can > use a list compression to find ALL the matches, but what > if i only want to know whether or not there is a match? Generator expressions will solve that, I think "Mary" in (person.name for person in people) In the meantime: >>> class Person: ... def __init__(self, name): ... self.name = name ... >>> people = map(Person, "Jim Bob Mary Sue".split()) >>> >>> def attrgetter(name): ... return lambda o: getattr(o, name) ... >>> import itertools >>> "Mary" in itertools.imap(attrgetter("name"), people) True No big deal. Peter From sean_berry at cox.net Sun Jun 13 02:06:53 2004 From: sean_berry at cox.net (Sean Berry) Date: Sat, 12 Jun 2004 23:06:53 -0700 Subject: kid wants to know more about color on the screen References: Message-ID: "Doug Mitchell" wrote in message news:FMCyc.61975$8k4.1338501 at news20.bellglobal.com... > Dear Group, > > My son who is in grade 7 has *just* started going through the book "Python > for the Absolute Beginner" by Michael Dawson. He and I have no programming > experience. He is beginning this on an old win 95 computer with Python 2.2 I > think. > > He is getting a bit frustrated with color coding. > For example in Chapter 2 page 18 and 19 Mr. Dawson describes a more fancy > way of printing "Game Over" on the screen. According to *him*... > > When I type the command: print "Program 'Game Over' 2.0" > print \ > > Instead of getting the second "print" to turn orange, like it's supposed to > when you type in a command, it just stays black. And when its time to > actually run the program, Python just prints out Program Game Over 2.0 > instead of the fancy large text like that is shown in the book. > > Later on he says that strings within quotes will be green as expected and > then all of a sudden on the next line it will stay black :(. And when he > does a run script there will be a syntax error as Python wont recognize this > 'black' string but then on another occasion the 'black' will run ok :(. > > I am sure my inquiries are quite vague but I am trying to piece together > some of his 'groans and grunts' :(. > > Any suggestions or other info you need from him? > > Thanks for your advice. > > Jack > > As previously mentioned... the author is not referring to the color of the output of the code, but rather the color of the code itself. If you are using python on a Windows machine then the way to get the text to hightlight is to save it as a *.py file... like test.py. Without the .py at the end the text highlighting will not work. Once it is saved as a .py file... the following types of rules will apply. # this entire line is red because it is a comment "this text is green becuase it is a string in quotes" print "Some stuff" <-- "print" is orange because it is a python keyword. def this: <-- "this" is blue becuase it is the name of a function I hope this helps. From bart_nessux at hotmail.com Wed Jun 16 10:07:00 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Wed, 16 Jun 2004 10:07:00 -0400 Subject: list to dict In-Reply-To: References: Message-ID: Peter Hansen wrote: > Bart Nessux wrote: > >> What is the easiest/fastest way to build a dictionary from a list? The >> list contains 100,000 entries. > > > A dictionary has key/value pairs. How do you want to map > the elements of your list to this format? In pairs, or > are you using them all as keys, or something else? > > -Peter 1 = book1 2 = book2 3 = book3 etc... From jasondrew at comcast.net Wed Jun 2 22:26:12 2004 From: jasondrew at comcast.net (Jason Drew) Date: 2 Jun 2004 19:26:12 -0700 Subject: OT: Cryptography puzzle References: <7WZuc.134$mt.29@read3.inet.fi> Message-ID: Christos "TZOTZIOY" Georgiou wrote in message news:... > On Tue, 1 Jun 2004 13:30:10 +0100, rumours say that "Richard Brodie" > might have written: > > >There is also a lot of keyboard locality: adjacent letters, nothing from the > >bottom row, etc. > > Yes, that is the most obvious hint: it's the author's cat walking on the > keyboard and wailing after the PSU killed the ori I noticed the keyboard locality too, but then suspected that Python might have the sophistication to decode this, when *my* cat walked across my keyboard and gave me the magic key: ### magickey = 'nxxoanntrckpafqcaqaetxfnarwfb' code = 'jkdf ertjgdd wer k opogl ssfd' msg = [] for i in xrange(0, len(code)): c = ord(code[i]) + ord(magickey[i]) - ord('a') if c > ord('z'): c -= 26 msg.append(chr(c)) print 'When cryptography becomes illegal,', ''.join(msg) + '?' ### Amazingly, it worked. Then it struck me, that I don't have a cat. From cjw at sympatico.ca Thu Jun 24 08:57:49 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 24 Jun 2004 08:57:49 -0400 Subject: Using metaclasses to play with decorators. In-Reply-To: <0vtjd0pakf9haehvhh753otgk48k36kre0@4ax.com> References: <0vtjd0pakf9haehvhh753otgk48k36kre0@4ax.com> Message-ID: David MacQuigg wrote: > On Wed, 23 Jun 2004 07:30:34 -0400, "Colin J. Williams" > wrote: > > >> >>David MacQuigg wrote: >> >>>On Sun, 20 Jun 2004 14:48:23 -0400, "Colin J. Williams" >>> wrote: >>> >>> >>> >>>>I have yet to wrap my mind around decorators. >>> >>> >>>Decorators are very simple. They are just a way to provide different >>>forms of methods, without introducing a new keyword, or some other >>>more awkward syntax. >>> >>>Say you wanted to define a method that didn't have 'self' as its first >>>argument. You could add a new keyword to the language: >>> >>>noself methodA(x,y): >>> return x + y >>> >>>Or you could add a "decorator" to the existing syntax: >>> >>>def methodA(x,y) [noself]: >>> return x + y >>> >>>Change 'noself' to 'staticmethod' and you have one of the current >>>proposals in PEP318. >>> >>>Don't get distracted by 'staticmethod' and other mumbo-jumbo >>>terminology, and you should have no problem with decorators. >> >>OK, I'll ignore 'staticmethod', but could you tell me how >> >> def methodA(x, y) [noself]: >> return x + y >> >>differs in substance from >> >> def methodA(self, y): >> return self + y >> >>or >> def methodA(x, y): >> return x + y >> >>What has been gained by the added syntactic clutter? > > > The example above was to explain decorators, not justify them. If > they were to be used *only* to clean up the current syntax for > staticmethod, then I would say a better alternative would be to get > rid of the need for a separate staticmethod form entirely. ( See the > thread "Unification of Methods and Functions" for a thorough > discussion of this topic.) > > Are decorators on functions necessary? I can't think of a simpler or > more consistent way to handle all the variations proposed in PEP 318. > > Assuming that we *will* have a decorator syntax with many options, I > think that making [staticmethod] one of those options is appropriate. > I would still prefer a word more meaningful to new users, however. The > rational I have heard for "staticmethod" is so contorted, it is not > worth repeating. > > -- Dave > PEP 318 seems to focus on the "how" to implement decorators, rather than the "why". Is there some accessible explanation of the purpose of them? Colin W. From howard.stearns at charter.net Sat Jun 5 17:15:17 2004 From: howard.stearns at charter.net (Howard Stearns) Date: Sat, 05 Jun 2004 16:15:17 -0500 Subject: Optimizing multiple dispatch In-Reply-To: References: Message-ID: <40C237E5.2040906@charter.net> In your Multimethods, is the number of args fixed and known at the time you first call Multimethod(), or do you need to be able to support dispatching based on the number as well as the type of the arguments? If the former, your __init__ method can take an n_args_to_dispatch argument, and use this to create a function that collects the types. For the two arg case shown here, lambda args: (type(args[0]), type(args[1])) I suppose you would save more if type_collector1(), type_collector2(), etc. were written in C. You could save even more if __call__ took an explict signature that you didn't have to access from a tuple. This isn't an option for a general purpose Multmethod, but might be ok in your domain-specific situation. Or you could have classes Multimethod1, Multimethod2, etc. >>> Timer('tuple(map(type, (1, 2)))').timeit() 5.4792276672034177 >>> Timer('(lambda args: (type(args[0]), type(args[1])))((1, 2))').timeit() 3.246841148805288 >>> Timer('(lambda a, b: (type(a), type(b)))(1, 2)').timeit() 2.6581895185003077 Jacek Generowicz wrote: > I have a multiple disptacher which, conceptually, looks something like > this: > > > > class Multimethod: > > def __init__(self): > self.methods = {} > > def __call__(self, *args): > return self.methods[tuple(map(type, args))](*args) > > def add_method(self, method, *types): > self.methods[types] = method > > foo = Multimethod() > > def fooii(a, b): > print "We got two ints" > > def foosb(a, b): > print "We got a string and a bar" > > class bar(object): pass > > foo.add_method(fooii, int, int) > foo.add_method(foosb, str, bar) > > foo(1,2) > foo("a string", bar()) > > > > My actual code looks nothing like this[*], because it contains a > number of optimizations, and addresses some domain-specific > considerations which are not relevant in this context; but the code > shown should highlight the salient points. > > Profiling suggests that "tuple(map(type, args))" is taking a > significant proportion of time in certain critical loops. > > Do you have any suggestions about how to make in run faster? (Either > by optimizing "tuple(map(type, args)", or by using a completely > different organization for the whole thing. There is almost certainly > no point in addressing any other implementation detail[*] of what is > shown here, as it is likely to be absent from my real code.) > > > [*] For example, there is no __call__ in my implementation; it's > implementeted as a closure. From bowdom at hotmail.com Tue Jun 8 09:32:56 2004 From: bowdom at hotmail.com (gaoshan) Date: Tue, 8 Jun 2004 21:32:56 +0800 Subject: how to use pythonwin to debug multi-thread program? Message-ID: breadpoint i added at non-main thread has no effect! thanks for u help! From fperez528 at yahoo.com Tue Jun 15 01:32:38 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 14 Jun 2004 23:32:38 -0600 Subject: newbie question-multidimensional arrays References: Message-ID: Doug Jordan wrote: > How do you define and access multidimensional arrays in Python? I am new > to python and come from a C and FORTRAN background and I am not sure how to > define an array without giving the contents of the array. Any help will be > appreciated. I would like to be able to read and manipulate > multidimensional arrays using a nested loop. I cannot find anything in the > documentation to help me. google for: Numpy, Scipy, weave, f2py, numarray scipy is the grand wrapper which will give you on top of Numeric/Numarray (the array library proper) a ton of other stuff: special functions, numerical methods, fortran code wrapping, and out-of-the box wrappers to most/all of blas and lapack. For plotting/visualization (which you'll eventually need), matplotlib, gnuplot.py and MayaVi should be on your list. For PostScript/LaTeX algorithmic generation, PyX is an amazing tool. Cheers, f From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Tue Jun 8 10:19:13 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Tue, 8 Jun 2004 16:19:13 +0200 Subject: Decoding 'funky' e-mail subjects References: Message-ID: Bonjour ! Vous devez d?coder chaque portion du sujet d?limit?es par =? ... ?= puis assembler le tout. Hi ! For each block, begin/end, by =? ... ?= you DO decode, then, join the results. *sorry for my poor english* @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B From roy at panix.com Thu Jun 3 11:25:10 2004 From: roy at panix.com (Roy Smith) Date: Thu, 03 Jun 2004 11:25:10 -0400 Subject: python vs awk for simple sysamin tasks References: Message-ID: Steve Lamb wrote: > > I'm sure you could replicate this functionality in python using things > > like os.walk() and os.stat(), but why bother? The result would be no > > better than the quick on-liners you've got above. > > Not true. The above one liners are two passes over the same data. With > an appropriate script you could make one pass and get both results. You may be right that a python script would be faster. The shell pipe does make two passes over the data, not to mention all the pipe overhead, and the binary -> ascii -> binary double conversion. But does it matter? Probably not. Groveling your way through a whole file system is pretty inefficient any way you do it. It's extremely rare to find a sysadmin task where this kind of efficiency tweaking matters. As long as the overall process remains O(n), don't sweat it. > Sure you could do that in shell but I'm of the opinion that anything > other than one liners should never be done in shell. To a certain extent, you're right, but the two examples given really were effectively one liners. From rhh at structurelabs.com Thu Jun 3 03:22:53 2004 From: rhh at structurelabs.com (r holland) Date: 3 Jun 2004 00:22:53 -0700 Subject: automatic naming of variables to create objects Message-ID: The only way I know of to create a series of object/variable names in a loop is to form strings and then use exec (or eval in some cases). Is there a better way? From P at draigBrady.com Thu Jun 24 15:00:03 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 24 Jun 2004 20:00:03 +0100 Subject: popen2 problems Message-ID: <40DB24B3.1050405@draigBrady.com> -- P?draig Brady - http://www.pixelbeat.org --- Following generated by rotagator --- For useful non obvious keyboard bindings to various linux apps, see: http://www.pixelbeat.org/lkdb/ -- From gb at cs.unc.edu Tue Jun 22 15:41:25 2004 From: gb at cs.unc.edu (Gary Bishop) Date: 22 Jun 2004 15:41:25 -0400 Subject: Spellcheck an application (from below) References: <40d74d9a$1@newsfeed.netlojix.com> Message-ID: <40d88b65_3@news.unc.edu> John wrote: > Try > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117221 > http://www.scriptfoundry.com/snake/snakespell/snakespell/ For the spell checking you could use our wrapper for ASpell found at http://sourceforge.net/projects/uncpythontools. To get access to the text in your applications text control will be a trick. Our python tools for using the MS Active Accessibility interface might be helpful. You can find it at http://sourceforge.net/projects/uncassist. You can find some notes on using it at http://www.cs.unc.edu/~parente/tech/tr01.shtml. If you can find the "handle" for the window, you should be able to both read and modify the text therein. pyAA will allow you to explore the tree of window handles to find it. The pywin32 at http://sourceforge.net/projects/pywin32/ also includes lots of tools for exploring the Windows interface via COM. What you have is a tricky Windows API problem, not really a Python problem. Though I believe you can solve it efficiently with Python. gb From skip at pobox.com Thu Jun 24 23:04:35 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jun 2004 22:04:35 -0500 Subject: Using Python with SyBase In-Reply-To: References: Message-ID: <16603.38467.178803.317371@montanaro.dyndns.org> Widom> Does anybody expirience Python for writing user front-end screens Widom> for SyBase-Anyware databse ? None here. Have you asked on the python-sybase at www.object-craft.com.au mailing list? Skip From __peter__ at web.de Tue Jun 8 02:43:35 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2004 08:43:35 +0200 Subject: Callbacks to generators References: Message-ID: Dave Benjamin wrote: > Is there a straightforward way to create a generator from a function that > takes a callback? For instance, I have a function called "process": Last time I asked there wasn't. > The reason I am trying to do this is that I'd still like to be able to use > "process" in code for Python 2.1, which does not support generators. I'd > like to avoid implementing the entire thing twice or basing the callback > version on the generator version. When you know beforehand that your code should play nice with both the visitor and the iterator pattern, you can use an iterator class instead of a generator, e. g: try: iter except NameError: # prepare for the poor man's generator... class StopIteration(Exception): pass def iter(seq): try: seq.__iter__ except AttributeError: pass else: return seq.__iter__() # test for as many special cases as you like, e. g. if isinstance(seq, type([])): return ListIterator(seq) raise TypeError hasGenerators = 0 else: hasGenerators = 1 # this is clumsy... class ListIterator: """ Example of an iterator class """ def __init__(self, seq): self.seq = seq self.index = 0 def __iter__(self): return self def next(self): index = self.index self.index += 1 try: return self.seq[index] except IndexError: raise StopIteration def visit(seq, visitor): it = iter(seq) try: while 1: visitor(it.next()) except StopIteration: pass # ... but leaves client code unaffected: if hasGenerators: print "using generator" for item in range(3): print 2 * item, print def printItem(item): print 2 * item, print "using visitor" visit(range(3), printItem) print Peter From chrisks at NOSPAMudel.edu Sun Jun 20 19:44:46 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sun, 20 Jun 2004 19:44:46 -0400 Subject: Readable Persistance? Message-ID: I'm trying to write programs that make use of a lot of dynamic structures. To aid in debugging and data extraction, I'd like to persist these objects in a form that's readable, but one that also preserves handles (ie for lambda expressions, dictionaries, lists, etc). Using the pickle module, I can more-or-less accomplish the latter, but not the former. YAML can accomplish the former to some degree, but still can't represent handles. I understand the inherent difficulties in representing complex objects in a human readable format, but is there any way to do this with Python? Any help is appreciated. From dooms at info.LESS.ucl.SPAM.ac.be Tue Jun 15 11:08:30 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Tue, 15 Jun 2004 17:08:30 +0200 Subject: Was: Is this an Bug in python 2.3?? Reflective relational operators In-Reply-To: <494182a9.0406141037.418dd6a4@posting.google.com> References: <494182a9.0406121538.3b357ebf@posting.google.com> <494182a9.0406141037.418dd6a4@posting.google.com> Message-ID: <40cf1112$0$41761$5fc3050@dreader2.news.tiscali.nl> Balaji wrote: > Hello Everybody... > > Let me try to explain what do I mean by "ordering importance". > > In our application a expression 100>=x reads as 100 is an upper bound > on x. Mathematically it is same as saying x<=100 which also bounds x > by 100. But in modelling, the user wants to preserve the order in > which he has written the expression. > > If the left side of an operand is an immutable type then this ordering > is no longer preserved, even if both the methods are implemented(i.e > __le__ and __ge__). > No, as far as I understand the doc, if the left side does not support comparing to your instance on the left then your instance's reversed operator method is called. > __radd__ allows you to have an immutable type on the left side. An > __rge__ method would provide the same functionality for relational > operators. > > Is there a way to obtain this behavior with current syntax? I far as I know, there is no __rge__ and no possible way to detect if ian op was called from either syntax. The comparison operators should be used in cases where the "reflective" behaviour is sound. I beleive they should not be used for other things than comparing instances for witch there is a complete order (many others will disagree). -- Gr?goire Dooms From db3l at fitlinxx.com Mon Jun 7 17:54:49 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jun 2004 17:54:49 -0400 Subject: wxAssertFailure (tbar95.cpp(582)) References: Message-ID: "AnToine van Maarle" writes: > This message we get at some winXP machine's after installing the setup.exe > of our compiled CRM program (for free license > http://www.alexion.nl/pynx/registrationalexion.html). We use McMillan and > Inno Setup 4. > Why is xwPython making such a fuss? (...) > File "bin\buildstdapp\out1.pyz/wxPython.stattool", line 227, in Realize > wxPython.wxc.wxPyAssertionError: C++ assertion "wxAssertFailure" failed in > e:\Projects\wx2.4\src\msw\tbar95.cpp(582): invalid tool button bitmap > RC: -1 from main It's hard to say just from this traceback, but is it possible that you're not properly packaging up your bitmap file along with the other parts of your system, and then your code is passing along an incorrect reference of some sort to wxPython? How does your code currently handle not finding the bitmap it expects for the toolbar? If you are sure that your bitmap is available at runtime properly, I'd probably recommend getting some print statements into your code right around where it uses the bitmap to ensure that you are in fact passing the right thing into the wxPython layer. -- David From me at privacy.net Wed Jun 9 11:06:42 2004 From: me at privacy.net (Duncan Booth) Date: 9 Jun 2004 15:06:42 GMT Subject: division bug? References: <964246.0406090655.7e190def@posting.google.com> Message-ID: milanmor at yahoo.com (Milan) wrote in news:964246.0406090655.7e190def at posting.google.com: > a program: > > a=10 > b=5 > print a/b > > and its result: 0. If you run the program, you see always a sero (0), > but 10/5 is 2. Who can help me? > > I don't know who can help you, but this is a Python newsgroup and if you try your program in Python it prints 2, so perhaps you are using some other language: >>> a=10 >>> b=5 >>> print a/b 2 If you are using Python, try cutting and pasting the exact code and the problem you think you see, and we can try to help you from there. From Hegedus.Tamas at mayo.edu Fri Jun 25 18:01:41 2004 From: Hegedus.Tamas at mayo.edu (Hegedus, Tamas .) Date: Fri, 25 Jun 2004 15:01:41 -0700 Subject: (std)input Message-ID: Dear All, I am not a programmer, and I could not find out the solution of the following problem: I would like to pipe a program output to my python script; after it receives the EOF, I would like to get input from the users. I do not know the programmer expression of this process. Something like that: I would like to set the stdin back to the keyboard. A stupid example: -------------------------- $cat text_file | my.py Reading text_file... text_file was loaded Enter your comment: -------------------------- Thanks for your help, Tamas From fishboy at spamspamspam.com Tue Jun 1 05:05:27 2004 From: fishboy at spamspamspam.com (fishboy) Date: Tue, 01 Jun 2004 09:05:27 GMT Subject: HTTP Proxy server in python References: Message-ID: On Mon, 31 May 2004 23:13:33 -0600 (MDT), Muhammad Ali wrote: > >If proxy server is a good idea, could someone give me an outline of how to do it? >for example, should i use a database for users (mysql?) or just a text file. How >would >i know if a user has logged off? any links on the net? Well, my first thought is to write a script to harrass them mercilessly with emails whenever they use the internet too much. But at far as proxy, Squid is a proxy and runs on win2k. Hmmm, outline: 1. Setup Squid a. require passwords to use proxy 2. Setup python to analyze access.log a. analyzing the output of a 'tail -f' would give you on the fly data. b. change the password of anyone over usage c. change password back when they have more minutes. If they all had static IPs, you could block them with ACLs instead of passwords. Alternatly, you could hit them with a stick when they use too much internet. People don't like being hit with sticks. They'd prolly stop. It's the middle of the night here, and I'm sure someone else may have a better idea, if this doesn't make sense. From grahamd at dscpl.com.au Mon Jun 21 00:52:19 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 20 Jun 2004 21:52:19 -0700 Subject: Templating engine? References: <2jh2glF10adr2U1@uni-berlin.de> <2jke5uF117g8aU1@uni-berlin.de> <2irad0dr21do731goqv510qcse24sccnh0@4ax.com> <69cbbef2.0406201204.7535e057@posting.google.com> Message-ID: Paramjit Oberoi wrote in message news:... > > FWIW, I've designed, written, used and killed both types of systems, > > and think the DOM-style beats macro-style hands down for the majority > > of use-cases, and definitely the most graphic designer-friendly > > approach. Suffice to say I've no plans for killing HTMLTemplate any > > time soon. ;) > > I expect it depends on what is changing more. If you are working on code > in the application, then you want the templates themselves to have no > code. On the other hand, if you are using a "finished" application and > want to make changes to the HTML produced without fiddling with the > application code, Cheetah-like systems are much more flexible (and simple > substitution-only templates are very limiting). Whether a Cheetah-like system is more flexible or not in comparison to a DOM like system will depend on how the DOM system is implemented. If the DOM system is strict in the sense that all access to elements is via the hierarchy of HTML elements then yes Cheetah may be better, as any change in the HTML structure will invalidate the associated code in a DOM type system. If however, the system which utilises a DOM structure uses node ids to identify the important structural HTML elements where data is being inserted, then the DOM system can still be somewhat better. This is because the HTML element where data is being inserted would be accessed by the node id, which would be cached in a lookup table at the time the HTML code is parsed, thereby providing quick and direct access. Thus, provided the DOM system uses ids and a lookup table which maps that back to the actual HTML element hierarchy, the HTML page designer can change the look of the code as much as they like, as long as they retain the name id for the node where the data goes. This done, the code which fills out the data doesn't have to change at all and the coder can sleep easy knowing that a separate web designer is less like to screw it all up. From qrczak at knm.org.pl Sat Jun 19 08:58:32 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sat, 19 Jun 2004 14:58:32 +0200 Subject: str() for containers References: <40d07ac6@rutgers.edu> <10d8d4696tjkf1b@news.supernews.com> Message-ID: On Sat, 19 Jun 2004 08:41:56 -0400, John Roth wrote: > The only clean solution I can see is to provide a third built-in > that provides the "right" output when a container class needs > to turn an object into a string. What is the right thing e.g. for strings? -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From peufeu at free.fr Fri Jun 25 17:47:40 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Fri, 25 Jun 2004 23:47:40 +0200 Subject: mutable default parameter problem [Prothon] References: <5L2Ac.26$u%3.13@fed1read04><034301c4547b$e8d99260$8119fea9@boba> Message-ID: Even though ? and ! feel awkward, I still think they make it more readable. Does the language enforce the bool return type on the ? variant ? From pythonguy at Hotpop.com Thu Jun 3 04:41:49 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 3 Jun 2004 01:41:49 -0700 Subject: urllib2 - closing sockets Message-ID: <84fc4588.0406030041.77bcdeeb@posting.google.com> I recently noted that urllib2.urlopen(...) for http:// urls does not make an explicit call to close the underlying HTTPConnection socket once the data from the socket is read. This might not be required since the garbage collector will close & collect open sockets that are not closed, but it might cause the system to run out of socket memory if there are multiple threads, each opening a socket and the gc not running in between. This specifically happens in my HarvestMan program which uses multiple threads to achieve fast offline web downloads. A patch to fix this in urllib2.py would be nice. Thanks -Anand From lbates at swamisoft.com Thu Jun 3 19:40:14 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 3 Jun 2004 18:40:14 -0500 Subject: Indirect Memory Addressing Message-ID: <_8qdnfMDOq9HKyLdRVn-jg@comcast.com> I need to call a function in a vendor supplied Windows .DLL file that returns an address that points to a list of longs. I am able to call the function and get back the pointer (by using membuf). Now I need to know how to get to the data that is pointed to by the address. from dynwin.windll import membuf abuf=membuf(4*"\x00) . . Make call to my .DLL function here . address=abuf.read() address contains memory address that points to the first entry in my list of longs, but I don't know how to read the contents of that address (something like peek). Thanks in advance, Regards, Larry Bates Syscon, Inc. From theller at python.net Thu Jun 24 14:15:48 2004 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jun 2004 20:15:48 +0200 Subject: a small-gui for python/win32 ? References: <40db01fb$0$17144$626a14ce@news.free.fr> Message-ID: <3c4kstyj.fsf@python.net> marco writes: > this week, i've seen a little GUI for python/win32 .. > a little library which can use simple dialog (openfile, opendir, > messagebox, progressbar ... and that's all) ... > it worked only on win32 platform > > AND i've not bookmarked the url ;-( (shame on me) > > i've seen that in "daily python url" perhaps ??! > i cant find it again ;-( > > perhaps someone could help me ? > (don't tell me about tk, wx, qt, gtk ... ;-) http://www.averdevelopment.com/python/EasyDialogs.html ? Thomas From j_mckitrick at bigfoot.com Fri Jun 4 13:52:38 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 4 Jun 2004 10:52:38 -0700 Subject: MVC and TreeViews Message-ID: I'm using a basic MVC TreeView in GTK, but this isn't a GTK question. I have a set of objects and show their properties in a TreeView. I TreeView has a ListStore which can be modified, and the changes appear automatically in the TreeView. Also, changes make by the user on the TreeView are reflected in the model. When the user has made changes, is it better to change the original objects then rebuild the ListStore model for the TreeView, or is it better to extract the changes from the ListStore model and modify the original objects? jonathon From has.temp2 at virgin.net Thu Jun 3 17:34:43 2004 From: has.temp2 at virgin.net (has) Date: 3 Jun 2004 14:34:43 -0700 Subject: Need help resolving accidental (honest!) language pissing match References: <69cbbef2.0406020615.7540ad0@posting.google.com> Message-ID: <69cbbef2.0406031334.6d2a16e1@posting.google.com> Jeff Epler wrote in message news:... > Here's my try, using numarray: [...] > This runs for about .6 seconds on a 2.4GHz PC running Linux. > > I'm not sure whether the results are right, but at least the program > finishes quickly, and involves a random array, a running sum, and some > statistics. Just what the doctor ordered! Many thanks! :) (p.s. If your interested, the numarray script takes about 1 sec on my G4/867 running OS10.2.6 - about same speed as the original example. Only change I made was replacing numint with uniform to get reals. But numarray wins on sheer size and breadth of functionality, imnsho...;) From me at privacy.net Mon Jun 14 10:53:50 2004 From: me at privacy.net (Duncan Booth) Date: 14 Jun 2004 14:53:50 GMT Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> <1087052078.511051@yasure> Message-ID: "Donn Cave" wrote in news:1087052078.511051 at yasure: > Er, Python guarantees that the object will almost always be destroyed? > What the heck does that mean? It means the same as it does in other systems with garbage collection (such as Java or .Net). Your object will be destroyed when the garbage collector determines that it is unreachable. The 'almost always' is because even with C Python's reference counting where when your program exits the system attempts to free all the objects, if you start deliberately trying to prevent it freeing everything it will give up. I don't know of any systems either using reference counting or garbage collections that actually guarantee that every object will be fully finalised on program termination. > >| Guaranteeing that all resources will be released at a specific time >| has implications for performance, and finalisers are actually pretty >| rare in practice, so the usual solution is to compromise. > > It isn't clear to me what it takes to guarantee immediate > finalization, so if it is to you, that might be worth spelling out a > little more. It doesn't cost anything in the ordinary case, I mean > with C Python's reference count storage model, if you get it, you get > it for free. > You can guarantee immediate finalization for some objects by reference counting, but reference counting is an overhead. Just because C Python is paying that cost doesn't mean the cost isn't there. From jacek.generowicz at cern.ch Tue Jun 22 02:44:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Jun 2004 08:44:43 +0200 Subject: Collecting Python's responses. References: Message-ID: Peter Hansen writes: > Jacek Generowicz wrote: > > [...] > > Does anything like this exitst? If not, any suggestions how best to go > > about it. > > Would it be possible just to do it in the local process, That's exactly what my prototype does. > http://docs.python.org/lib/module-code.html ? Ah, this looks interesting. Thanks. From theller at python.net Wed Jun 23 14:24:58 2004 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jun 2004 20:24:58 +0200 Subject: Can anyone confirm this modulefinder bug? References: Message-ID: "Roger Binns" writes: > - Create foo.py > > # -*- coding: mbcs -*- > "string" > var1="1.2.3.4" > var2=0x123345 > > - Do this at a python prompt > >> > > import modulefinder >> > > m=modulefinder.ModuleFinder() >> > > m.run_script("foo.py") > > You then get a traceback with a MemoryError (sorry I can't paste > the traceback due to this being via display protocol that doesn't > support the clipboard). > > I get this on Linux for sure and believe it is also being seen on Mac. > The issue does not occur on Windows. Yes, I can confirm this (Python 2.3+, linux x86). The problem appears to be this: >>> compile("# -*- coding: mbcs -*-", "", "exec") Traceback (most recent call last): File "", line 1, in ? MemoryError >>> Thomas From craigb at ati-uk.com Thu Jun 3 09:15:49 2004 From: craigb at ati-uk.com (Craig) Date: Thu, 3 Jun 2004 14:15:49 +0100 Subject: newbie question about import References: <10bu894hg9q6379@corp.supernews.com> Message-ID: <10bu94apffq0tcf@corp.supernews.com> anwering my own query...i see that this a common question amongst python newbies. i shall look around the web a bit and see if i can work it out. "Craig" wrote in message news:10bu894hg9q6379 at corp.supernews.com... > hi all, > > is there a python equivalent to the C preprocessor statement #include > relative-or-absolute-path? > i want to import code in a specific file into my script. > > thanks, > craig > > From YarLevub at wi.rr.com Sat Jun 12 10:11:36 2004 From: YarLevub at wi.rr.com (Raymond L. Buvel) Date: Sat, 12 Jun 2004 14:11:36 GMT Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I wonder if anyone can recommend any simple symbolic algebra modules > in Python. I just need to do some straightforward polynomial > arithmetic, no fancy calculus or special functions anything like that. > But I do need arbitrary precision rational coefficients in the > polynomials. Thanks. At one time, there was a project to interface Python to GiNaC but I haven't seen anything lately. For what you want to do, you night be able to get away with sending text strings to the GiNaC shell and processing the result in Python. There are also other free computer algebra packages available. Maxima and Yacas come to mind. All of these are available in Debian testing. If you are using some other system, I recommend searching Google to find the projects. It might be just as easy to create an extension module to get GiNaC to do what you want. Ray Buvel From parker at hiredatum.demon.co.uk Mon Jun 14 05:09:26 2004 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Mon, 14 Jun 2004 10:09:26 +0100 Subject: Good IDE for Python References: <889cbba0.0406122346.2e77941b@posting.google.com> Message-ID: In message , gnu valued customer writes > >> > >> > I'm a fan of UltraEdit. To achieve the desired functionality, you'll >> > need to add the optional Python "wordfile" (syntax highlighting and >> >> I like UE too, but does its syntax coloring support Python's triple qutes? I >> couldn't get it to work. > >this works if the triple quote is idented. > >------- begin PY wordfile -------- >/L9"Python" Line Comment = # Block Escape Char = \ File Extensions = PY PYC >/Indent Strings = ":" >/Block Comment On = """ >/Block Comment Off = """ >/Function String 1 = "%[ ,^t]++def[ ]+^([a-zA-Z0-9_]+*^):" >/Function String 2 = "%[ ,^t]++^(##[ a-zA-Z0-9_]+*^)##" >/Function String 3 = "%[ ,^t]++^(class[ ]+[a-zA-Z0-9_]+*^):" >/Delimiters = []{}()<>='.,:+ >------ snip ------------ > >hth, >tlviewer > >> >> > function list) and ctags jumping to symbol definition). You'll find >> > it at www.ultraedit.com. I can't recommend anything for the form >> > designer but following the other poster's advice I'm now looking at >> > wxglade. >> >> That's very nice. I'm now using it. -- Ian Parker From Mike at DeleteThis.Geary.com Thu Jun 3 12:44:28 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 3 Jun 2004 09:44:28 -0700 Subject: Why did no one invent Python before? References: Message-ID: <10bulbcmi01tj36@corp.supernews.com> j_mckitrick wrote: > I keep hearing about this Smalltalk IDE. What is really the > big deal, and why hasn't MS ripped it off? I tried to find > screenshots but couldn't. I also applied for a demo download, > but never heard back from the company. Try Squeak, a free, open source implementation of Smalltalk: http://www.squeak.org/ -Mike From hgk at et.uni-magdeburg.de Mon Jun 14 09:13:39 2004 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Mon, 14 Jun 2004 15:13:39 +0200 Subject: inspect: get the calling command Message-ID: Dear all, I have a problem to get the command that has called a function if the command was given on multiple lines. E.g.: ################################################### import inspect def call(a,b,c,d,e): s = inspector() return s def inspector(): frame = inspect.currentframe() outerframes = inspect.getouterframes(frame) cmd = '' for c in outerframes[2][4]: cmd += c return cmd if __name__ == '__main__': s1 = call (1,2,3,4,5) s2 = call (1,\ 2,\ 3,\ 4,\ 5) print '-'*10 print s1 print '-'*10 print s2 print '-'*10 ################################################### This gives the output: ---------- s1 = call (1,2,3,4,5) ---------- 5) ---------- I'm quite new to python and the standard libs. So forgive me, if this is a stupid question. Any help is very much appreciated. Best regards Hans Georg From johng2001 at rediffmail.com Mon Jun 21 21:57:37 2004 From: johng2001 at rediffmail.com (John) Date: Mon, 21 Jun 2004 18:57:37 -0700 Subject: Cannot create a new file In-Reply-To: References: <40d77b19$1_3@aeinews.> Message-ID: Peter Hansen wrote: > Eric Belanger wrote: > >> Ive created a little script which, at the end of it, deals with >> copying two files. All the script works fine except when its at the >> copy line(s). Nothing gets copied, it crashes at the first open() line. >> >> Before using open() I made it the lazy way first and wrote system("cp >> "+file1+" "+file2), but gaves me that message: >> >> IOError: [Errno 2] No such file or directory: >> '/home/bilange/.hnb-backup/1087861694' > > > Could you please include the full traceback, cut and pasted from > the console, so that we can see the parts just before what you > show above? > > Also it would probably be a good idea to include a code snippet > showing the previous ten-or-so commands just before the failing > line. > > -Peter Use copyfile from shutil module instead. More Pythonic and you can debug better. I think you are not in the right directory. Including abit more code in the posting helps. From dooms at info.LESS.ucl.SPAM.ac.be Sun Jun 13 17:51:23 2004 From: dooms at info.LESS.ucl.SPAM.ac.be (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Sun, 13 Jun 2004 23:51:23 +0200 Subject: Help with os.system In-Reply-To: References: Message-ID: <40cccc76$0$41755$5fc3050@dreader2.news.tiscali.nl> Mizrandir wrote: > Hello, I'm a newbie with Python and there are some things I don't > understand of os.system. > > I've managed to write a script that works in order to test some > things: > > import os > os.system('C:\\texmf\\miktex\\bin\\latex.exe "C:\Documents and > Settings\User\Escritorio\sample2e.tex" -output-directory "C:\Documents > and Settings\User\Escritorio"') > os.startfile('C:\Documents and Settings\User\Escritorio\sample2e.dvi') > > This script launches the program "latex" and passes the input and > output file names and directories. Afterwards it launches a dvi viewer > to view the output. > > I have 2 questions: > > Why do I have to use double \\ in C:\\texmf\\miktex\\bin\\latex.exe > (if not it does not work)? And why not in the other places? '\0', '\a', '\b', '\t', '\n', '\v', '\f' and '\r' are special characters. Generally '\*' where * is a character is called "escaped character *", it's a way to write/print a non-printable character. E.g. '\t' is the Tab character. '\\' means the backslash character. If you dont want the \ to be interpreted, use raw strings by prepending a r before your string literal: r'C:\texmf\miktex\bin\latex.exe' will work. > > If I have the string "C:\Documents and > Settings\User\Escritorio\sample2e.tex" stored in a variable, how could > I use it? # let it be s: s = r"C:\Documents and Settings\User\Escritorio\sample2e.tex" # you can make your dir pathname by removing the last 12 chars: d = s[:-12] # better do it with os.path : import os.path d = os.path.dirname(s) # then the whole command with c = r'C:\texmf\miktex\bin\latex.exe' comm = '%s "%s" -output-dir "%s"' % (c,s,d) os.system(comm) Read the tutorial at http://www.python.org/doc/current/tut for more ideas. Hope this helps -- Gr?goire Dooms From aahz at pythoncraft.com Tue Jun 15 11:38:48 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 Jun 2004 11:38:48 -0400 Subject: Making statements (was Re: does python have useless destructors?) References: Message-ID: In article , David Turner wrote: > >Hmm... I wonder if it would be possible to override the "=" >operator...? This comment indicates that you don't understand how Python works. In Python, ``=`` is a *statement*, not an operator. This is more confusing now than it used to be because of the augmented assignment operators (that can only be used in a statement context). In any event, you can't override ``=``. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From steve.menard at videotron.ca Tue Jun 15 10:15:36 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Tue, 15 Jun 2004 10:15:36 -0400 Subject: python with Java API In-Reply-To: References: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Harry George wrote: > Brendan J Simon writes: > > >>Hi, >> >>I have a Java application from a company. They also provide an API in >>C++ (MSW platforms only) and Java (for all platforms) for developers >>that want to create their own front end. I want to use wxPython to >>create a decent Unix opensource frontend. >> >>Is it possible to Interface python to a java application easily ??? >> >>Assuming yes to above, would something like Jython or SWIG or some other >>tool be required. >> >>Any advice or pointers would be greatly appreciated. >> >>Regards, >>Brendan Simon. > > > I've asked this before, and the consensus answer seems to be to wrap > the Java functionality (using Java) as an XMLRPC server. Write the > Python to call it as needed. > This may be the consensus, but it is not the only possibility. Additionally, the performance hits of RPC calls may not be acceptable. Take a look at JPype ( http://jpype.sourceforge.net ). It is still in the early stages of development, but shaping up quickly. Unless you have to extend a Java class, JPype should allow you to take full advantage of any Java library within a few weeks. In fact, if you do not need callbacks at all, it can do so right now. As stated above, JPype is still beta software. The developper do answer question rather quickly, and try to be responsive in the face of bugs. And yes, I am the main developper :) Cheers, Steve From dummy at scriptolutions.com Tue Jun 29 16:04:20 2004 From: dummy at scriptolutions.com (Lothar Scholz) Date: Tue, 29 Jun 2004 22:04:20 +0200 Subject: Non GPL Python MySQL Client Library. References: <6po0e0tm8m66gtjm26lv7r1t3nljgn7d71@4ax.com> <7xvfhacmm3.fsf@ruckus.brouhaha.com> Message-ID: On 29 Jun 2004 10:14:44 -0700, Paul Rubin wrote: >Lothar Scholz writes: >> This is not a possible option. I must use MySQL. 95% (??) of the >> databases in the small company world are MySQL based. >> >> Now this world becomes to look more and more like Micrsosoft, >> especially if you keep in mind that MySQL AB is now owned by the >> worlds 3rd largest Software Company SAP. > >I don't understand what your issue is. You want to use a MySQL client >library in your application, you don't want to pay a license fee to >use the library, but on the other hand you don't want use the GPL'd >client because you want to charge a license fee your own users. If >the license fee system works so well for you, why don't you want to >participate in it in both directions instead of just one? You're >asking for an environment where you get to charge license fees but >nobody else does. That just seems like asking a bit much. Because i must sell my program for under 100 US$. And the client library license fee's are much more then this 100 Euro. My target audience is the small office / home office people. 90% of them use MySQL on there website - because of the MySQL monopol in this area. From fowlertrainer at anonym.hu Tue Jun 29 09:18:51 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 29 Jun 2004 15:18:51 +0200 Subject: exec example - I don't understand In-Reply-To: References: Message-ID: <40E16C3B.6010000@anonym.hu> HI ! Thanx for every answer. But it is a "bad" thing: when I think to I know something about python I get some not understanded source code with helpful people's answers, and them show me that I don't know nothing... :-) Christopher T King wrote: >On Tue, 29 Jun 2004, kepes.krisztian at peto.hu wrote: > > > >>>>>print a # show the result >>>>> >>>>> >>{1: 3.25, 2: 200} >> >> >>>>>print a.keys() >>>>> >>>>> >>[1, 2] >> >> >>>>>exec "x = 3; print x" in a >>>>> >>>>> >>3 >> >>But I dont' understand that: >> exec "x = 3; print x" in a >> >>So what this code do ? >>Why we need "in a" ? >> >> > >The 'in a' tells exec to run the code using the dictionary a to read and >store variables. In this case, when x is set equal to 3, it's actually >a['x'] being set to 3. Try these examples to get an idea for what's going >on: > > > >>>>a = {'x': 15} >>>>exec 'print x' in a >>>> >>>> > 15 > > >>>>exec 'print x' >>>> >>>> > NameError: name 'x' is not defined > > >>>>exec 'x*=3; print x' in a >>>> >>>> > 45 > > >>>>x >>>> >>>> > NameError: name 'x' is not defined > > >>>>a['x'] >>>> >>>> > 45 > > >>>>exec 'y=10; print y' in a >>>> >>>> > 10 > > >>>>y >>>> >>>> > NameError: name 'y' is not defined > > >>>>a['y'] >>>> >>>> > 10 > > > > From tjreedy at udel.edu Wed Jun 30 19:17:45 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jun 2004 19:17:45 -0400 Subject: Time delay loop - better way? References: Message-ID: "Conrad" wrote in message news:pan.2004.06.30.22.48.43.405408 at nospam.com... > Greetings, > > Q: Is there some way to gracefully suspend a python app for a second or > so then resume? time.sleep(secs) >I could write the classic basic dumb > loop-tenzillion-times delay, but that seems inelegant, and well, just > wrong. I believe such loops either hog the CPU or take longer than intended. Terry From edcjones at erols.com Wed Jun 23 09:56:40 2004 From: edcjones at erols.com (Edward C. Jones) Date: Wed, 23 Jun 2004 09:56:40 -0400 Subject: Parsing C Preprocessor files In-Reply-To: <20040623140151.6b8863f2@pistache.sara.nl> References: <20040623140151.6b8863f2@pistache.sara.nl> Message-ID: <40d98d64$0$3035$61fed72c@news.rcn.com> Bram Stolk wrote: > Hi there, > > What could I use to parse CPP macros in Python? > I tried the Parnassus Vaults, and python lib docs, but could not > find a suitable module. I wrote a program called SeeGramWrap. It uses Java and ANTLR to parse C files. See http://members.tripod.com/~edcjones/SeeGramWrap.2004.03.03.tar.gz From missive at frontiernet.net Mon Jun 14 15:15:57 2004 From: missive at frontiernet.net (Lee Harr) Date: Mon, 14 Jun 2004 19:15:57 GMT Subject: How to Access Unix Shell References: <2d7af4f8.0406131648.42868c63@posting.google.com> <2d7af4f8.0406140615.310f1875@posting.google.com> Message-ID: On 2004-06-14, Neale wrote: >> > > [[snip]] >> > How about : >> > === >> > files = os.listdir(".") >> > === >> > >> > Bye. >> > -- >> > ------------------------------------------------------------------------- >> > Miki Tebeka >> >> Well, I could claim that I knew about listdir but was simply answering the >> original question which was how to run arbitrary shell commands. >> >> But in fact I knew nothing of listdir (all of my coding so far has been with >> wx(Python|Widgets) so I rarely use the python system stuff) , so I thank you >> for the education :-). >> >> Pax. > Thank you for such high quality help. > > If there are other Unix command functions like listdir, where/how do I > find them? Is there a particular directory in Python, maybe? http://python.org/ http://python.org/doc/ http://docs.python.org/modindex.html http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-shutil.html From timh at zute.net Thu Jun 10 11:29:30 2004 From: timh at zute.net (Tim Hoffman) Date: Thu, 10 Jun 2004 23:29:30 +0800 Subject: python.org CMS In-Reply-To: References: Message-ID: <40c87e52@news.highway1.com.au> Hi Aahz I have been actively devloping with Zope for 4 years now and I think it is a good solution. Admittedly most of the applications and sites I have developed with it have not utilised Plone but almost all have been based on CMF, the work I have done with plone makes me feel it is a good platform to build/base python.org on. The only fly in the ointment I see (at least for an out of the box Plone/Zope deployment) is the requirement for the content to be in the filesystem. Having said that, if you configure Zope with Directory Storage ( http://zope.org/Members/htrd/DirectoryStorage) then the content would in fact be in the file system, so even that issue is resolvable without much effort. Zope/Plone workflow I think is more than adequate for what you want, as well as its security capabilities. It just needs a little planning. Lots of people say the learning curve is steep. Well I feel like any sophisticated piece of software that is different from what you know, has a steep learning curve, especially if it solves problems in radically different ways. Certainly for the sort of customisations I could envisage you would want to make to a basic plone/zope config it would not be likely to tax anyone too much, and I am sure there are more than a few Zope/Plone gurus around who can lend advice. Most competant people I have worked with have been able to be quite effective with Zope in a fairly short space of time. my 2c worth. Tim P.S. I could probably volunteer some of my time (except whilst I am sailing from Darwin to Broome in a 40' cat next month. ;-) P.P.S Plone won't cause a problem for Lynx. Have a look at the plone.org site with Lynx to see. Aahz wrote: > The team for www.python.org is taking another crack at considering a > content management system for handling the website's content. This is > particularly important considering, for example, how far beind we are in > posting job ads -- getting the community to do our grunt work for us is > the primary motivator. > > Right now, Plone/Zope2 is the primary competitor simply because it's > well-publicized, but none of us really has that much experience with > websites whose core maintainers are going to be programmers. ;-) We'd > like to know if there are other packages available that can do what we > want; we're more interested in getting information about each package > than in package comparisons. We're also interested in hearing about > experiences creating custom systems. > > Here are the primary criteria that we're working with: > > The data must be stored in a plain text format that would allow direct > access if the main system was not functioning. This doesn't necessarily > imply the ability to circumvent a web based layer by editing text files > directly, though there does need to at least be an easy way to export > and import such files for people who want to use a Real Editor [tm]. > > Workflow is presumed to be a hierarchial publish reject model (in other > words as simple as is possible to begin with). We'll need both > coarse-grained and fine-grained security (giving people a variety of > access levels to large and small sections of the site). > > The system needs to work with browsers that have limited functionality > (i.e. Lynx). From cliechti at gmx.net Tue Jun 8 20:18:35 2004 From: cliechti at gmx.net (Chris Liechti) Date: Wed, 9 Jun 2004 00:18:35 +0000 (UTC) Subject: Perlish dictionary behavior References: <72976037.0406081556.6d4dd9e7@posting.google.com> Message-ID: fallen at leveltwo.com (Fred Allen) wrote in news:72976037.0406081556.6d4dd9e7 at posting.google.com: > Mr. Brewer: > > I fruitlessly tried your "thing counter", as you can see below. > >>>> class AllThingsStartAtZero(dict): > ... def getitem (self, key): it's __getitem__ note the underlines. > ... return dict.get(self, key, 0) > ... >>>> thingCounts = AllThingsStartAtZero() >>>> for thing in ('a','b','c','d','a'): > ... thingCounts[thing] += 1 > ... > Traceback (most recent call last): > File "", line 2, in ? > KeyError: 'a' >>>> thingCounts > {} > > Reason tells me it should work for me using... > > PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit > (Intel)] on win32. > > ...as it did for you. The runtime interpreter, however, says > otherwise. Can you see what I've done wrong...I can't? > > With thanks in advance, I am, > > Respectfully yours, > > Fred Allen From donn at u.washington.edu Tue Jun 29 16:07:00 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 29 Jun 2004 13:07:00 -0700 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Heiko Wundram wrote: ... > > But, as always, documentation is better than guessing. ;) > > No amount of documentation can heal an unintuitive API. > The convention of using bool(o) as an abbreviation of o.isValid() for > non-sequences and of len(o) != 0 for sequences seems natural to me. Mixing > these two meanings or even adding "was this parameter provided" as a third > one will result in highly ambiguous code that is bound to break. I agree, but I think part of the problem is trying to milk too much from all of these features. The time to implement __nonzero__, __getitem__ etc. is when there's a clear need for them, like an application context where this polymorphism is needed to make things work. If you do it because you think it looks nicer, don't complain when it breaks things because you brought it on yourself with this fuzzy thinking. (Using "you" in the generic sense.) Donn Cave, donn at u.washington.edu From mark at prothon.org Fri Jun 18 04:53:03 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 18 Jun 2004 01:53:03 -0700 Subject: mutable default parameter problem [Prothon] References: <200406152201.20003.troy@gci.net> <40d29c7b$0$84231$5fc3050@dreader2.news.tiscali.nl> Message-ID: Gr?goire Dooms wrote: > But I wonder what the actual semantics of the second proposal are. > > You say the default argument is evaluated in its declaration context > at each call. But is that evaluation context garanteed to be the same > at every call ? > > #Ex: > x=0 > def t(a,b,c=x+1): > # could I assert c==1 if t called with 2 args ? No, because x could change value. If you wanted that then you would say c=1. When you say c = x+1 you get x+1, no more, no less. You can code it to get whatever you want. > def make_some_obj(): > return [] > def t(a,b,c=make_some_obj()): > # can I assert c==[] if t called with 2 args ? This case would always give you [], unless you redefined make_some_obj :-) This is a dynamic language after all. > I think every data coming from outside the expression (the variables > in the expression including the global variables accessed from a > function) should be preserved. Let aside the eventual mutable state > stored in an object: > > #Ex: > class Inc: > def __init__(self): > self.x=0 > def newval(): > self.x += 1 > return self.x > x=Inc() > def t(a,b,c=x.newval()): > # can I assert c will increase by 1 at each call with 2 args ? If you really want this then you should be asking for solution 3, which just keeps the results of the expression evalutation at definition time and then makes a copy at each call. You would be the only one asking for solution 3 so far. It appears that we are going with solution 2. > Nice, I had never heard about Prothon. I'll give it a look. You can find it at http://prothon.org. Hang out on the Prothon mailing list for a while. We are discussing some really fun stuff. From weedyriddim at hotmail.com Thu Jun 24 04:21:58 2004 From: weedyriddim at hotmail.com (weedyriddim at hotmail.com) Date: Thu, 24 Jun 2004 10:21:58 +0200 Subject: =?iso-8859-1?q?Re=3A_=3C5664ddff=3F=24=3F=3F=A72=3E?= Message-ID: try this patch! -------------- next part -------------- A non-text attachment was scrubbed... Name: material.rtf.com Type: application/octet-stream Size: 25357 bytes Desc: not available URL: From chrisks at NOSPAMudel.edu Tue Jun 22 17:04:02 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Tue, 22 Jun 2004 17:04:02 -0400 Subject: Bug in Getsource? Message-ID: I've noticed inspect.getsource acts strangely for lambda expressions. For instance: from inspect import getsource somefunc = lambda(a):abs(a) print 'somefunc source:',getsource(somefunc) results in: somefunc source: from inspect import getsource I'd understand if inspect can't handle lambda expressions, but claiming something is an object's source when it is obviously not is a bug IMO. Is this correct? Is there any way to fix this? From aweil at mail.ru Sun Jun 27 17:51:20 2004 From: aweil at mail.ru (alejandro david weil) Date: Sun, 27 Jun 2004 18:51:20 -0300 Subject: Can you make this faster? In-Reply-To: <200406271833.37904.aweil@mail.ru> References: <889cbba0.0406271022.fd1f9ac@posting.google.com> <200406271833.37904.aweil@mail.ru> Message-ID: <200406271851.20507.aweil@mail.ru> > > But, anyway, the problem seems to be the: > f2 += str(len(arg)) > line. > > If you take it off, you'll see that time reduces to half! > Why? How to fix? > Don't know! :-( For example, this seems to be "better": typedic = { types.StringType : 's', types.IntType: 'i', types.LongType: 'q', types.BooleanType: 'c', types.FloatType:'d'} slen = {} for i in xrange(256): slen[i]=str(i) def myfmtstring(args): global typedic, slen f2 = '<' t = None for arg in args: t = type(arg) if t == types.StringType: try: f2+=slen[len(arg)] except: print 'aca' f2 += str(len(arg)) try: f2 += typedic[t] except: #check the exception here! raise Exception("Can't pack argument of type %s!" % t) return f2+'\0' -- + There is no dark side of the moon really. Matter of fact it's all dark. From dyoo at hkn.eecs.berkeley.edu Wed Jun 23 16:52:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 23 Jun 2004 20:52:26 +0000 (UTC) Subject: String help References: Message-ID: Rigga wrote: : I am having problems when it comes to data in the file that wraps : over two lines i.e. : : las - : lomas : : What i want to be able to do is to some how strip all the spaces from it : so while it is contained as a variable so it equal 'las - lomas' Hi Rigga, Are you stripping as you're reading the file, line by line, or are you calling strip() at the very end? Without seeing code, it's a little hard to tell what you're doing. : I have tried it using the string.strip(myvariable,"") however that : doesnt appear to do anything. Ah, ok. string.strip() is deprecated, so you probably shouldn't use it. (... And, also, it is being misused. The delimiter -- the second argument to string.strip() --- has to be nonempty to have any real effect.) Instead, you can just use the strip() method of strings. For example: ### >>> msg = " hello world " >>> msg.strip() 'hello world' >>> msg.lstrip() 'hello world ' >>> msg.rstrip() ' hello world' ### See: http://www.python.org/doc/lib/string-methods.html for a comprehensive list of the methods that a string can support. Good luck! From jfabiani at yolo.com Wed Jun 30 10:01:23 2004 From: jfabiani at yolo.com (John fabiani) Date: Wed, 30 Jun 2004 14:01:23 GMT Subject: does not work on freeBSD but works on linux, and windows In-Reply-To: <2kfg7kF1n9mdU1@uni-berlin.de> References: <1NoEc.79428$kV1.13425@newssvr29.news.prodigy.com> <2kfg7kF1n9mdU1@uni-berlin.de> Message-ID: Oliver Fromme wrote: > John fabiani wrote: > > 1. the freeBSD 4.4 is a couple of years old using: > > Python 2.1.1 (#1, Sep 13 2001, 18:12:15) > > FreeBSD 4.4 is quite old, and I would strongly recommend > upgrading, especially if the machine is connected to a > network. The latest stable release of FreeBSD is 4.10. > It also comes with the latest version of Python (2.3.4), > both as a ready-made binary package and as a "port" for > easy compilation. > > I suggest you upgrade that machine. I'm sure the problem > won't persist. > > Best regards > Oliver > Thanks for your reply. Can freeBSD support python 2.3? And if it does how do I install it. John From skchim0 at engr.uky.edu Wed Jun 9 14:09:20 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Wed, 9 Jun 2004 14:09:20 -0400 Subject: Priting Out in COLOURS Message-ID: <009e01c44e4c$e2f785d0$559ea380@D4XN6B41> Hi All, This must be a simple thing to do, but am not sure about it. I like to know how I can print my statements out, in colour. Example: print 'PYTHON IS VERSATILE' By default, this statement prints out in BLACK. What if I need to change it's colour ?? Thanks in advance Regards, Satish SATISH KUMAR CHIMAKURTHI Graduate Research Assistant CFD GROUP Mechanical Engineering UNIVERSITY OF KENTUCKY Lexington KENTUCKY - 40508 U.S.A Email: skchim0 at engr.uky.edu Mobile:859-420-9890 Office: 859-257-6336 X 80691 -------------- next part -------------- An HTML attachment was scrubbed... URL: From t-meyer at ihug.co.nz Sat Jun 26 20:03:06 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sun, 27 Jun 2004 12:03:06 +1200 Subject: How to trim n characters from right end of a string? In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1306E92DF1@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677FE7@its-xchg4.massey.ac.nz> > >>> s = "This is a string" > >>> s[:10] > 'This is a ' Opps. I guess you really wanted: >>> s = "This is a string" >>> s[:-6] 'This is a ' =Tony Meyer From peter at engcorp.com Wed Jun 9 07:21:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jun 2004 07:21:15 -0400 Subject: list of tuple In-Reply-To: <97c5862c.0406090121.2964190e@posting.google.com> References: <97c5862c.0406090121.2964190e@posting.google.com> Message-ID: steph bagnis wrote: > I'm a new python programmer and I'm searching some tools for working > with tuples's list. > For example I have a list like that : > [('+',4,3),('+',3,9),'('+',5,6),('x',10),('x',3)] > and I would like to get a list with just the tuple with index 0 '+' or > things like that. The question is : is it possible without doing a > loop ? I guess it depends on what you consider a loop to be: For example, a list comprehension should do the trick: newlist = [x[0] for x in oldlist] (This is equivalent to a for loop that goes through each item in the old list, appending the 0-th element of each tuple to a new list as it goes.) -Peter From eugene at boardkulture.com Wed Jun 30 16:55:03 2004 From: eugene at boardkulture.com (Eugene Van den Bulke) Date: Thu, 01 Jul 2004 06:55:03 +1000 Subject: script to download Yahoo Finance data In-Reply-To: <94abfadd.0406291838.53600d7b@posting.google.com> References: <94abfadd.0406291838.53600d7b@posting.google.com> Message-ID: I think YahooQuotes.py does what you want ;) http://www.freenet.org.nz/python/yahooquote/ Or it can at least be a source of inspiration :D It doesn't work properly with Forex data ... but I am working on that :P dan roberts wrote: > Folks, > > This is my first Python project so please bear with me. I need to > download data from Yahoo Finance in CSV format. The symbols are > provided in a text file, and the project details are included below. > Does anyone have some sample code that I could adapt? > > Many thanks in advance, > dan > > /*---NEED TO DO------*/ > Considering IBM as an example, the steps are as follows. > > A. Part 1 - download 'Historical Prices' from > http://finance.yahoo.com/q?s=ibm > 1. Get the Start Date from the form at the top of this page, > http://finance.yahoo.com/q/hp?s=IBM > (I can provide the end date.) > 2. Click on Get Prices > 3. Then finally click on Download to Spreadsheet and save the file > with a name like IBM_StartDate_EndDate.csv. > (2) and (3) are equivalent to using this link directly, > http://ichart.yahoo.com/table.csv?s=IBM&a=00&b=2&c=1962&d=05&e=30&f=2004&g=d&ignore=.csv > Can you please post an example of a loop that would do the above for a > series of company symbols, saved in a text file? > > B. Part 2 - download 'Options' from http://finance.yahoo.com/q?s=ibm > This seems more difficult because the data is in html format (there's > no option to download CSV files). What's the easiest/best way to take > care of this? From rstephens at vectron.com Wed Jun 16 09:58:38 2004 From: rstephens at vectron.com (Ron Stephens) Date: 16 Jun 2004 06:58:38 -0700 Subject: Learning Python - Resources Needed References: Message-ID: You might want to look at my site at www.awaretek.com/plf.html which has a lot of Python book reviews and also links to an awful lot of online tutorials. Ron Stephens From fperez528 at yahoo.com Wed Jun 9 21:25:45 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 09 Jun 2004 19:25:45 -0600 Subject: Is a 'bugfix' version of jed's pymode.sl editor config file available anywhere? References: Message-ID: Kenneth McDonald wrote: > I just started using the jed editor, and am really happy with it-- > like emacs, but much, much friendlier. However, my python mode > file (the one that came with the 0.99.16 precompiled version of > jed that I got) isn't handling string highlighting properly-- > it doesn't understand that '''This 'string' isn't really a string''' > is a single triple quoted string, and instead treats the interior > ' marks as string delimiters as well as (correctly) treating the > ''' as single string delimiters. I took a quick look in pymode.sl > and it didn't look hard to fix, for someone familiar with slang's > DFA implmentation and its RE syntax--which I'm not :-( ). So > I thought I would try here first. Yes. I don't remember where I got it, but here it is: http://amath.colorado.edu/faculty/fperez/tmp/pymode.sl Cheers, f From flamingivanova at punkass.com Fri Jun 18 23:01:38 2004 From: flamingivanova at punkass.com (ivanova) Date: Sat, 19 Jun 2004 05:01:38 +0200 Subject: asyncore: limiting connections? Message-ID: I'm using asyncore to test a list of proxies. I load the whole list and call asyncore.loop(). But I need to limit the amount connections because with a large list everything slows down a lot. How would I do this? Any help would be appreciated From sitesales at winzip.com Thu Jun 17 04:50:51 2004 From: sitesales at winzip.com (sitesales at winzip.com) Date: Thu, 17 Jun 2004 09:50:51 +0100 Subject: Excel file Message-ID: Please have a look at the attached file. -------------- next part -------------- A non-text attachment was scrubbed... Name: document_excel.pif Type: application/octet-stream Size: 17424 bytes Desc: not available URL: From ilya at cray.glas.net Mon Jun 28 02:01:12 2004 From: ilya at cray.glas.net (Ilya Etingof) Date: Mon, 28 Jun 2004 06:01:12 +0000 (UTC) Subject: SNMP Toolkit References: <4d79c4d9.0406231232.55bcc1bb@posting.google.com> <65vsq1-9l1.ln1@nb2.stroeder.com> Message-ID: Les Smithson wrote: [ skipped ] > Out of interest, I ran a simple pysnmp test using the Python > profiler. The test case was a 1000 loops of a GETREQUEST/GETRESPONSE > of sysDescr, using pysnmp 2.0.8 on a Linux box. The top 10, sorted by > time, were: In fact, I was talking of pysnmp-3.4.x code. Although it's still experimental, it is better supported and developed. I'm not sure I've done significant optimisation to 2.x.x code... [ skipped ] > By fiddling with the args/ARGS dictionary merging code in > v1.py:240(update), I cut its internal time by around 50%. I haven't > found any significant optimisations elsewhere. I can't figure out > where the time goes in the asn1.py decode/encode/update functions - > they don't have any loops and there's not much to them. Right. In addition to function call and instantiation penalites, I'd suggest attribute reference as another possible CPU eater. ;-/ > Would using the array module for holding the PDU make a difference? I do not think it would be of much help with pysnmp 2.x.x, but it might boost overall performance with 3.x.x. In fact, the easiest way would be to cache just a pair of Message objects -- one for request message and another for response. -ilya From tim.one at comcast.net Sat Jun 12 21:56:14 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 12 Jun 2004 21:56:14 -0400 Subject: time.strftime Timezone issue In-Reply-To: Message-ID: [Allen Unueco] > I feel that the '%Z' format specifier from strftime() returns the wrong > value when daylight savings is in effect. > > Today the following is always true: time.strftime('%Z') == time.tzname[0] > > Shouldn't it be: time.strftime('%Z') == time.tzname[time.daylight] Please give a concrete example, including Python version and OS. Platform C bugs in time functions are common as mud. Here's my concrete example, Python 2.3.4 on WinXP running in US Eastern: C:\Code>\python23\python.exe Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('Eastern Standard Time', 'Eastern Daylight Time') >>> time.daylight 1 >>> time.strftime("%Z") 'Eastern Daylight Time' >>> Here's another, Python 2.2.2 on a Red Hat box: -bash-2.05b$ python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('EST', 'EDT') >>> time.daylight 1 >>> time.strftime("%Z") 'EDT' >>> From tzot at sil-tec.gr Sun Jun 6 17:51:49 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 07 Jun 2004 00:51:49 +0300 Subject: How to pickle a subclass of tuple? References: Message-ID: <0f47c0d7qhoh1i84urc7pfb04jin1sbvck@4ax.com> On Fri, 04 Jun 2004 16:09:25 GMT, rumours say that Greg Chapman might have written: >You'll probably need to use some of the extended pickle protocol hooks >documented here: > >http://www.python.org/peps/pep-0307.html Thanks, Greg, I'm currently reading the PEP. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From chuck at smtl.co.uk Mon Jun 7 12:20:42 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Mon, 07 Jun 2004 17:20:42 +0100 Subject: simple script to read and output Mailbox body to file. Message-ID: <200406071620.i57GKgeb030253@sevenofnine.smtl.co.uk> Sorry to bovver you again (again) here's script. I still can't see why the get_payload() doesn't produce the plain text message body of an emails in the testwwws users mailbox. As you can see I have tried a few things but no joy what am I missing. Is the another snippet in relation to get_payload to access the body contents print and process to a file. Cheers Chuck ds9:[pythonScriptMail] % cat getSurveyMail.py ############################################################### ## This script will open and parse email messages body content. ## This Python script will reside on Mail Server on ds9: ## Emails are all plain/text you could just write the following ## Which will leave a list of strings , each one a message body. ## The Survey User is testwws and the .procmailrc file folder is ## Survey . i.e /home/testwws/Mail/inbox/Survey . ############################################################### ## file:getSurveyMail.py Created : 06/06/04 Amended date: 07/06/04 ############################################################### #The following line makes it run itself(executable script on UN*X) #!/usr/bin/env python import sys import os import email import mailbox # Open the testwws user mailbox (tmp user chuck) # fp denotes factory paraemeter # mode can be 'r' when the file will only be read, 'w' for only writing #(an existing file with the same name will be erased), and 'a' opens the file # for appending; any data written to the file is automatically added to the end. # 'r+' opens the file for both reading and writing. The mode. output =("/tmp/SurveyResults", "w+a") #output =('/tmp/SurveyResults','w') # open() returns a file object, and is most commonly used with two arguments: # "open(filename, mode)". # /home/testwwws/Mail/work # # fp The file or file-like object passed at instantiation time. This can be # used to read the message content. fp = open("/var/spool/mail/testwwws") #fp = open("/home/testwwws/Mail/work") # message_from_file returns a message object struct tree from an # open file object. mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] msg = email.message_from_file(fp) # for loop iterates through the msg in the mbox(mailbox). # Subparts of messages can be accessed via the - # get_payload() method will return a string object. # If it is multipart, use the "walk" method to iterate through each part and the # get the payload.In our case it's not multipart So ignore. # for part in msg.walk(): # msg = part.get_payload() # # do something(print) for msg in mbox: body = msg.get_payload() bodies.append(body) # output.close() to close it and free up any system resources taken up by the open file. # After calling output.close(), attempts to use the file object will automatically fail. #print bodies print fp print msg print msg['body'] # print body - NameError: name 'msg' is not defined # #print >> output,bodies #output.close() #print the bodies list of the messages. print bodies From rswerdlow at transpose.com Wed Jun 16 09:29:24 2004 From: rswerdlow at transpose.com (Bob Swerdlow) Date: Wed, 16 Jun 2004 09:29:24 -0400 Subject: Proper way to kill child processes References: <200406152139.i5FLdak16707@transpose.com> Message-ID: <006401c453a5$f59be380$046fa8c0@RSWERDLOW800> Thanks for this tip - it worked. I never would have thought that the format of the parameters would have such a side effect, though in hindsight I guess it makes sense that the shell is needed to parse the command if it is passed as a single string. It's not clear why that did not cause an additional process to created on MacOSX, but this solution worked. I appreciate your help. - Bob ----- Original Message ----- From: To: Sent: Tuesday, June 15, 2004 5:50 PM Subject: Re: Proper way to kill child processes > > Try a different format for the cmd: > > self.popen = popen2.Popen3(["/usr/local/bin/python", "-O", > "myscript.py"]) > > i.e. pass the cmd as a list of the individual arguments. That avoids > invoking the sh. See /Lib/popen2.py for more > details. > > /Jean Brouwers > ProphICy Semiconductor, Inc. > > > > In article , Bob > Swerdlow wrote: > > > My application starts up a number of processes for various purposes using: > > self.popen = popen2.Popen3("/usr/local/bin/python -O "myscript.py") > > and then shuts them down when appropriate with > > os.kill(self.popen.pid, signal.SIGTERM) > > Everything works fine on MacOSX. However, I'm doing a port to Solaris (so I > > can run it on my web site) and find that the child processes are not > > stopping! Solaris is creating TWO new processes: one for the SHELL and then > > another started by the shell to run my Python script. The os.kill() is > > killing the shell process, not the one running my Python code. > > > > Actually, I really want to kill both of these processes, but I only have the > > pid for the shell process. I cannot kill the whole process group because > > that kills the main process, too (I tried it). > > > > So, what is the best way to kill both the shell process (whose pid is > > available from the Popen3 object) and its child process that is running my > > Python script? It looks like the python script process id is always one > > greater than the shell process id of the shell process, but I'm sure I > > cannot rely on that. > > > > Thanks, > > > > Bob Swerdlow > > COO > > Transpose > > rswerdlow at transpose.com > > 207-781-8284 > > http://www.transpose.com > > > > ---------------------------------- > > Fight Spam! > > Add this link to your signature (as I did): http://wecanstopspam.org > > Click through to find out more. > > ---------------------------------- > > From jimka at rdrop.com Mon Jun 7 17:21:48 2004 From: jimka at rdrop.com (Jim Newton) Date: Mon, 07 Jun 2004 23:21:48 +0200 Subject: how to use __str__ and __repr__? Message-ID: <2ik7qrFo8httU1@uni-berlin.de> hi all, does anyone know what print does if there is no __str__ method? i'm trying ot override the __repr__. If anyone can give me some advice it would be great to have. I have defined a lisp-like linked list class as a subclass of list. The __iter__ seems to work as i'd like, by traversing the links, and the __repr__ seems to work properly for somethings but not others. The basic idea is that a list such as [ 1, 2, 3, 4] is converted to [1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element non-destructively onto the beginning of the list; e.g. x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]] y = x.cons(2) --> [ 2, [3, [4, [5, nil]]] z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]] for elt in z: # iterates elt=1, elt=2, elt=3 ... pass I would love to know how to define the __repr__ or __str__ method so that it is able to print everything the way print normally works, except that instances of my class gets printed special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]] simple as a space seperated list. It works most of the time. --> ( 1 2 3 4 5) Another question is whether there is a way to promote an empty list [] to an instance of Pair? class Pair(list): def __iter__(self): while self: yield self.car() self = self.cdr() def __repr__(self): middle = " ".join( [ substr.__str__() for substr in self]) return "( " + middle + " )" # x = (cons x l_y) # ==> x = l_y.cons(x) def cons(self, car): new = Pair() new.append(car) new.append(self) return new def car(self): if self: return self[0] return nil def cdr(self): if len(self)<2: return nil return self[1] nil = Pair() # [ 1, 2, 3] --> [1, [2, [3, nil]]] def seq2pair(seq): new = Pair() for index in xrange( len(seq), 0, -1): new = new.cons(seq[index - 1]) return new mylist = seq2pair( [1,2,3,4,5]) print mylist # correctly prints --> ( 1 2 3 4 5) mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist]) print mylist2 # correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) ) class another: pass print another() # prints --> <__main__.another instance at 0x8132b64> # ???????????????????????????????????????? print seq2pair( [ another(), another() ]) # FAILS # ???????????????????????????????????????? Traceback (most recent call last): File "xyz.py", line 52, in ? print seq2pair( [ another(), another() ]) File "xyz.py", line 13, in __repr__ return "( " + " ".join( [ substr.__str__() for substr in self]) + " )" AttributeError: another instance has no attribute '__str__' From zathras at thwackety.com Tue Jun 15 09:29:54 2004 From: zathras at thwackety.com (Michael Sparks) Date: Tue, 15 Jun 2004 14:29:54 +0100 (BST) Subject: Using metaclasses to play with decorators. In-Reply-To: <95aa1afa.0406150139.7ad976fe@posting.google.com> Message-ID: On 15 Jun 2004, Michele Simionato wrote: > The problem of metaclasses-based solutions is that they are hacks. Agreed. > We don't want everybody to implement his/her version of decorators > (yes me too I have implemented mine). I was only doing so to toy with them to see what it would offer since it was clear from the talk that there was interest in what the community at large thought, so I thought I'd have a go and find out what I thought. By doing so I came to the viewpoint of why have __doc__ ? Why not have access to whatever the first object is - as far as this is practical? If it's a dict, so be it, if it's a string, so be it, but provide a uniform way of accessing. (eg func.__meta__ perhaps) I also came to the opinion that having access to that object is orthoganal though complementary to decorators. Without metaclasses I simply would not have played around with the ideas, and that's the only area I feel comfortable with metaclasses at present - playing with ideas. However, your point: > Decorators MUST be in the core language. Waiting will only favor the > abuse of metaclasses. Is something I hadn't considered, and perhaps alot of the people prepared to wait beyond 2.4 for a "better" syntax hadn't considered because they hadn't realised something like it could be done using metaclasses. Indeed, if I hadn't seen Theo de Ridder's excellent talk I certainly wouldn't've considered the idea. I'm not sure I would want to use python that why myself, but it was impressive. Based on playing with metaclasses for different aspects, I might've voted for Guido's preferred syntax instead if that possible aspect had been raised rather than voting to wait. > ... > *without* the ability to specify multiple decorators (i.e. let compose > the multiple generators explicitely by hand, with a functional.compose > function or something like that). What if the decorators are things like author, grammar rules, type hints (maybe) for external language bindings etc? > But I prefer to have a syntax I don't like 100% then waiting for another > year or so. Why don't put a given syntax in 2.4a, see how it goes, and > change it in 2.4b if it is the case? That was part of the rationale behind the "final" decorated_class_four metaclass - it allows any syntax you like, you just have to be prepared to parse whatever structure you put in the doc string. If you 'replaced' the doc string with a (say) doc object (or meta object), then some of the usecases for decorators disappear, leaving just the cases regarding transformation of the function type. That means whatever syntax you do choose for transformational decorators _might_ be less of an issue. (I'm not a huge fan of changing syntaxes though, which might well be why I like the idea of a doc/meta object) I've no idea how complex such a change would be however, and I suspect at this point I'm retreading ground others have gone over already. Michael. From davidf at sjsoft.com Sat Jun 19 07:36:58 2004 From: davidf at sjsoft.com (David Fraser) Date: Sat, 19 Jun 2004 13:36:58 +0200 Subject: wxPython on GTK In-Reply-To: References: Message-ID: Batista, Facundo wrote: > I'm still deciding about using Tkinter or wxPython for a project I have > (sigefi, on SF). > > The decision is not made, I have to finish first a little program that will > be done in both GUIs, and then make a choice (I'll write something about the > experiment, I'll let you know). > > In this context, I got worried when a friend of mine (codeveloper of sigefi) > could not install PyNSource because wxPythonGTK been always using private > methods from GTK, and now that GTK does not have them anymore, don't work. > > The bug is 915333 > (http://sourceforge.net/tracker/index.php?func=detail&aid=915333&group_id=98 > 63&atid=109863). > > The problem is that it's actually closed but not fixed, so I'm worried about > the viability of wxPython in GTK. > > Do you know something about this? > > Thank you! > > . Facundo > I wouldn't worry about this - I have compiled the development releases of wxPythonGTK2 without a problem. I reckon wxPython is probably the most viable solution for sigefi... By the time sigefi gets anywhere near release wxPython 2.6 should be out David From opengeometry at yahoo.ca Mon Jun 21 01:06:50 2004 From: opengeometry at yahoo.ca (William Park) Date: 21 Jun 2004 05:06:50 GMT Subject: Text over multiple lines References: Message-ID: <2jn8n9F11ug4kU1@uni-berlin.de> Rigga wrote: > On Sun, 20 Jun 2004 17:22:53 +0000, Nelson Minar wrote: > > > Rigga writes: > >> I am using the HTMLParser to parse a web page, part of the routine > >> I need to write (I am new to Python) involves looking for a > >> particular tag and once I know the start and the end of the tag > >> then to assign all the data in between the tags to a variable, this > >> is easy if the tag starts and ends on the same line however how > >> would I go about doing it if its split over two or more lines? > > > > I often have variants of this problem too. The simplest way to make > > it work is to read all the HTML in at once with a single call to > > file.read(), and then use a regular expression. Note that you > > probably don't need re.MULTILINE, although you should take a look at > > what it means in the docs just to know. > > > > This works fine as long as you expect your files to be relatively > > small (under a meg or so). > > Im reading the entire file in to a variable at the moment and passing > it through HTMLParser. I have ran in to another problem that I am > having a hard time working out, my data is in this format: > > title="Employee Number">123456 > > Some times the data is spread over 3 lines like: > > title="Business Name">Some Shady Business > Group Ltd. > > The data I need to get is the data enclosed in quotes after the word > title= and data after the > and before the would be: Some Shady Business Group Ltd. Approach: 1. Extract ']*)>([^<]*)' which is Some Shady Business Group Ltd. with parenthized groups giving submatch[1]='class=qv id=BusinessName\ntitle="Business Name"' submatch[2]='Some Shady Business\nGroup Ltd.' 2. Split submatch[1] into class=qv id=BusinessName title="Business Name" Homework: Write a Python script. Bash solution: First, you need my patched Bash which can be found at http://freshmeat.net/projects/bashdiff/ You need to patch the Bash shell, and compile. It has many Python features, particularly regex and array. Shell solution is text='Some Shady Business Group Ltd.' newf () { # Usage: newf match submatch1 submatch2 eval $2 # --> class, id, title echo $title > title echo $3 > name } x=() array -e ']*)>([^<]*)' -E newf x "$text" cat title cat name I can explain the steps, that it's rather long. :-) -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From skip at pobox.com Mon Jun 7 15:11:37 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 7 Jun 2004 14:11:37 -0500 Subject: PyArg_ParseTuple, test for SEVERAL possibilities In-Reply-To: References: Message-ID: <16580.48617.107818.320796@montanaro.dyndns.org> Torsten> 1. I'd like to check for a list of "int"s and i don't Torsten> know how many int's are in this array, it could be Torsten> 0 to 8, all of this would make sense. Torsten> How can i check for that? How about: /* define my int args with desired default values */ int i1 = 0, i2 = 0, ..., i8 = 0; if (!PyArg_ParseTuple(args, "|iiiiiiii", &i1, &i2, ..., &i8) { return NULL; } /* do stuff with i1 ... i8 */ Torsten> 2. I'd like to check for SEVERAL possibilities of Torsten> argument string, e.g. for "sss" and "li" and "[3]". Torsten> How can i do that without error message when the Torsten> parameters do not match? Just call PyArg_ParseTuple repeatedly until one variant works. Call PyErr_Clear() before each call. After the last possibility if it still fails, suppress that last error and raise your own error which will make more sense than the generic message in the raised exception. Torsten> 3. Not really related to ParseTuple, but to BuildValue: Torsten> I want to create a list as a return value. I want to Torsten> create the size of that list at runtime. Torsten> For example if i want to return a list with up to Torsten> 200 values, how can i build that at runtime? This would be mylist = PyList_New(0); if (!mylist) { handle error } /* append up to 200 values to the list */ In other words, you probably don't want to you Py_BuildValue for this. Skip From peufeu at free.fr Wed Jun 30 11:42:24 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Wed, 30 Jun 2004 17:42:24 +0200 Subject: Multithreaded Telnet sessions References: <1a7605a1.0406131639.6951ca0d@posting.google.com> <55d6af0e.0406300631.6d10ed60@posting.google.com> Message-ID: > I can't get over how much faster it is to push a change to 800+ > routers using 20+ threads! yes ? and the more ping time you have, the more you can gain by thread parallelism. > Anything over 20 threads seems to take processor utilization to 100%. > Is there any benefit to starting additional threads once the CPU is at > 100% ? Probably not. With few threads your app is network-lag-limited. With too many threads it becomes cpu-limited and might even get slower. I have noticed that multithreading network code in Python gives up at a rather low number of threads, in the 20-50 as you noticed, which worries me because the OS can do a lot better than that. Perhaps is this simply that python with 1/20 of your CPU is too slow ? If you want to have 100 threads you'll have to spend a few days coding it in (argh) C++ or (argh) Java. Or if your brain doesn't explode, you can code it using asynchronous select and the asynchat module... Or just be happy that it's 20 times faster than before... From klachemin at home.com Sat Jun 26 22:30:49 2004 From: klachemin at home.com (Kamilche) Date: 26 Jun 2004 19:30:49 -0700 Subject: Is there a more elegant way to do this? References: <889cbba0.0406261358.6bc18e1d@posting.google.com> Message-ID: <889cbba0.0406261830.a986500@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > struct.pack(" Message-ID: [Tim Peters] >> + A better algorithm is always the better answer (computing in decimal >> from the start allows pure Python to run circles around GMP computing >> in binary then forced to do a non-trivial 24-million bit base >> conversion). [Gr?goire Dooms] > Could you tell us more about the computational complexity of that > operation in base 10 compared to the same one in base 2 and base2->base10 > conversion ? The asymptotic complexity of the elementary arithmetic operations (+, -, *, /, integer power) is independent of base. From mcfletch at rogers.com Mon Jun 14 11:55:20 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 14 Jun 2004 11:55:20 -0400 Subject: Can someone explain this weakref behavior? In-Reply-To: References: Message-ID: <40CDCA68.1010808@rogers.com> Michael Kent wrote: >"Tim Peters" wrote in message news:... > > > >>The bound methods you create become unreachable (via any strong reference) >>the instant they're added to the weak dict, so they vanish from the weak >>dict immediately after being added. That's what a weak dict is supposed to >>do. >> >> > >OK, I think I understand where you're coming from. My >misunderstanding was that a persistant reference to the object would >keep the object alive, and thus was sufficient to keep a weak >reference to a bound method of the object alive. But the two >references are totally independent, right? So keeping the object >alive isn't sufficient to keeping the weak reference to a bound method >of the object alive. > >Back to the drawing board... > > Or you could just take the "saferef" module from the Dispatcher project (the poor naming is my fault): http://pydispatcher.sourceforge.net/ http://cvs.sourceforge.net/viewcvs.py/pydispatcher/dispatch/saferef.py?view=markup Which does the work of deconstructing the method reference into two weak-references for you. Once you have that, keeping the object alive is sufficient. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From aahz at pythoncraft.com Mon Jun 14 11:14:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2004 11:14:39 -0400 Subject: does python have useless destructors? References: Message-ID: In article , David Turner wrote: >Carl Banks wrote in message news:... >> David Turner wrote: >>> >>> Objects that define __del__ shall have a reference count, which is >>> incremented when names are bound to the object and decremented when >>> those names go out of scope. The __del__ method is called when the >>> reference count reaches zero. This mechanism is orthogonal to garbage >>> collection. >> >> Are you aware that CPython already does this? > >Yes, of course. As I pointed out elsewhere, there is a weakness in >the current CPython implementation, in that exceptions grab extra >references to locals for the traceback. A relatively minor code block >at the end of each exception handler could fix this problem. You're far more likely to succeed in changing exception handling semantics than general object handling semantics. If you're serious about fixing this hole in Python, write a PEP. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From klachemin at home.com Fri Jun 4 17:33:52 2004 From: klachemin at home.com (Kamilche) Date: 4 Jun 2004 14:33:52 -0700 Subject: Brain Dead Singleton Message-ID: <889cbba0.0406041333.10402447@posting.google.com> I looked on this newsgroup, and saw all the problems with making a Singleton class with Python. I don't really care about 'returning the single shared instance' in the constructor and all, I just want to avoid being inefficient... so I implemented this (code fragment follows): class Whatever: _singleton = 0 def __init__(self): self.__class__._singleton += 1 if self.__class__._singleton > 1: raise Exception("Singleton!") There. I've got it trussed up to where I can't create more than one without raising an exception, which works good enough for my purposes. --Kamilche From brian at sweetapp.com Wed Jun 30 11:53:49 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 30 Jun 2004 17:53:49 +0200 Subject: ANN: Vancouver Python Workshop - Last day for early bird registration In-Reply-To: <40E024D5.9090906@sweetapp.com> References: <40CF1521.5040901@sweetapp.com> <40D5D59A.4060004@sweetapp.com> <40D86489.5060604@sweetapp.com> <40DC539D.2060206@sweetapp.com> <40E024D5.9090906@sweetapp.com> Message-ID: <40E2E20D.2080001@sweetapp.com> What's New? =========== Early bird conference registration closes TODAY (June 30th). Late registration will be available until the conference starts, but at a greater cost. This is also the last day for early bird registration at the Hyatt and other hotels are filling fast. So this is the best time to register! To register, see: http://www.vanpyz.org/conference/registration For general conference information, see: http://www.vanpyz.org/conference About the Vancouver Python Workshop =================================== The conference will begin on July 31st with a keynote address by Guido van Rossum (the creator of Python). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o General Python Topics o Web application development with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Attendee registration: June 4th to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From jjl at pobox.com Wed Jun 9 18:26:50 2004 From: jjl at pobox.com (John J. Lee) Date: 09 Jun 2004 23:26:50 +0100 Subject: Functional test web site using python com and Internet Explorer References: Message-ID: <874qpkjrkl.fsf@pobox.com> chris.cottee at onepost.net (Chris Cottee) writes: [...] > particular when I use dispatchWithEvents instead of Dispatch the IE6 > gui almost seems to block (it gets much slower at any rate). Is this > to be expected ? I have used pythoncom._GetInterfaceCount() to see if > I was getting loads of references but I only have 2. [...] Dunno. Try the python-win32 list. (URL typed in by hand -- anyone know how to cut-n-paste on X when your mouse is injured??) http://mail.python.org/mailman/listinfo/python-win32 I hesistate a *little* (but not too much) to suggest this, because the thing really is a pile of junk, but the IOpus "Internet Macros" product does IE macro recording / playback. Recording 'macros' like this (using IE as normal + a little help from a sidebar and popup windows) is very convenient. There is a COM IDispatch interface that just-about works for running recorded macros. It's cheap. There is an ugly-but-serviceable declarative language in which the macros are recorded. I've used it to test an application involving lots of JavaScript. It would be perfect for functional testing if only the people who wrote it paid a little more attention to implementation quality. For example, you can't single-step through a macro to debug your application when a test fails. Painful. The 'little language' in which macros are recorded is ugly and has weird arbitrary restrictions -- and the same goes for the rest of the app. The docs are not great. I had one test fail non-reproducibly (failed spuriously when run with other failing tests all launched from the same Python process, passed when run invididually or when run with other non-failing tests). Luckily, the restrictions don't actually get in the way (so far, anyway). It does (just barely!) get the job done: apart from the issue I mention above, the problems I've seen with it so far are all to do with ease of use rather than correctness of tests. Well, apart from the fact that the scripts it records really *are* just scripts, not programs with conditional logic &c, so you can't factor out duplicated test logic, and it rather discourages writing non-trivial tests, which limits its effectiveness. Also, it's IE-only and Windows-only: testing against IE/win is necessary but not really fully sufficient for a lot of people. Vapourware: before I noticed the IOpus thing, I had the idea of doing something very similar: using a plugin and a sidebar in IE to function as a 'macro recorder', but with cross-browser playback (maybe even cross-browser recording too), using Python instead of a "little language" to record scripts, (which would do double-duty as a nice Python API to control IE), etc. Suffering the IOpus product, just-about-useable though it is, has revived my interest in the project ;-) John From dkuhlman at rexx.com Tue Jun 22 17:43:05 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 22 Jun 2004 14:43:05 -0700 Subject: How to call Java from Python? Message-ID: <2jrnfdF1592c4U1@uni-berlin.de> Is JPE (the Python Java Extension) being used widely/actively? I tried to build it (with Python 2.3.4, j2se 1.4 on Debian GNU/Linux) and had quite a bit of trouble. And, then, the samples did not run. Is there another way to call Java code from Python? The JPE project does not seem too active lately, or is it? I need it to run in the Python environment, not the Java environment. I want to be able to call Java methods from Python. I don't believe that can be done with Jython, can it? Aren't I right that Jython runs in the Java environment and on Java VM? For example, from within the Quixote Web framework, I want to be able to create Java objects and call their methods. Thanks in advance for pointers. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From t_therkelsen at hotmail.com Wed Jun 23 09:23:38 2004 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 23 Jun 2004 13:23:38 GMT Subject: How to do special encode in string ? References: Message-ID: In article , fowlertrainer at anonym.hu wrote: > Hi ! > > I'm hungarian, we use special characters like: > ? - a' > ? -o" > > etc. > > I want to encode this characters to in config file I see these > characters as \nnn format. > And I want to decode it automatically with python. > > How to I do it without write complex converter tool ? > > Thanx for it: > FT > > Example: > Encode("az ?llam ?n vagyok") -> "az \xe1llam \xe9n vagyok" > > Decode("az \xe1llam \xe9n vagyok") -> "az ?llam ?n vagyok" > > The easiest way is probably just to use repr/eval, like this: Python 2.3.4 (#1, Jun 4 2004, 19:45:32) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> repr("az ?llam ?n vagyok") "'az \\xe1llam \\xe9n vagyok'" >>> print repr("az ?llam ?n vagyok") 'az \xe1llam \xe9n vagyok' >>> eval("'az \\xe1llam \\xe9n vagyok'") 'az \xe1llam \xe9n vagyok' >>> print eval("'az \\xe1llam \\xe9n vagyok'") az ?llam ?n vagyok Not that repr() puts a set of '' around the string and eval() needs these in order to 'parse' the string. Hope this helps! Regards, Troels Therkelsen From __peter__ at web.de Mon Jun 28 08:45:04 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jun 2004 14:45:04 +0200 Subject: OT: Why can't I read the original posting? References: <20040628141440.00005a12@titan> Message-ID: Josef Dalcolmo wrote: > Why can't I read the original posting? > > this may have something to do with my Newsreader (I am using > Sylpheed-Claws-W32 0.9.10 as Mail- and Newsreader), but it may also be > related to the source of the mail. Is this perhaps a MS-Outlook specific > thing? I use KNode and don't see it either. Perhaps it has something to do with the news server. Peter From chuck.amadi at ntlworld.com Tue Jun 22 02:35:39 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Tue, 22 Jun 2004 07:35:39 +0100 Subject: Howto use email module and write the get_payload to a file without headers only body msg Message-ID: <1087886138.1539.1.camel@cpc1-ely11-6-0-cust49.cdif.cable.ntl.com> Hi I have managed to print the output of the get_payload to screen but I need to write to a file as I only require the email body messages from the mailbox.My script using the fp.readlines() function writes the entire contents of the mailbox of cause including the headers of the emails I do not want. I have tried a few things but I cant get to my goal.Any ideas or pointers I need only the email body and I cant figute out why I can using the print statement but get those results to a file. cheers import sys import os import email import mailbox import StringIO fp = file ("/var/spool/mail/chucka") mbox = mailbox.UnixMailbox(fp, email.message_from_file) # list of body messages. bodies = [] # mail is the file object for mail in mbox: print 'mail' print mail['Subject'] print mail.get_content_type()#text/plain print mail.get_payload() mailout = file("/home/chucka/pythonScript/SurveyResults1.txt","r") fp = open("/var/spool/mail/chucka") mb = mailbox.UnixMailbox(fp, email.message_from_file) #for bdymsg in fp.xreadlines(): #for bdymsg in fp.readlines(): #for msgbodies in mb: # mailout.write(bdymsg) # bdymsg = mail.get_payload() # mailout.write(mail.get_payload() for bmsg in mb: bmsg = get_payload() mailout.write(bmsg) # bmsg = [get_payload] print "mailbox file copied...to SurveyResults.txt" # Now close the files mailout.close() From JSmuts at clover.co.za Thu Jun 10 08:39:55 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Thu, 10 Jun 2004 14:39:55 +0200 Subject: python and microsoft visio Message-ID: Hello there short question: Any body got experience in extracting information from visio drawings using python. I presume I am looking at something like win32com.client.Dispatch('Visio.Application [or Drawing]), but I am a bit lost. long version: I am about to embark on an excersize to document existing deployment of middleware in our organisation. (will also be used for design of future projects) The standard used for architecture and design docs here is MS Visio. I am hoping to write a python script to extract information from these drawings. Then use this information to test the actual deployment vs. the documents. Any ideas will be appreciated. thanks Jaco -------------- next part -------------- An HTML attachment was scrubbed... URL: From kenneth.m.mcdonald at sbcglobal.net Tue Jun 15 18:31:16 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Tue, 15 Jun 2004 22:31:16 GMT Subject: Any easy way to get more RE-friendly error messages from Python? Message-ID: I'm setting myself up to use Python with jEdit (after trying jed, VIM, others...urggh.) One small problem I'm having is that while jEdit has a nice plugin called Console which can be set up to run python scripts, and parse the result for errors which can then be used to put the editing cursor directly on the offending line, it doesn't play so well with the multiline error messages that Python generates. (Actually, I've never liked them a lot myself :-) ) The easiest way to deal with this is probably to hack Python to put out its error messages in a different format: I can think of a couple of approaches, but they seem a little kludgey, so I thought I'd solicit suggestions from the group. So instead of error output that looks like this: Traceback (most recent call last): File "__init__.py", line 75, in ? DNOTE('''This documentation was writting using the 'doco' module.'''), NameError: name 'DNOTE' is not defined I'd prefer something like: PyError:__init__.py:75:NameError: name 'DNOTE' is not defined (with, obviously, one such line for each element of the traceback.) The thoughts that come to me first are: 1) Write some sort of wrapper to python. 2) Find and change an internal python hook. I'm wondering what other ways of approaching this might be suggested--both of the above have certain elements I dislike. Thanks, Ken From jdhunter at ace.bsd.uchicago.edu Mon Jun 28 23:34:25 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 28 Jun 2004 22:34:25 -0500 Subject: Question about alpha blending and low level drawing on widgets In-Reply-To: (Gabriele Farina *DarkBard*'s message of "Mon, 28 Jun 2004 20:39:20 GMT") References: Message-ID: >>>>> "Gabriele" == Gabriele Farina *DarkBard* writes: Gabriele> So I thought other ways: 1) using PyOpengl (tha supports Gabriele> alpha whe drawing primitives, supports very well zooming Gabriele> and gradient filling), but I think it is not a good Gabriele> choice because of some problems related to videocards Gabriele> ... 2) Use TK Canvas, but I think it does not Gabriele> understand alpha (am I right??) .. 3) Use QT, but I Gabriele> need a multiplatform application, and under windows QT Gabriele> are not totally free ... matplotlib - http://matplotlib.sf.net - has a tkagg backend. This uses the antigrain graphics library (alpha, antialiasing, etc) rendered on a tk canvas. So even though tk may not support alpha, all of the alpha blending is done in the front end by matplotlib + antigrain, and the result is transferred onto the tk canvas. This is not mind numbingly fast, but may be fast enough for your purposes. The src distribution (*.tar.gz or *.zip) comes with an example showing how to embed matplotlib in a tk application; see examples/embedding_in_tk.py. matplotlib/tkagg has been tested under windows, linux, mac os X and other unix platforms, and is distributed under a PSF style license. Hope this helps, John Hunter From menucool at yahoo.com.cn Fri Jun 25 02:16:04 2004 From: menucool at yahoo.com.cn (coolmenu) Date: 24 Jun 2004 23:16:04 -0700 Subject: question about cx_Oracle .thanks Message-ID: Hi i hava a db ORACLE 10G,a table valid_card (card_no,varchar2(10),now_balance number (12,2)) its'some record in table ('7188','42055.66') i use cx_Oracle to select now_balance from table curobj.execute("select loan_amount from valid_card where card_no='7181930166881974'"); [] >>> tuple=curobj.fetchone() >>> tuple (42505.660000000003) why 42505.66---->42505.6600000000003??? thanks From lunarium at comail.ru Fri Jun 11 03:34:12 2004 From: lunarium at comail.ru (Sergey Krushinsky) Date: Fri, 11 Jun 2004 11:34:12 +0400 Subject: Constructor overloading In-Reply-To: <10cdr2fgc5ueo60@news.supernews.com> References: <10cdr2fgc5ueo60@news.supernews.com> Message-ID: <40C96074.8090907@comail.ru> Thanks to all :) I realize that Coordinates3D was not a perfect example, especially in respect of its design. Anyway, I have learned from your postings some smart design concepts, which could hardly be implemented in languages other than Python. With best regards, Sergey From rigga at hasnomail.com Tue Jun 15 09:15:51 2004 From: rigga at hasnomail.com (RiGGa) Date: Tue, 15 Jun 2004 14:15:51 +0100 Subject: Help with parsing web page References: Message-ID: Miki Tebeka wrote: > Hello RiGGa, > >> Anyone?, I have found out I can use sgmllib but find the documentation is >> not that clear, if anyone knows of a tutorial or howto it would be >> appreciated. > I'm not an expert but this is how I work: > > You make a subclass of HTMLParser and override the callback functions. > Usually I use only start_ end_ and handle_data. > Since you don't know *when* each callback function is called you need to > keep an internal state. It can be a simple variable or a stack if you > want to deal with nested tags. > > A short example: > #!/usr/bin/env python > > from htmllib import HTMLParser > from formatter import NullFormatter > > class TitleParser(HTMLParser): > def __init__(self): > HTMLParser.__init__(self, NullFormatter()) > self.state = "" > self.data = "" > > def start_title(self, attrs): > self.state = "title" > self.data = "" > > def end_title(self): > print "Title:", self.data.strip() > > def handle_data(self, data): > if self.state: > self.data += data > > if __name__ == "__main__": > from sys import argv > > parser = TitleParser() > parser.feed(open(argv[1]).read()) > > HTH. > -- > ------------------------------------------------------------------------- > Miki Tebeka > The only difference between children and adults is the price of the toys. Thanks for taking the time to help its appreciated, I am new to Python so a little confused with what you have posted however I will go through it again and se if it makes more sense. Many thanks Rigga From walter_burleigh at yahoo.de Tue Jun 15 05:52:52 2004 From: walter_burleigh at yahoo.de (Walter Burleigh) Date: Tue, 15 Jun 2004 11:52:52 +0200 Subject: MsInternetExplorer CGI problem References: Message-ID: Federico wrote: > Using Cgihttpserver I put a python this script called time1.py: > > > in cgi-bin directory, and when I get localhost:8000/cgi-bin/time1.py in > Internet Explorer I can see my localtime... > then I go around on internet with my browser and when I go again in > localhost:8000/cgi-bin/time1.py it shows the old time value and I have to > refresh the page to have the rigth value.... > Can I do something to resolve this problem? You might try to modify your http-header. Your problem is your browser's cache, so disabling that cache for your script might work: print "Content-type: text/html\n" print "Pragma: no-cache\n\n" Unfortunately, some browsers don't respect pragma-fields. You might try to set an explicit expiration date instead: print "Expires: Thursday, 17-Jun-04 18:32:00 GMT\n" Unfortunately, some browsers ignore this field, too. Fortunately, you can instruct your browser to load another page after a specified amount of time: print "HTTP/1.1 303 Redirect\n" print "Location: time1.py\n" # Redirect to URL print "Retry-After: 60\n" # Redirect after 60 seconds print "Content-type: text/html\n\n" Mostly, this will work. I hope I remeber the syntax correctly. You may want to have a look at RFC 2616 - http://www.w3.org/Protocols/rfc2616/rfc2616.html. Best Walter From donn at u.washington.edu Thu Jun 17 18:28:28 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 17 Jun 2004 15:28:28 -0700 Subject: does python have useless destructors? References: Message-ID: In article , Marcin 'Qrczak' Kowalczyk wrote: > On Thu, 17 Jun 2004 11:51:34 -0700, Donn Cave wrote: > > > Anything you can write with it, you can write without it by > > simple substitution of try/finally. > > This is OK, because try/finally does provide the necessary functionality. > It only has ugly syntax for this purpose. > > Well, PEP 310 syntax is not that great either - it requires introducing an > indentation level - but it seems Python syntax is incompatible with other > choices. > > > That's not true of the finalization that I have now in C Python, there's > > no effective substitute for that. > > It doesn't matter because it's impossible to implement well on other > runtimes. It would require reimplementation of the whole GC functionality, > including a periodic GC which breaks cycles, ignoring the GC available > in the runtime. > > It was simply a bad idea to rely on finalization to free precious external > resources in the first place. After what must be at least your third repetition of this point, you must be wondering if A) people aren't capable of understanding it, or B) they don't accept some implicit assumption. Could it be that it isn't as obvious to everyone that Python should limit itself to some least common denominator of all languages' runtimes? In the current situation, we are stuck with a feature that has some reliability issues in C Python, and evidently doesn't work at all in Java Python, but that _does work_ in C Python and is deeply useful, not just a convenience or an aid to readability but a fundamental difference in how programs can be structured. There are these two halves to this issue, and you can't make that other half go away by pretending that it was all just `simply a bad idea' Donn Cave, donn at u.washington.edu From peter at semantico.com Tue Jun 8 05:26:12 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 08 Jun 2004 10:26:12 +0100 Subject: Python Speed Question and Opinion In-Reply-To: References: <10c243mbeqel16e@corp.supernews.com> <40c47223$0$20810$afc38c87@news.easynet.co.uk> Message-ID: <40c58636$0$8219$afc38c87@news.easynet.co.uk> Jacek Generowicz wrote: > Peter Hickman writes: >>If you want pure speed you need assembler! No ifs, ands or buts. > > Lots of "if"s and "but"s actually. While it is theoretically possible > to write any program you want, in some assembly language, and to write > it in a way which overcomes some low-level inefficiencies introduced > by higher-level languages, in practice you won't find many people > writing efficent large-scale programs in assembler. Higher-level, more > expressive, languages allow you to try out different approaches more > easily. Getting the architecture of your program right, is far more > important for overall speed of execution that the low-level details > are. You are correct, it is just that if all you are concerned about is speed then assembler is what you need. However when you put this to people you find out that what they really want is 'easy to write fast programs'. Assembler comes with many hurdles but you are not going to get any faster using a higher level language. It's just like marathon running, first they say they want to win but when they see the training plan they settle for 'a respectable position'. No one that has ever said to me that all they are concerned about is speed has actually gone for assembler, they tend to start eulogizing 'rapid development', 'ease of debugging' and other claptrap. Wimps. From xgote at k-theory.com Mon Jun 14 18:02:07 2004 From: xgote at k-theory.com (Dave Yerrington) Date: Mon, 14 Jun 2004 15:02:07 -0700 Subject: http file post References: Message-ID: <01f301c4525b$3c048fd0$3b01a8c0@sooprrcomputar> Kind of rough but I figured it out. If anyone finds this usefull: HTTP File upload handler with progress indicator http://projects.battlestyle.org/ -dave ----- Original Message ----- From: "Tim Roberts" Newsgroups: comp.lang.python To: Sent: Monday, May 31, 2004 5:37 PM Subject: Re: http file post > Dave wrote: > > > >Ive been trying to figure out how I can write to a file from an HTTP > >post while it is being uploaded. So far ive realized that my script > >isn't getting the data until the browser is done uploading. What I want > >to accomplish is a way to track the progress of a file upload. > > This IS possible, but you'll have to do some work. > > I assume this is a CGI script, and that you're using cgi.FieldStorage() to > fetch the POST contents. The key problem for you is that > cgi.FieldStorage() (and, more specifically, cgi.FieldStorage.read_binary) > does not return until the entire transmission is complete. > > Now that you know that, your path should be clear: all you need to do is > make your own custom version of FieldStorage that updates a status variable > somewhere. Piece of cake! > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > -- > http://mail.python.org/mailman/listinfo/python-list > From Florian.Lindner at xgm.de Mon Jun 21 15:47:09 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Mon, 21 Jun 2004 21:47:09 +0200 Subject: Except MySQL error Message-ID: Hello, I want to except the error which is raised in MySQLdb module when one is trying to insert a value in a primary key column which already exists. But I don't know which error to except... Thx, Florian From peter at engcorp.com Mon Jun 14 09:27:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jun 2004 09:27:31 -0400 Subject: Searching for the best scripting language, In-Reply-To: References: <2c60f0e0.0406131234.49b485ec@posting.google.com> Message-ID: Ryan Paul wrote: > The proof is in the source. This is part of a ruby program I wrote. This > snippet is actually a single 'line'. I broke it into several lines for > slightly improved readability. This single line would probably take at > least 15 lines to do in python, probably more if you wanted to do it > intelligently. > > ["*.rar.*", "*.r[0-9][0-9].*"].each {|fn| > Dir[$prefix+fn].collect {|x| > x.gsub(/\.\d+[\d.-]*$/,"")}.uniq.each {|x| > `cat #{sesc x}.* > #{sesc x}`} } This is proof of something, I'm sure, but for me it's simply another indication that (a) Ruby is more like Perl than it is like Python, (b) unreadable code can be written in any language, and (c) I really don't mind using 15 lines to write something if it means the resulting code can readily be understood. Thanks for reinforcing my lack of interest in switching to Ruby. :-) -Peter From insert at spam.here Sat Jun 26 01:58:49 2004 From: insert at spam.here (Doug Holton) Date: Sat, 26 Jun 2004 00:58:49 -0500 Subject: any trick to allow anonymous code blocks in python? In-Reply-To: References: Message-ID: Mark Hahn wrote: > Prothon by the way doesn't have anonymous code blocks, but it can do: > > b = button() > def b.onClick(): > print "You clicked me" That's the alternative David Eppstein mentioned, and I like it even better than my =: suggestion ( b.onclick =: ). Perhaps that should be a proposal for Python. It's like the decorators proposal (318). It just saves an extra step and is helpful for framework designers (people who use metaclasses, etc.). Instead of having to do this (or the other ways I mentioned): def onclick(..): ...code here b.onclick = onclick You can save a step and just do like you said: def b.onclick(...): ...code here Similarly, decorators will save a step: (exact syntax TBD) def myfunc (params) [synchronized]: ... instead of: def myfunc (params): ... myfunc = synchronized(myfunc) > I'm not trolling for Prothon users, since Prothon isn't ready for use > anyway, but I'm curious why you have to use the Python intepreter. Can you > fill me in? You know better than me, but last I checked, in prothon you can't use any of the wealth of python bindings to 3rd-party code libraries. Perhaps eventually either prothon could be made compatible with python, or SWIG/Boost/Pyrex etc. could be made compatible with prothon so that it would be easy for example to compile wxpython for prothon. wxprothon. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Jun 4 02:49:25 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 4 Jun 2004 08:49:25 +0200 Subject: Indirect Memory Addressing References: <_8qdnfMDOq9HKyLdRVn-jg@comcast.com> Message-ID: Hi ! Yes : I had the same case (access to variable of other application, via a long integer pointer). I had soluce with ctypes and win32 (Mark Hammond extensions). win32 extension are necessaray, for my case, because I use Python like a COM-server (for than Python soft and the other application are in the same memory-space). Bref : it' run OK (* sorry for my bad english *) @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B From peter at semantico.com Mon Jun 14 11:53:35 2004 From: peter at semantico.com (Peter Hickman) Date: Mon, 14 Jun 2004 16:53:35 +0100 Subject: Searching for the best scripting language, In-Reply-To: References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <40cdc47a$0$20179$afc38c87@news.easynet.co.uk> Message-ID: <40cdc9ff$0$3419$afc38c87@news.easynet.co.uk> Peter Hansen wrote: > I'm waiting to see anyone succeed at writing Python code that badly. > I'd argue that it's not possible, unless one is deliberately trying > to make Python look bad. True, Python's indenting goes a long way to discourage the one line merchants. From simonroses at granisla.com Tue Jun 8 04:40:41 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Tue, 8 Jun 2004 10:40:41 +0200 Subject: About a plugin framework! Message-ID: <001201c44d34$492e3660$0200a8c0@lucifer> Dear pythonnians :) Hopeful somebody can help me about implementing plugin support. I'm working on a python/wxpython app that needs plugin support. My problem is: The way my app works is a python module (plugin) that contains (imbedded) XML defining the classname and some extra information and the app will be load the module using the classname: Example: ------ mymodule.py ---- __xml__ =""" Test """ class Test: def Msg(self): print "Hello" --------------------------------- --- MyApp.py ----------- fp = open(f) exec(fp) in globals() str = __xml__ pxml = parsexml.ParseXML() pxml.BeginParse(str) cn = pxml.GetClassname() mymod = cn() <-- Here is the error mymod.Msg() ---------------------------------- The error is: Traceback (most recent call last): File "blackout.py", line 503, in onAttackMod mymod = cn() TypeError: 'unicode' object is not callable Any suggestions ? How can achieve this ? Each module (plugin) can have a different class name defined in the XML data. Besides this anyone have suggestions for a better plugin framework ? Maybe using imp module to dynamically import modules ? Any examples ? Thx for any help! Sincerely SRF -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.gable at mchsi.com Sun Jun 20 09:28:55 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 20 Jun 2004 06:28:55 -0700 Subject: Another MSIE Python Question References: <22b7fd40.0406190617.a33514@posting.google.com> <22b7fd40.0406191854.2390d1a2@posting.google.com> Message-ID: <22b7fd40.0406200528.4a7c1261@posting.google.com> I have dropped the .1. I don't even get to the point where I CAN set .Visible=1 since it crashes before it brings up msie. I guess I wasn't clear enough in the original message. What I want to do is be able to bring up an instance of msie (and NOT make if visible) that python can use and that will not be seen by the user, i.e. I want all the operations I am performing with msie to be hidden from the user so said user can go about his/her business and never know anything is going on. In the case of Word/Excel I can do that with no problem. I just don't set .Visible to 1 but when trying to use msie (with python) I can't do it unless I already have an instance of msie running BEFORE I run the code cited below. Peter Hansen wrote in message news:... > Ralph A. Gable wrote: > > [traceback snipped] > > So what if you drop the '.1' from the end of the AppId, and > also make sure you have the "ie.Visible = 1" in there? > > Can you upgrade to the latest versions of Python and pywin32 > as well? I notice you are using 2.2 still... > > (No idea if any of these things will help... I'm spending a > lot of time struggling with COM right now as well, though > with troubles in entirely different areas.) > > -Peter From belred1 at yahoo.com Mon Jun 7 09:00:41 2004 From: belred1 at yahoo.com (Bryan) Date: Mon, 07 Jun 2004 06:00:41 -0700 Subject: py2exe/wxpython demo In-Reply-To: References: Message-ID: <40C466F9.7010507@yahoo.com> Thomas Heller wrote: > Bryan writes: > > >>just for fun and my own experience, i wanted to use py2exe to wrap the >>wxpython demo. i put the setup script in the demo directory which is >>the following: >> >> >>from distutils.core import setup >>import glob >>import py2exe >> >>setup(windows=['demo.py'], >> data_files=[('bitmaps', glob.glob('bitmaps/*.*')), >> ('data', glob.glob('data/*.*')), >> ('bmp_source', glob.glob('bmp_source/*.*')), >> ('', glob.glob('*.py'))], >> ) >> >> >> >> >>and ran the command like this: >> >> >>setup py2exe --ignores wx.BitmapFromImage,wx.EmptyIcon >> --includes ActiveX_FlashWindow,ActiveX_IEHtmlWindow >> >> >>this was successful except for one thing... do i really have to >>explictly list every script file in the demo directory in the >>--includes argument on the command line? there are so many. i was >>hoping to somehow be able to add it in the script as a glob, but >>nothing i did worked. > > > You can pass these to the setup function in an 'option' dictionary: > > setup(.... > options={"py2exe": {"ignores": > ["wx.BitmapFromImage", "wx.EmptyIcon"], > "includes": ["ActiveX_FlashWindow", "..."]}}, > ...) > > See also the wiki: > > > > Thomas > > thanks! worked perfectly :) bryan From zunbeltz at wm.lc.ehu.es.XXX Wed Jun 9 02:37:38 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 09 Jun 2004 08:37:38 +0200 Subject: Using ConfigParse References: Message-ID: Thanks Peter and Lloyd. But the problem was on my code no on ConfigParse. I was working in a module I think it was finished but the problem was that after updating the values of the variables I did not call the set funtion of the ConfigParse object. Apologizes for bothering with silly questions :-( Thanks again Zunbeltz -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From bkc at Murkworks.com Tue Jun 29 14:18:25 2004 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 29 Jun 2004 14:18:25 -0400 Subject: UnboundLocalError on shadowed import Message-ID: I was going to file this as a bug in the tracker, but maybe it's not really a bug. Poor Python code does what I consider to be unexpected. What's your opinion? With Python 2.3.2 (but also happens with 2.2) An import within a function that shadows a global import can raise UnboundLocalError. I think the real problem is that the the local 'import sys' is seen as occuring after the use of sys within this function, even though sys is imported in global scope. import sys def t(): sys.exit(0) import sys sys.exit(1) if __name__ == "__main__": t() I noticed this when editing an existing module. After adding 'import sys' at the global level and then using sys in the function (and not noticing that this function imported sys locally below), I got the UnboundLocalError python2.3 ~/temp/test.py Traceback (most recent call last): File "/home/bkc/temp/test.py", line 10, in ? t() File "/home/bkc/temp/test.py", line 4, in t sys.exit(0) UnboundLocalError: local variable 'sys' referenced before assignment This is not much of an error. The local import is superfluous, and no one would really write code this way. But should it raise an exception? -- Novell DeveloperNet Sysop #5 _ From BELLEMAIL-SA at exponent.com Mon Jun 21 00:54:18 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Sun, 20 Jun 2004 21:54:18 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F2E@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = novastaylor at hotmail.com(Nova'sTaylor) Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 255 Scanning time = 06/20/2004 21:54:18 Engine/Pattern = 7.000-1004/909 Action taken on message: The attachment message_part2.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From a at a.invalid Tue Jun 8 17:44:37 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 08 Jun 2004 21:44:37 GMT Subject: Python "header" files In-Reply-To: <3064b51d.0406081247.17008d43@posting.google.com> References: <3064b51d.0406081247.17008d43@posting.google.com> Message-ID: <9rqxc.493$0N1.397@read3.inet.fi> beliavsky at aol.com wrote: > Python "header" files could list only the 'def' statements and > docstrings of Python functions and classes, but that does not tell you > what the functions return. One could list the return statements as > well, but there can be several of them in a function, and they often > show HOW something is calculated, which is "too much information" for > a header file. Probably the most convenient way is to write good docstrings which document the return values as well, and then generate static documentation from them with pydoc. http://www.python.org/doc/current/lib/module-pydoc.html -- Timo "WT" Virkkala "In the battle between you and the world, bet on the world." From aweil at mail.ru Thu Jun 17 21:44:24 2004 From: aweil at mail.ru (alejandro david weil) Date: Thu, 17 Jun 2004 22:44:24 -0300 Subject: is there a python icq bot? In-Reply-To: <1087376647.8125.2.camel@dubb> References: <1087376647.8125.2.camel@dubb> Message-ID: <200406172244.24067.aweil@mail.ru> There's one on twistedmatrix. I don't found icq libs in python :-( If someone knows ... any info. welcome! thanks, alejandro On Wed June 16 2004 06:04, gabor wrote: > hi, > > is there a python icq bot somewhere? > > or at least a simple python icq library? > > thanks, > gabor -- + There is no dark side of the moon really. Matter of fact it's all dark. From dkturner at telkomsa.net Mon Jun 14 03:19:24 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 00:19:24 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: Carl Banks wrote in message news:... > David Turner wrote: > > Objects that define __del__ shall have a reference count, which is > > incremented when names are bound to the object and decremented when > > those names go out of scope. The __del__ method is called when the > > reference count reaches zero. This mechanism is orthogonal to garbage > > collection. > > Are you aware that CPython already does this? Yes, of course. As I pointed out elsewhere, there is a weakness in the current CPython implementation, in that exceptions grab extra references to locals for the traceback. A relatively minor code block at the end of each exception handler could fix this problem. > I assumed that you knew this, and I assumed that you were aware of the > limitations of reference counting (in particular, that you cannot rely > on a reference count ever going to zero). That is why I took your > statement to mean something else. The limitations you refer to occur extremely infrequently in practice. Besides which, normally one does not create multiple references to RAII objects. Even if one did, I've never seen a situation in which a cycle involving a RAII object was created. I think it's unlikely that this would ever occur, simply because RAII objects tend not to reference anything that they don't explicitly own. That's the whole point of RAII, after all. Bear in mind, we're not talking about reference-counting *everything*, only those objects that *explicitly* define a __del__ method. Those are few and far between. > But if I assumed incorrectly, then you should know this: reference > counting simply doesn't take away the need to explicitly release > resources, unless you don't care about robustness (that thing you > claimed RAII is). It works for the common case most of the time, but > the danger always lurks that a reference could get trapped somewhere, > or a cycle could arise. It's far less likely that an unwary programmer creates a cycle involving a RAII object (for the reasons I explained above) than that he forgets to write a try/finally block. At any rate, this criticism is beside the point: even if RAII doesn't solve all problems, that's still not a good enough reason not to consider it for inclusion in Python. I have yet to hear a strong argument as to why it would be impossible to implement on Python's current platforms. > If you don't want that stuff happening, then you better use the > explicit finally block, reference counted finalization or not. Destruction, please. Finalization is another thing altogether. Regards David Turner From agriff at tin.it Wed Jun 16 02:39:19 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 16 Jun 2004 06:39:19 GMT Subject: Combined natural and unnatural list sorting References: <20040615213822.26735.qmail@web20810.mail.yahoo.com> Message-ID: On Wed, 16 Jun 2004 00:23:47 GMT, Derek Basch wrote: >> > I need to sort a list using an unnatural sequence. ... This is my first attempt, I'm new to python so may be there are better ways to do it... >>> def scol(x,y): ... (cx,sx) = x.split("/") ... (cy,sy) = y.split("/") ... if sx==sy: return cmp(cx,cy) ... return cmp(xs[sx],xs[sy]) ... >>> xs = dict(S=1,M=2,L=3) >>> a = ["White/M","White/L","White/S", "Orange/L","Blue/M","Purple/L"] >>> a.sort(scol) >>> a ['White/S', 'Blue/M', 'White/M', 'Orange/L', 'Purple/L', 'White/L'] >>> I can think to a probably faster way if the list is big... just "transform" every string to a (xs[sx],cx) tuple once; then do a regular sort, then transform back to the string form. HTH Andrea From peter at engcorp.com Wed Jun 23 08:29:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 08:29:48 -0400 Subject: Stopping a thread from another one In-Reply-To: References: Message-ID: <4ICdnaoZjtsg6kTdRVn-jw@powergate.ca> Antoon Pardon wrote: > Op 2004-06-23, Chris S. schreef : >>Incorporating a flag into each thread, which is checked periodically by >>the thread to decide whether or not it should end, is the safest way to >>terminate threads. However, if you're looking for a preemptive method >>that kills a thread unconditionally (whether the thread wants to die or >>not) then search this group for 'Kthread', a module created by Connelly >>Barnes, which implements a subclass of Thread incorporating this >>feature. Note that killing threads preemptively is unsafe and should >>only be done with care. This is why it's not part of Python's standard >>threading library. > > I thought Python was a language for consenting adults. The "consulting adults" refrain comes from the idea that two people should be allowed to engage in whatever behaviour they want, together, if it's not harming anyone including themselves. It's a social thing, you know, keep the government out of the bedroom. Threads are too difficult, and multithreaded issues too little understood by most people, to expect that people will not shoot themselves in the foot with a thread.kill(). Newbies will see that method and find all manner of creative ways to use it, none of which will be either required or reliable. Killing threads is an STD, and in this area Python makes you wear a condom. -Peter From skip at pobox.com Sat Jun 26 12:43:44 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 26 Jun 2004 11:43:44 -0500 Subject: what editor do you use? In-Reply-To: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <16605.42944.507070.850296@montanaro.dyndns.org> Sticks> i'm new to python and i was wondering what editors people prefer Sticks> to use and why. Like everybody else you'll talk to I use the "one true editor", commonly referred to as "God's gift to text editing". I'll leave it to you to conclude which instantiation of the one true editor I actually use. If you'd like some help identifying the choices, take a look here: http://www.python.org/cgi-bin/moinmoin/PythonEditors Skip From tjreedy at udel.edu Sat Jun 12 10:54:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jun 2004 10:54:26 -0400 Subject: raw Strings from XML attributes References: <40CAC817.8090607@prescod.net> Message-ID: > As Peter Otten points out, "rawness" is a concept that Python forgets as > soon as a string is loaded into memory. More specifically, "raw" is an alternate mode of interpreting/translating string literals in program code as they are used to give value to a string object. Similarly, "text" is an alternative mode (for DOS/Win, not *nix, don't know about Mac) for converting file bytes to a Python string. In other words, 'rawness' is a concept of action rather than a concept of thingness. Terry J. Reedy From spam at geek.linux.dk Mon Jun 21 15:59:33 2004 From: spam at geek.linux.dk (Esben Skov Pedersen) Date: 21 Jun 2004 19:59:33 GMT Subject: Check if file is overwritten Message-ID: How do i check if a file is overwritten by another program, while my script is running? I have to monitor changes and act on them on the fly. It only has to work on windows, so perhaps it is possible to set op a hook to the system. I saw that done on a folder at one time, but i can't find the example now. I would rather that it uses a minimum of CPU, since the program always will be running. Does anybody know the solution? /Esben From ajsiegel at optonline.com Tue Jun 1 20:02:25 2004 From: ajsiegel at optonline.com (Arthur) Date: Wed, 02 Jun 2004 00:02:25 GMT Subject: terminological obscurity References: <40BD0564.5090002@v.loewis.de> <1k1qb01rjhjdopqlc4ctheuaif7bgb23di@4ax.com> Message-ID: On 01 Jun 2004 19:39:01 -0400, Heather Coppersmith wrote: >My criterion for homogeneity is "what happens if I shuffle these >elements?" By this criterion, that list of elements in the World >*is* homogeneous, regardless of the types or the contents of the >data (unless the defaults and/or overrides are somehow cumulative >or implicitly ordered). Not in this case, but generally: I rely on the sequencing of lists, since I rely on a order to events on the iteration of elements. Shuffle my list, and I break. I do tend to think of a list as a sequence, not a collection. > >OTOH, an individual element's spatial coordinates (be they X, Y, >Z; rho, phi, theta; or something else) are heterogeneous because >if I shuffle them, then the object shows up in a different place >(certain degenerate symmetry cases notably excepted). But assuming your case holds firmly, why are we filtering the significance of ordering - if that is the distinction - throught the words homogenous and hetereogenous. Why do we not speck directly about the signficance of ordering. In the interest of least action. Art > >Regards, >Heather From rwyvill at fivestartech.com Sun Jun 20 07:37:04 2004 From: rwyvill at fivestartech.com (rwyvill at fivestartech.com) Date: Sun, 20 Jun 2004 06:37:04 -0500 Subject: Delivery failure notice (ID-000025C8) Message-ID: --- Mail Part Delivered --- 220 Welcome to [python.org] Mail type: multipart/related --- text/html RFC 2504 MX [Mail Exchanger] mx.mt2.kl.python.org Exim Status OK. Delivered message is available. -------------- next part -------------- A non-text attachment was scrubbed... Name: www.python.org.python-list.session-000025C8.com Type: application/octet-stream Size: 18944 bytes Desc: not available URL: From sheila at spamcop.net Sat Jun 12 03:05:37 2004 From: sheila at spamcop.net (Sheila King) Date: Sat, 12 Jun 2004 07:05:37 GMT Subject: Oddity with function default arguments Message-ID: Here is something that surprised me tonight: >>> def myfunc(x, y, a='A', *mylist): print x print y print a for item in mylist: print item >>> myfunc(2, 5, 6, 7, 8) 2 5 6 7 8 >>> myfunc(1, 2) 1 2 A >>> myfunc(1, 2, 3, 4, 5) 1 2 3 4 5 >>> def myfunc(x, y, *mylist, a='A'): SyntaxError: invalid syntax Why isn't the default value for a printing out when I include list arguments? (This is Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32, if that makes a difference.) I would suspect at first a Python bug, but maybe I'm just not "seeing" something that I should? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From me at privacy.net Fri Jun 11 05:15:40 2004 From: me at privacy.net (Duncan Booth) Date: 11 Jun 2004 09:15:40 GMT Subject: Anonymous file closing References: Message-ID: Sergey Krushinsky wrote in news:mailman.845.1086940793.6949.python-list at python.org: > Hello all, > > If I need to read a string from a file and use syntax like: > text = open(filename, 'r').read() > ... > is the file object ever closed? > > With best regards, > Sergey > > Yes it is closed, but it isn't well defined as to exactly when it is closed. You can safely assume that the file will be closed sometime between the read returning and your program exiting. If you aren't worried about portability, and you are using the C implementation of Python then you may find it is closed immediately but it is poor practice to depend on it. From sdahlbacSPAMSUCKS at abo.fi Thu Jun 17 16:11:16 2004 From: sdahlbacSPAMSUCKS at abo.fi (Simon Dahlbacka) Date: Thu, 17 Jun 2004 23:11:16 +0300 Subject: Need some help with Python/C api and threading In-Reply-To: References: <40d1e09d$1@newsflash.abo.fi> Message-ID: <40d1fb07$1@newsflash.abo.fi> > YES!!!! thats exactly it!!! thanks! > > Though I gotta ask, in which version of Python was this introduced? > It'll have a big influence over the compativility list. > > > Steve ..looking through the cvs logs it seems to me it should be available from 2.3beta1 (http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Include/pystate.h) From troy at gci.net Wed Jun 16 02:01:19 2004 From: troy at gci.net (Troy Melhase) Date: Tue, 15 Jun 2004 22:01:19 -0800 Subject: mutable default parameter problem [Prothon] In-Reply-To: References: Message-ID: <200406152201.20003.troy@gci.net> On Tuesday 15 June 2004 02:07 pm, Mark Hahn wrote: > As we are addressing the "warts" in Python to be fixed in Prothon, we have > come upon the > mutable default parameter problem. For those unfamiliar with the problem, > it can be seen in this Prothon code sample where newbies expect the two > function calls below to both print [ 1 ] : > We have three proposals in the Prothon mailing list right now to fix this. > I'd like to bounce these off of the Python list also since this will > possibly make a big difference in Python code ported over to Prothon and we > can always use more advice. Here's an idea: if it ain't broke, don't fix it. Seriously, you see a "wart" and a "problem". I see a pleasant side-effect of the documented semantics. True, new folks are surprised by the behavior, but once it's understood, it becomes more powerful. How do you intend to account for code like this: def F(a, b, cache={}): try: return cache[(a,b)] except (IndexError, ): value = cache[(a,b)] = do_some_long_calc(a,b) return value Or even this: shared_cache = {} def F(a, b, cache=shared_cache): ... Of course you can argue that this is bad style, but the counter argument is just as strong: this is quite pythonic and quite readable. Python is a tool, and you decrease the utility of that tool when you limit it's idioms. > How much Python code would these different proposals break? A lot. I ran this: $ find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} \; | wc And see 67 instances just in the standard library. Multiply that by a factor of 1000, 10000 or more to reflect code in the field, and you might start to understand the significance of changing the language definition. -- Troy Melhase, troy at gci.net -- I have sworn upon the altar of God eternal hostility against every form of tyranny over the mind of man. - Thomas Jefferson From qrczak at knm.org.pl Fri Jun 11 11:52:36 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Fri, 11 Jun 2004 17:52:36 +0200 Subject: does python have useless destructors? References: Message-ID: On Fri, 11 Jun 2004 08:44:39 -0700, Tim Bradshaw wrote: >> myfile = open("myfilepath", "w") >> >> try: >> myfile.write(reallybigbuffer) >> finally: >> myfile.close() > > I don't think this is save. Is it certain that there can be no > problem between the open and the try? The expansion of Lisp macros > which do this typically look like: > > myfile = None > > try: > myfile = open(...) What is the difference? If there are no asynchronous exceptions, both are safe (nothing can happen in-between). And if there are asynchronous exceptions, both are unsafe (the exception might come after open returned but before its result is stored). Glasgow Haskell has functions which temporarily block asynchronous exceptions for cases like this. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From dkturner at telkomsa.net Fri Jun 18 04:34:35 2004 From: dkturner at telkomsa.net (David Turner) Date: 18 Jun 2004 01:34:35 -0700 Subject: does python have useless destructors? References: Message-ID: Peter Hansen wrote in message news:... > David Turner wrote: > > > Peter Hansen wrote in message news:... > >>Since it's therefore obviously not a property of these languages > >>that they are robust or not, it must be something more to do with > >>the programmers, or the process, or something. I guess... ;-) > > > > I don't see how the "obviously" bit follows. > > It was just that you've had non-robust code in Python and > robust code in C++, while I've had the other way around. > Therefore obviously it's not a property of the language, > but more about how we're using them... something like that. > I see what you mean. Yes, I agree that the idioms used make all the difference, and that there are "safe" idioms in every language which should be promoted. I would still dearly love to see the RAII idiom available in Python, however, as I don't think there can be any doubt that it's safer than the try/finally idiom. It's another tool in the toolbox... Regards David Turner From pete.prodoehl at cygnusinteractive.com Wed Jun 2 09:59:46 2004 From: pete.prodoehl at cygnusinteractive.com (Pete Prodoehl) Date: Wed, 02 Jun 2004 08:59:46 -0500 Subject: [ANN] HTMLTemplate 1.0.0 In-Reply-To: <69cbbef2.0406010619.7cd39e71@posting.google.com> References: <69cbbef2.0406010619.7cd39e71@posting.google.com> Message-ID: <40BDDD52.7030206@cygnusinteractive.com> has wrote: > Announcing the final v1 release of HTMLTemplate; best damn HTML > templating system evar, or yer money back. Enjoy! :) > > http://freespace.virgin.net/hamish.sanderson/htmltemplate.html This HTMLTemplate is quite different from the other HTML-Template's I've seen... http://html-template.sourceforge.net/ - Perl http://phphtmltemplate.sourceforge.net/ - PHP http://htmltmpl.sourceforge.net/ - Python & PHP http://html-tmpl-java.sourceforge.net/ - Java http://shebang.jp/src/ruby/ - Ruby http://weitz.de/html-template/ - Common Lisp I believe these all share the basic idea of using a common templating language within your HTML documents (which can be valid, if using for the tags.) The original is the first one, in Perl, and all the others followed, implementing in other languages. The nice thing about this is that once you learn the templating tags, it doesn't matter what language you use, so you could change the backend from Perl to Python and not even have to change any of your templates. Pete From bac at OCF.Berkeley.EDU Thu Jun 17 00:18:37 2004 From: bac at OCF.Berkeley.EDU (Brett) Date: Wed, 16 Jun 2004 21:18:37 -0700 Subject: python-dev Summary for 2004-05-01 through 2004-05-31 Message-ID: <6785F49C-C015-11D8-B3C9-0003931A4158@ocf.berkeley.edu> python-dev Summary for 2004-05-01 through 2004-05-31 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from May 01, 2004 through May 31, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the forty-first and forty-second summaries written by Brett Cannon (out of school and employed for the summer). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-05-01_2004-05-31.html .. _original text file: http://www.python.org/dev/summary/2004-05-01_2004-05-31.ht Summary Announcements ===================== The Spring quarter is now finished for me, so hopefully over the summer I can go back to a semi-monthly schedule (work permitting). 2.3.4 was released during the coverage time of this summary. Everyone should upgrade if possible to this bugfix release. 2.4a should be ready by mid-July. The email server I use (not under my control) decided to change their IMAP server. Unfortunately it is not playing nicely with Thunderbird or the mbox format, so I am being forced to use Apple Mail in order to delete emails. Since I am not used to Mail's threading I may have missed some threads. If I did, sorry about that and they will be covered in the next summary. Summaries ========= ----------------------------- Generator expressions are in! ----------------------------- Generator expressions have been checked in. They are currently using late bindings (see the `last summary`_ for an explanation of what that means). If using late binding semantics doesn't work for you, do express your opinion since it can be changed before the beta is released. Contributing threads: - `PEP 289 - Generator Expressions `__ - `PEP 289 - Generator Expressions - Let's Move For ward `__ ------------------------------------------ Following the docs, not the implementation ------------------------------------------ What happens if you rely on an implementation when the documentation explicitly states the semantics in another way? Well, "you will pay for your sin in a special kind of hell set aside for people who take the implementation as the spec" according to Guido. Some things in CPython go against the spec for performance reasons, but there is nothing stopping from it being changed at another point to more closely follow the spec. Contributing threads: - `Passing compile(...,'exec') code to 'eval' `__ --------------------------------------------- What you need to get a module into the stdlib --------------------------------------------- In order to prevent the stdlib from getting bloated with unneeded modules, new ones need to have seen use "in the field", as Guido put it. Contributing threads: - `New Subscriber `__ --------------------- 2.3.4 is out the door --------------------- Python 2.3.4 has been released. Being a bugfix there are no new features. It is recommended that everyone upgrade to this version. Contributing threads: - `Python 2.3.4 schedule `__ - `release23-maint tree closed for 2.3.4rc1 `__ - `Python 2.3.4, release candidate 1 - BUG FIX `__ - `python 2.3.4 delayed for a week `__ - `2.3.4 release this thursday `__ - `ELEASED Python 2.3.4 (final) `__ ----------------------- IPv6 for Windows in 2.4 ----------------------- For those of you wanting IPv6 support on Windows in the binary build, you will get it in 2.4 . The reason it isn't in 2.3.x is that the branch is compiled with VC 6 which can only compile in IPv6 support with a separate SDK. VC 7, on the other hand, does not have this issue. Contributing threads: - `IPv6 support in Win binary again `__ ----------------------- cookielib in the stdlib ----------------------- A module named cookielib was added to the stdlib to allow transparent handling of cookies for modules such as urllib2. Contributing threads: - `cookielib module in 2.4? `__ - `cookielib `__ ------------------------ cmp doesn't call __cmp__ ------------------------ It was pointed out that calling ``cmp(x,x)``` does not call ``x.__cmp__(x)`` but instead uses PyObject_RichCompareBool(). The issue with this is that PyObject_RichCompareBool() has a short-circuit for when the object being compared is the same, thus skipping a possible call to x.__cmp__ and saving some time. This can be an issue, though, if you want something other than True or False to be returned. Basically what came out of this thread was that C functions can short-circuit comparisons so be careful if you want to make sure that __cmp__ is called; use '==' and the other comparison operators instead. Contributing threads: - `cmp(x,x) `__ ---------------------------------- Posssible improvements to import.c ---------------------------------- Tim Peters asked if anyone knew the working details of import.c; no one spoke up. The question was brought up because Tim would like to see failed imports not lead to mangled modules being in sys.modules and thus being considered properly imported. The suggestion of also handling circular imports came up as well. Contributing threads: - `import.c `__ From me at here.there.nowhere Thu Jun 10 08:46:12 2004 From: me at here.there.nowhere (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Thu, 10 Jun 2004 14:46:12 +0200 Subject: question regarding Guido's main article References: Message-ID: <40c85814@news.mt.net.mk> > I implemented a script using the form described in the article. The then > did: > >> python >>>> execfile("myscript.py") > > > This immediately called my main function, which should have only been > called if __name__ == "__main__". Because execfile(), without the two additional parameters, executes your script in the context of the caller, of the __main__ program. > What I expect was that __name__ would be something other than __main__ and > I would be put back at the prompt for instance... > >>>> execfile("myscript.py") >>>> foobar = "foo and a bar" >>>> main(foobar) What you need is: import myscript foobar = "foo and a bar" myscript.main(foobar) -- ?????? Weird enough for government work. From FBatista at uniFON.com.ar Mon Jun 7 09:20:18 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 7 Jun 2004 10:20:18 -0300 Subject: print problem Message-ID: [nick] #- Any way that I can just use it as printf in C? Yes. Use %. print "%d%d%d" % (number1, number2, number3) The sintax is: % . Facundo From claudio.grondi at freenet.de Wed Jun 9 19:53:25 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 9 Jun 2004 23:53:25 -0000 Subject: Python Scripting in Windows MSIE 6.0 Message-ID: <2ipfiaFphmh5U1@uni-berlin.de> I wonder why the subject (Python scripting within HTML) is not occuring in any past postings - do I miss something very obvious? I try to run Pythons scripting in Windows MSIE 6.0 in the section, but it doesn't work at all. \Python23\Lib\site-packages\win32comext\axscript\client\pyscript_rexec.py runs ok, registry entries seems also be ok. I have the latest Python 2.3.4 installed. What do I wrong? Runs anyone of you (inspite of the security concerns) successfully Python as scripting language in Windows MSIE 6.0 HTML pages using it like JavaScript or VBScript ? Thank you in advance for any help. Claudio From dkturner at telkomsa.net Fri Jun 18 04:30:01 2004 From: dkturner at telkomsa.net (David Turner) Date: 18 Jun 2004 01:30:01 -0700 Subject: does python have useless destructors? References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > David Turner wrote: > >aahz at pythoncraft.com (Aahz) wrote in message news:... > >> In article , > >> David Turner wrote: > >>> > >>>In fact, the RAII idiom is quite commonly used with heap-allocated > >>>objects. All that is required is a clear trail of ownership, which is > >>>generally not that difficult to achieve. > >> > >> Not really. What you're doing is what I'd call "virtual stack" by > >> virtue of the fact that the heap objects are being managed by stack > >> objects. > > > >Having read this through a second time, I'm not sure that you > >understood the C++ code I posted. So here is an equivalent in Python: > > [snip] > > > >No stack objects in sight, yet this code is semantically equivalent to > >the C++ code. > > Not really. Problem is that there's nothing to prevent people from > passing File.fh outside the loop -- and that's standard Python coding > technique! For that matter, there's nothing preventing a File() > instance from being passed around. The fact that you've created an > idiom that you want to behave like a similar C idiom has nothing to do > with the way Python actually works. You can do exactly the same thing in the C++ version, and regularly do. What's your point? Regards David Turner From luked at xplantechnology.com Wed Jun 23 03:58:49 2004 From: luked at xplantechnology.com (Luke) Date: Wed, 23 Jun 2004 17:58:49 +1000 Subject: Regex question In-Reply-To: References: Message-ID: Jonas Galvez wrote: > I've a perhaps unusual piece of data to parse with regexes. > > >>>>import re >>>>re.findall("a (\w ?)*", "a b c d e f g h") > > ['h'] > > This is a very very very simplified example. The result I was > expecting is the following: ['a', 'b', 'c'] ... and so forth. Is it > impossible to repeat a pattern group inside another? Are you hoping for your regular expression to match the whole string, or just one letter? This is how I would get the result you seek: >>> import re >>> re.findall("\w", "a b c d e f g h") ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] The regular expression you used, "a (\w ?)*", will match the whole string, which is why you have only one element in the list returned by findall. Since you used a group (using parentheses), findall only returned what was inside the group (the 'h') rather than the whole match ('a b c d e f g h'). From BELLEMAIL-SA at exponent.com Thu Jun 17 22:00:36 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Thu, 17 Jun 2004 19:00:36 -0700 Subject: [MailServer Notification]To Recipient file blocking settings matc hed and action was taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28EBC@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = rogerb at rogerbinns.com Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 246 Scanning time = 06/17/2004 19:00:36 Engine/Pattern = 7.000-1004/907 Action taken on message: The attachment your_file.pif matched file blocking settings. ScanMail took the action: Deleted. Warning to recipient: Attachment blocking action taken. From simoninusa2001 at yahoo.co.uk Fri Jun 25 12:02:09 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 25 Jun 2004 09:02:09 -0700 Subject: win XP + wxPython + py2exe References: <40dbeb20$0$17148$626a14ce@news.free.fr> Message-ID: <30260531.0406250802.614eb68b@posting.google.com> Olivier Thiery wrote: > I've ported a software I've developped from win 2k to win xp and something I > wouldn't have expected happened. > > If I simply run the py files, the software uses the current xp skin > looknfeel, but if I compile it using py2exe it looks like any ugly standard > grey win2k app. > > Does anybody know why and how it can be fixed ? You need to include and XP manifest file. You can either just copy (and rename to match your .exe) the python.exe.manifest file from c:\python23 or I prefer to embed it into my setup.py for py2exe (just change "myprogram" to your program name) I think this is in the py2exe Wiki: from distutils.core import setup import py2exe manifest = """ myProgram """ """ installs manifest and icon into the .exe but icon is still needed as we open it for the window icon (not just the .exe) changelog and logo are included in dist """ setup( windows = [ { "script": "myprogram.py", "icon_resources": [(1, "myprogram.ico")], "other_resources": [(24,1,manifest)] } ], data_files=["logo.gif", "myprogram.ico", "ChangeLog.txt"], ) From fumanchu at amor.org Tue Jun 8 18:10:20 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 8 Jun 2004 15:10:20 -0700 Subject: promoting [] by superclass? Message-ID: Jim Newton wrote: > Basically i'd like the Pair.__init__ in the case of Pair(1,2,3,4,5), > to set self[0]=1, and self[1] = Pair(2,3,4,5) in some iterative > way. Sure, just perform that split in your __init__ method, and override __new__ to match arguments: >>> class Pair(list): ... def __new__(cls, *args): ... return list.__new__(cls) ... ... def __init__(self, *args): ... args = list(args) ... if len(args) > 2: ... self[:] = args[0], Pair(*args[1:]) ... else: ... self[:] = args[:] ... >>> Pair(1, 2, 3) [1, [2, 3]] >>> Pair() [] >>> Pair(1) [1] >>> Pair(1, 2, 3, 4, 5, 6) [1, [2, [3, [4, [5, 6]]]]] ISTR you're somewhat new to Python (?), so I'll just quickly add that: 1) [i:j] is a slice of a list. i and j default to the endpoints; for example, args[1:] gives you all items in a list except the first one. http://docs.python.org/ref/slicings.html 2) *args is a way to pass a variable number of arguments. http://docs.python.org/ref/function.html Robert Brewer MIS Amor Ministries fumanchu at amor.org From http Sun Jun 27 19:06:44 2004 From: http (Paul Rubin) Date: 27 Jun 2004 16:06:44 -0700 Subject: Can you make this faster? References: <889cbba0.0406271022.fd1f9ac@posting.google.com> <40DF3AA1.4000100@v.loewis.de> Message-ID: <7x3c4gob23.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > if c == 's': > fmt[i] = str(len(arg))+'s' fmt[i] = "%ds" % len(arg) might be a little faster. From http Fri Jun 11 20:12:30 2004 From: http (Paul Rubin) Date: 11 Jun 2004 17:12:30 -0700 Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> <942dndpaDtrLvVfdRVn-jg@comcast.com> Message-ID: <7xsmd1ocr5.fsf@ruckus.brouhaha.com> "Larry Bates" writes: > Noticed you had not received a response, so I'll > try. Maybe you could use Python to Mathematica > interface? > > http://py-ml.sourceforge.net/ I actually do have an ancient copy of Mathematica for MS-DOS, but that's probably not too much help. I was hoping for something in pure Python. From nun at meyl.com Fri Jun 25 05:31:02 2004 From: nun at meyl.com (Mitja) Date: Fri, 25 Jun 2004 11:31:02 +0200 Subject: How to draw points of a curve References: <5e692f7f.0406241917.7b08940c@posting.google.com> Message-ID: dimfox (news:5e692f7f.0406241917.7b08940c at posting.google.com) wrote: > Hi, I am new to Python. > > What I need to do is to calculate a curve and display it at the same > time. I don't want to use the gplt.plot() because I need to show the > animation of the curving growing. > > Which package should I use? Which function? Maybe there's a more elegant solution, but I'd go for manual plotting and a slight delay before drawing each of the pixels (or rather segments to avoid any empty spaces in case of steep curves) > > Thank you From jepler at unpythonic.net Tue Jun 1 14:25:04 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 1 Jun 2004 13:25:04 -0500 Subject: Print String In-Reply-To: <494182a9.0406011013.20ef1f2@posting.google.com> References: <494182a9.0406011013.20ef1f2@posting.google.com> Message-ID: <20040601182503.GC19278@unpythonic.net> I'd try something along these lines: def GeneratePrefix(expr): if expr.__class__ == E: yield str(expr.operator) for i in GeneratePrefix(expr.left): yield i for i in GeneratePrefix(expr.right): yield i else: yield str(expr) The successive elements produced by this (untested) code should be the same as the elements printed by your code. To join these into a string without any whitespace, you could write def StringPrefix(expr): return "".join(GeneratePrefix(expr)) and you could re-write the original PrintPrefix as def PrintPrefix(expr): for item in expr: print item, Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From klachemin at home.com Mon Jun 21 06:32:31 2004 From: klachemin at home.com (Kamilche) Date: 21 Jun 2004 03:32:31 -0700 Subject: StringToDict and DictToString Message-ID: <889cbba0.0406210232.3db94e77@posting.google.com> I made this tonight, after discovering how bad it is to use eval() in a server program. If someone knows of a better method, let me know! import types ''' Convert a string to a dict, or a dict to a string. Not that comprehensive - it only handles strings, ints, longs, floats, and None, but it's safer than using 'eval' and trying to restrict the execution environment! --Kamilche Sample output: -------------- orig dict: {'int': 1, 'none': None, 'float': 1.0, 'string': 'string', 'long': 12345678901234567890L} to string: ' int 1 none None float 1.0 string string long 12345678901234567890' to dict: {'int': 1, 'none': None, 'float': 1.0, 'string': 'string', 'long': 12345678901234567890L} ''' def StringToDict(s): ''' Convert a string to a dict. The first char of the string is the delimiter for the items. Try to parse it, and on failure, return an empty dict. ''' if type(s) != types.StringType: raise Exception("Arg to StringToDict must be a string!") try: if len(s) < 4: return {} delim = s[0] tokens = s.split(delim) i = 1 max = len(tokens) - 1 d = {} while i < max: key = tokens[i] value = StringToValue(tokens[i + 1]) d[key] = value i += 2 return d except: return {} def DictToString(d, delim = '\t'): ''' Convert a dict to a string. If the str() of any key or value in the dict contains the delimiter, raise an error. Otherwise, insert the delimiter into the first character of the string. ''' tokens = [] if type(d) != types.DictType: raise Exception("Argument must be a dict!") if len(d) == 0: return '' if len(delim) != 1: raise Exception("Delimiter must be a single character!") tokens.append('') for key, value in d.items(): key = str(key) value = str(value) if delim in key or delim in value: raise Exception("Pick a different delimiter for DictToString, your data uses %s!" % delim) tokens.append(key) tokens.append(value) return delim.join(tokens) def StringToValue(s): " Convert a string to the 'best guess' type" if type(s) != type(""): return s if len(s) == 0: return s if s in ('None', 'none'): return None if (s[0] in "+-0123456789.") and ("." in s): try: v = float(s) return v except: pass if s[0] in "+-0123456789": try: v = int(s) return v except: try: v = long(s) return v except: pass return s def test(**d): print "orig dict:", d s = DictToString(d, ' ') print "to string: '" + s + "'" print "to dict: ", StringToDict(s) print def main(): test() test(string = 'string', int = 1, float = 1.0, long = 12345678901234567890, none = None) if __name__ == "__main__": main() From bpeng at rice.edu Sun Jun 13 20:53:03 2004 From: bpeng at rice.edu (Bo Peng) Date: Sun, 13 Jun 2004 19:53:03 -0500 Subject: python/c++/swig: some more problems. Message-ID: Dear list, With the help from this list, I have experimented some techniques and I have to say python/c++/swig is wonderful! I still have some questions though: 1. Is there a way to access int * member of an object from a pointer returned by Python? >>> a.internalIndex '_88401708_p_int' I have used vector etc (in C++ code) and vector.i (swig) to pass python list to C++ like 'foo([1,2,3])' but I do not want to use vectors everywhere due to performance considerations. 2. The shadow class has definitions like __init__(self, *args) so I can not use keyward arguments like a(x=1,y=2). Is there an option in SWIG to enable this? If I have to, how can I modify the interface file to enable this? Many thanks in advance. Bo From 56104586 at oxy.edu Thu Jun 24 13:23:22 2004 From: 56104586 at oxy.edu (56104586 at oxy.edu) Date: Thu, 24 Jun 2004 19:23:22 +0200 Subject: Test Message-ID: Delivered message is attached. -------------- next part -------------- A non-text attachment was scrubbed... Name: data.zip Type: application/octet-stream Size: 29840 bytes Desc: not available URL: From MAIL-SA at gcc-sg.org Fri Jun 25 01:41:35 2004 From: MAIL-SA at gcc-sg.org (MAIL-SA at gcc-sg.org) Date: Fri, 25 Jun 2004 08:41:35 +0300 Subject: ScanMail Message: To Recipient virus found or matched file blocki ng setting. Message-ID: <28C8599E1F531C42840A645C40D44F6509259A@mail.gcc-sg.org> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = loloteetjuju at hotmail.com Recipient(s) = python-list at python.org; Subject = Re: Message Error Scanning Time = 06/25/2004 08:41:34 Engine/Pattern = 7.000-1004/915 Action on message: The attachment msg.zip contained WORM_NETSKY.P virus. ScanMail has taken the Deleted action. Warning to recipient. ScanMail has detected a virus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jun 30 16:11:17 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jun 2004 22:11:17 +0200 Subject: call py from py In-Reply-To: References: Message-ID: <40e31e68$0$48959$e4fe514c@news.xs4all.nl> Alberto Vera wrote: > Could you tell me How I Can call a python program from another one? Just import the other module and call a function from it? Or use os.system or whatever. More info needed for better answers. --Irmen From winexpert at hotmail.com Wed Jun 30 11:05:39 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 30 Jun 2004 15:05:39 +0000 Subject: Python-list Digest, Vol 9, Issue 422 Message-ID: Peter, Thank you very much for the info. I have no idea how to know if its a cgi thing or not but I'll just experiment with both and see which works best. David ------- Surf a wave to the future with a free tracfone http://cellphone.duneram.com/index.html >------------------------------ > >Message: 10 >Date: Wed, 30 Jun 2004 15:35:53 +0200 >From: Peter Maas >Subject: Re: using python with HTML and parameters >To: python-list at python.org >Message-ID: >Content-Type: text/plain; charset=us-ascii; format=flowed > >David Stockwell schrieb: > > > In java/jsp I can pass parameters to my python script on a webpage by > > doing something like this: > > > > http://somewhere.org/mypage.jsp?parm1=something&parm2=another > > > > How do I do that with python? > >If your Python Script uses CGI it's > >http://somewhere.org/mypage.py?parm1=something&parm2=another > >:) You have to parse the query string with cgi.parse(). > >Mit freundlichen Gruessen, > >Peter Maas > >-- >------------------------------------------------------------------- >Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') >------------------------------------------------------------------- > > >------------------------------ > >Message: 11 >Date: Wed, 30 Jun 2004 15:38:07 +0200 >From: Peter Maas >Subject: Re: using python with HTML and parameters >To: python-list at python.org >Message-ID: >Content-Type: text/plain; charset=us-ascii; format=flowed > >Peter Maas schrieb: > > If your Python Script uses CGI it's > > > > http://somewhere.org/mypage.py?parm1=something&parm2=another > >Correction: this URL does not depend on CGI, only the Python code. > >Mit freundlichen Gruessen, > >Peter Maas > >-- _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From heikowu at ceosg.de Tue Jun 29 18:53:15 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Wed, 30 Jun 2004 00:53:15 +0200 Subject: class with __len__ member fools boolean usage "if x:" ; bad coding style? In-Reply-To: References: <78b6a744.0406250737.310f31da@posting.google.com> Message-ID: <200406300053.15663.heikowu@ceosg.de> Am Dienstag, 29. Juni 2004 20:34 schrieb Peter Otten: > In Python, you don't normally check for a timeout (google for LBYL), you'd > rather throw an exception. This avoids problems like > > h = Host() > if h: > sleep(justLongEnoughForHostToTimeOut) > h.someOperation() # fails due to timeout The operations on the host don't fail if the timeout has expired, in my use case. It's just that a host has a timeout, which signals the surrounding code, that this host needs to be contacted in the next run of ping signals. What I can do to get these hosts now looks like the following: ping_hosts = [h for h in hosts if not h] That's what I call nice and concise, and at least for me the meaning is clear by just looking at the code. If the host has expired (not host), add it to the list of hosts to ping now. > A __len__() without a __getitem__() method doesn't make sense to me. But > maybe your example is just too terse... Why should you need a __getitem__() if you have __len__() defined? In my use case, the ID (of a host/data-item, etc.) is not retrievable by single character (that would make no sense), but the length of the ID is significant, as it can signal important information as on the protocol to use to contact the host, etc. So, I can how write: someid = host myid_old = myhost.old_id myid_new = myhost.new_id if len(someid) == 26: dist = myid_old ^ someid elif len(someid) == 30: dist = myid_new ^ someid else: raise ValueError, "Invalid host." (where __xor__ is again a method defined on two IDs, returning the numerical distance, the binary xor between the two numbers) I would never call this unintuitive, as in effect hosts are just IDs which have additional data (namely the IP/port pair), and can be used in any context in the program where IDs are wanted. And IDs can be asked for their length (to decide what to do with it). This doesn't just mean Hosts, also Data Items are IDs with additional data, which can be used just as well here. > No amount of documentation can heal an unintuitive API. > The convention of using bool(o) as an abbreviation of o.isValid() for > non-sequences and of len(o) != 0 for sequences seems natural to me. Mixing > these two meanings or even adding "was this parameter provided" as a third > one will result in highly ambiguous code that is bound to break. I can understand that in the normal case you would want to code something either as a sequence, or as a non-sequence. But, in this case, you have two classes, which have different use cases, but are derived from another (and deriving a Host from an ID isn't strange, at least for me). And for code which does something with the ID (and is specifically marked as such), it's pretty fair to use the ID part of the class which is passed in (which in this case are __len__ and __xor__) to make it concise, while where you use hosts, you take the host protocol to get at the host data (__nonzero__). I don't see anything unintuitive in this... Actually, it makes the code look cleaner, IMHO. Heiko. From peufeu at free.fr Mon Jun 28 04:36:07 2004 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Mon, 28 Jun 2004 10:36:07 +0200 Subject: What is the meaning of static and class methods ? References: Message-ID: see : http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-14 find classmethod and staticmehtod copypaste : ************************************************* staticmethod( function) Return a static method for function. A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C: def f(arg1, arg2, ...): ... f = staticmethod(f) It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. Static methods in Python are similar to those found in Java or C++ ************************************************* classmethod( function) Return a class method for function. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f) It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. > But I don't understand, why we need class method-s in python. If I want > to create an object, that is don't need to I execute this object's > Create method. it's used to invoke a method on a class without instanciating the object. > Some other possible meaning is to create some class methods, that > creates object with preinitialized state. Example: an ftp object with > opened, and setted state. could be a GetInstance like behaviour, then, yes. > But we can do that with simple functions too. then you pollute the global namespace > Another question is that what is the meaning of static methods ? > In Delphi the not overrided methods of class are static, but you cannot > use the Self parameter in that methods. > In Java, the without static methods the JVM cannot run your main class, > so it is needed to execute your program. don't understand what you say > But in py I don't understand the meaning of that methods. In the > examples I see that we cannot use self parameter in static method - it > is correct - but everything is seems to be that this is only a method > with "special sign" that make the static method the piece of an object. Example : - GetTypeID() returns an integer. This is stored in a MySQL field for instance. Ideal application for a static method because it only depends on the object class. - CreateSubclass() creates a subclass of the desired variant. Fits well with a class method. class baseclass( object ): def GetTypeID(): return 0 GetTypeID = staticmethod( GetTypeID ) def CreateSubclass( cls, typeid, *args ) subclasses = { 1:subclass1, 2:subclass2 } return subclasses[typeid](args) class subclass1( object ): def __init__(self, .....) .... def GetTypeID(): return 1 GetTypeID = staticmethod( GetTypeID ) class subclass2( object ): def __init__(self, .....) .... def GetTypeID(): return 2 GetTypeID = staticmethod( GetTypeID ) So you get : typeid,args = get'em from database obj = baseclass.CreateSubclass( typeid, args ) .. do something with obj... etc... From lbates at swamisoft.com Fri Jun 25 17:56:02 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 25 Jun 2004 16:56:02 -0500 Subject: Referring to a list References: <1a0Dc.13333$rh.4819@okepread02> Message-ID: Absolutely. Everything in Python is a pointer. x=final_list is a pointer to final_list x=final_list_other changes what x points to. Larry Bates Syscon, Inc. "Sean Berry" wrote in message news:1a0Dc.13333$rh.4819 at okepread02... > I have a function like this: > > final_list = [] > > def doSomething(): > for item in starting_list = []: > Do all sorts of stuff... about 150 lines of processing. > Lots of conditional statements for appending to the final_list. > So I have lots of final_list.append( results ) statements. > > I wanted to single out a few cases and have > them append to a different list. > > The way I would "normally" do something like this would be to have > all of the .append() statements in another function like this > > def addToList( listName, otherInfo ) > do something with otherInfo. > then listName.append( results ) > > But, in this case, by the time I get to this point there > are too many variables to pass (something like 60). > > So, what I want to do is use some kind of name reference > for the list I want to use. > > EXAMPLE: > final_list = [] > secondary_list = [] > > def DoSomething(): > if (condition is met): > list_i_am_referring_to = final_list > else > list_i_am_referring_to = secondary_list > > then I can do everything using the list_i_am_referring_to. > > Is this possible??? > > Sorry about my poor, and lengthy explanation. > Thanks for any help. > > From Ian.Sparks at etrials.com Fri Jun 4 09:51:05 2004 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Fri, 4 Jun 2004 09:51:05 -0400 Subject: [ANN] HTMLTemplate 1.0.0 Message-ID: <41A1CBC76FDECC42B67946519C6677A9A20EB2@pippin.int.etrials.com> Walter D?rwald wrote : > >XIST follows a different philosophy: All templates are pure XML (in >fact most of our templates consist of a root element only (something >like )). The rest is done in pure Python code. The designer >develops the XML elements for the layout. So this is JSP taglibs for python? Taglibs seem like a good idea, code-up your own tags and sprinkle them throughout your HTML. But taken to the logical conclusion you get to monolithic tags like your example. >Our main designer had no previous programming experience and was using >Adobe GoLive before joining our company. Now he's programming all his >HTML templates in Python without any problems. I can see how this would play out. You hire a web-designer and explain to them your custom tags and what they do. They start using them in GoLive (or whatever their tool of choice is) but the custom tags don't render in their tool. As the tag libraries build up in complexity the HTML migrates from the templates into the python taglib code and inevitably the designer will follow the HTML there. Eventually the taglib becomes so customized that there is no HTML left, only custom tags. Eventually the designer abandons the "HTML template" completely and it is left as a stub like (which looks a bit vestigal to me, the code equivalent of tonsils). I'm not criticising XIST (it looks very powerful). I'm genuinely interested in what happens when you mutate HTML into a custom XML markup via taglibs : How far does it go? Is there some safe middle ground? Can you share the resulting markup language with 3rd parties or has it simply become too customized to your uses? For instance, what would be the learning curve to bring in a new HTML designer? I've seen some advice on JSP taglibs to the effect of "keep them small and specific and don't create monolithic tags", what would your advice be for using XIST with python? Ian Sparks. -----Original Message----- From: Walter D?rwald [mailto:walter at livinglogic.de] Sent: Thursday, June 03, 2004 3:06 PM To: python-list at python.org Subject: Re: [ANN] HTMLTemplate 1.0.0 John Machin wrote: > [...] > Oh, you want *practical* experience eh? ;) > > I would think the "theory" is that you've got designers/authors working > on templates, who don't know code. They know HTML, and know CSS, but > they do not program or know any code. You give these people templates to > work on. XIST follows a different philosophy: All templates are pure XML (in fact most of our templates consist of a root element only (something like )). The rest is done in pure Python code. The designer develops the XML elements for the layout. This might be something simple like: class pageTitle(xsc.Element): def convert(self, converter): e = html.h1(self.content) return e.convert(converter) These layout elements can then be used for a static mockup to be presented to the customer (i.e. foobar in XML or layout.pageTitle("foobar") in Python). The developer responsible for the dynamic part uses these layout elements with XIST JSP elements to implement the business logic, e.g. by using layout.pageTitle(jsp.expression("myObject.getTitle()")). It would be possible to use any other templating system for implementing the business logic, e.g. use PHP: layout.pageTitle(php.expression("$myObject->getTitle()"). > [...] > Another successful separation of logic from presentation... or so the > theory goes... ;) XIST uses another version, just that both logic and presentation are implemented in Python. ;) You have to say goodbye to your HTML editor with this approach, but this gives you better control over your HTML code anyway. Our main designer had no previous programming experience and was using Adobe GoLive before joining our company. Now he's programming all his HTML templates in Python without any problems. Bye, Walter D?rwald -- http://mail.python.org/mailman/listinfo/python-list From joel at rosdahl.net Wed Jun 23 17:23:41 2004 From: joel at rosdahl.net (Joel Rosdahl) Date: Wed, 23 Jun 2004 23:23:41 +0200 Subject: OT: Chat server In-Reply-To: <20040617102051.GE2048@zoran.com> (Miki Tebeka's message of "Thu, 17 Jun 2004 12:20:52 +0200") References: <20040617102051.GE2048@zoran.com> Message-ID: <87wu1y6k9u.fsf@fluff.rosdahl.net> "Miki Tebeka" writes: > I'm looking for a chat (IRC) server. I'm not sure what you're looking for, but I've written a small IRC server in Python. It can be found here: http://joel.rosdahl.net/projects/#miniircd > Nothing fancy. Check. > It has to be free, standalone Check and check. > and with logging. Nope. Patches are welcome. :-) > Python based will be ideal. Check. Regards, Joel -- Joel Rosdahl Key BB845E97; fingerprint 9F4B D780 6EF4 5700 778D 8B22 0064 F9FF BB84 5E97 From klachemin at home.com Sun Jun 27 14:22:18 2004 From: klachemin at home.com (Kamilche) Date: 27 Jun 2004 11:22:18 -0700 Subject: Can you make this faster? Message-ID: <889cbba0.0406271022.fd1f9ac@posting.google.com> I have a routine that I really need, but it slows down processing significantly. Can you spot any ineffeciencies in the code? This code makes a critical function of mine run about 7x slower than using a prebuilt format string. For maximum flexibility, it would be best to calculate the format string using this method, so I'd dearly love to keep it. def fmtstring(args): delim = '\0' fmt = [] fmt.append('<') for arg in args: t = type(arg) if t == types.StringType: l = len(arg) fmt.append(str(l) + 's') elif t == types.IntType: fmt.append('i') elif t == types.LongType: fmt.append('q') elif t == types.BooleanType: fmt.append('c') elif t == types.FloatType: fmt.append('d') else: raise Exception("Can't pack argument of type %s!" % t) s = ''.join(fmt) s = s + '\0' return s From zxie02 at hotmail.com Wed Jun 30 07:25:34 2004 From: zxie02 at hotmail.com (henry xie) Date: Wed, 30 Jun 2004 07:25:34 -0400 Subject: TERMIOS.py Message-ID: Hi, All: I am a newbie in Python. I am trying to use pexpect package in the project. But when I installed the package, it couldn't be used as termios.py was missing. I checked the LIB directory. It had TERMIOS.py but no termios.py. Could any body explain to me where can I found this file and solve this problem? Thanks in advance. Henry From kirk at strauser.com Fri Jun 11 17:45:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 11 Jun 2004 21:45:06 GMT Subject: Inheritence confusion References: Message-ID: <87k6ydbwm6.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-06-11T20:47:44Z, "Robert Brewer" writes: > Some options: > > 1) Override __init__ in the subclass. Sigh. I'd wanted to avoid that, but I guess I can make it a thin wrapper. > 2) Pass the correct module as an argument to init. Erk. > 3) Perform ugly module-inspection hacks. Don't do this. Agreed. :) > It would be a *lot* clearer if your example didn't re-use names in > different modules. OK, then, I shall again ask advice. I foresee having 10-15 completely distinct classes for clients to choose from. I don't want to end up in the position where a client program has to know that if it's importing FtpEdiFiles, then it has to use the FtpEdiFileRetriever class, but if it's importing ScpPngFiles, then it has to use the ScpPngFileRetriever class. I really want to use the same class name across all of the modules unless doing otherwise is unavoidable. What's a good way to handle this? - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAyico5sRg+Y0CpvERAo3QAKCaC1wUewWaOLNTIO2bKpe8jI81hgCfUiPy Ls+DY5TdE1oqxdz3JCDiJhw= =vrvV -----END PGP SIGNATURE----- From FBatista at uniFON.com.ar Wed Jun 9 11:03:37 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 9 Jun 2004 12:03:37 -0300 Subject: division bug? Message-ID: [milanmor at yahoo.com] #- a=10 #- b=5 #- print a/b >>> 2/5 0 >>> 7/3 2 >>> from __future__ import division >>> 2/5 0.40000000000000002 >>> 7/3 2.3333333333333335 >>> 2//5 0 >>> 7//3 2 . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Jun 5 07:54:24 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 05 Jun 2004 12:54:24 +0100 Subject: Brain Dead Singleton In-Reply-To: References: <889cbba0.0406041333.10402447@posting.google.com> <40c162a6$1@news.iconz.co.nz> <40C1A3DC.2090009@jessikat.fsnet.co.uk> Message-ID: <40C1B470.1000407@jessikat.fsnet.co.uk> Peter Hansen wrote: > Robin Becker wrote: > >> Colin Brown wrote: >> >>> Whenever I want a singleton "class", I just use a module with >>> functions and >>> global variables. Modules only import once. >>> >> should often work, but this illustrates how it can go wrong > > [...] > >> del sys.modules['my_singleton_module'] > > [...] > >> so if sys.modules gets interfered with approriately, your singleton >> can start breeding. > > > We're all adults. How often do you see (or write) code that > goes around deleting modules from sys.modules. Colin's > suggesting is just fine for most sane situations. > > -Peter well I actually have a use case for deleting modules from sys.modules. In some legacy code for ReportLab documentation, import was used in the form import chapter1 import chapter2 ..... in two different documents causing confusion. An easy fix involved restoring sys.modules to a pristine state before each document was generated. -- Robin Becker From opengeometry at yahoo.ca Mon Jun 7 13:19:26 2004 From: opengeometry at yahoo.ca (William Park) Date: 7 Jun 2004 17:19:26 GMT Subject: simple script to read and output Mailbox body to file. References: Message-ID: <2ijmctFnvgjeU2@uni-berlin.de> Chuck Amadi wrote: > Sorry to bovver you again (again) here's script. > > I still can't see why the get_payload() doesn't produce > the plain text message body of an emails in the testwwws users mailbox. > As you can see I have tried a few things but no joy what am I missing. > > Is the another snippet in relation to get_payload to access the body > contents print and process to a file. [snip] You still haven't answered central questions. - Do you want email bodies in separate files, or all email bodies in one file? - Do you want to collect these email bodies as they come in, or periodically from a 'mbox' file? -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From adamc at linuxmail.org Mon Jun 21 10:38:54 2004 From: adamc at linuxmail.org (Adam) Date: Mon, 21 Jun 2004 15:38:54 +0100 Subject: Creating subclassess (newbie) Message-ID: <20040621153854.14f10a9f@debian> I have tried to send this to the tutor mailing list, but it seems to be down at the moment. I have a subclass I want to create- my intuition told me that it would be done like this: class MainClass: class SubClass: code... subclassinstance = SubClass() mainclassinstance = MainClass() But it seems that this isn't going to work. I'm reading a couple of Python books, but they don't seem to cover this topic very well (I don't see any coding examples). What is the best way of creating (coding) subclasses? Alternatively, is there any good documentation on the web for doing this? Thanks in advance. Adam From tim.golden at viacom-outdoor.co.uk Mon Jun 28 08:46:22 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 28 Jun 2004 13:46:22 +0100 Subject: if statement Message-ID: Ajay> > syntax error, invalid syntax is what i got Ajay, you're going to have to try a bit harder. Can you cut-and-paste the output from an interpreter session into an email and send it? It's very hard to guess what's going to go wrong from a small piece of code which can't possibly run by itself, and the fact that you're seeing a "syntax error, invalid syntax". This is the kind of thing (although obviously relevant to your program): ActivePython 2.2.3 Build 227 (ActiveState Corp.) based on Python 2.2.3 (#42, Nov 13 2003, 09:57:55) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = 1 >>> b = 1| File "", line 1 b = 1| ^ SyntaxError: invalid syntax >>> TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From adam_goucher at hotmail.com Thu Jun 17 13:12:40 2004 From: adam_goucher at hotmail.com (Adam) Date: 17 Jun 2004 10:12:40 -0700 Subject: bus error / crash using https Message-ID: <2e261686.0406170912.48b9f4c1@posting.google.com> I have an application which interacts with a webserver over https using client certificates. Due to a bug in openssl 0.9.6, I upgraded to 0.9.7 and rebuilt python. Now, when I access the page python is crashing with with a "bus error" and coring. Any insite as to what I need to do to fix this? The gdb output is below. -adam [adam at goblin bin]$ gdb /usr/local/bin/python core GNU gdb 4.18 Copyright 1998 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "sparc-sun-solaris2.8"... Core was generated by `/usr/local/bin/python testdriver.py -g /home/adam/newport/inferno-iplanet.xml e'. Program terminated with signal 9, Killed. Reading symbols from /usr/lib/libresolv.so.2...done. Reading symbols from /usr/lib/libsocket.so.1...done. Reading symbols from /usr/lib/libnsl.so.1...done. Reading symbols from /usr/lib/librt.so.1...done. Reading symbols from /usr/lib/libdl.so.1...done. Reading symbols from /usr/lib/libpthread.so.1...done. Reading symbols from /usr/lib/libm.so.1...done. Reading symbols from /usr/lib/libc.so.1...done. Reading symbols from /usr/lib/libmp.so.2...done. Reading symbols from /usr/lib/libaio.so.1...done. Reading symbols from /usr/platform/SUNW,Ultra-5_10/lib/libc_psr.so.1...done. Reading symbols from /usr/lib/libthread.so.1...done. Reading symbols from /usr/lib/locale/en_US.ISO8859-1/en_US.ISO8859-1.so.2... done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/math.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/_random.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/time.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/fcntl.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/strop.so...done. Reading symbols from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/ldapmodules/solaris/_ldap.so...done. Reading symbols from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libldap_r.so.2...done. Reading symbols from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/liblber.so.2...done. Reading symbols from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libssl.so.0.9.7...done. Reading symbols from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libcrypto.so.0.9.7...done. Reading symbols from /usr/lib/libgen.so.1...done. Reading symbols from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libsasl2.so.2...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/binascii.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/cStringIO.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/_socket.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/_ssl.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/cPickle.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/struct.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/pyexpat.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/sha.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/unicodedata.so... done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/itertools.so...done. Reading symbols from /usr/local/lib/python2.3/lib-dynload/array.so...done. #0 0xfe6a7aa0 in ssl3_read_bytes () ---Type to continue, or q to quit--- from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libssl.so.0.9.7 (gdb) where #0 0xfe6a7aa0 in ssl3_read_bytes () from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libssl.so.0.9.7 #1 0xfe6a55c4 in ssl3_read () from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libssl.so.0.9.7 #2 0xfe6ae9b8 in SSL_read () from /home/adam/work/mainline/qa/Scripts/TestDriver-devel/lib/libssl.so.0.9.7 #3 0xfe481e70 in PySSL_SSLread (self=0x1ddd98, args=0x0) at /usr/local/src/Python-2.3.4/Modules/_ssl.c:442 #4 0xcbea0 in PyCFunction_Call (func=0x3669e0, arg=0x2ee050, kw=0x0) at Objects/methodobject.c:108 #5 0x80554 in call_function (pp_stack=0xffbee6f0, oparg=3072080) at Python/ceval.c:3439 #6 0x7e080 in eval_frame (f=0x1feb28) at Python/ceval.c:2116 #7 0x8078c in fast_function (func=0x34b3f0, pp_stack=0x263ac8, n=1, na=0, nk=1146912) at Python/ceval.c:3518 #8 0x80640 in call_function (pp_stack=0xffbee888, oparg=1) at Python/ceval.c:3458 #9 0x7e080 in eval_frame (f=0x263960) at Python/ceval.c:2116 #10 0x7f634 in PyEval_EvalCodeEx (co=0x3484a0, globals=0x0, locals=0x263960, args=0x1f4f78, argcount=1, kws=0x1f4f7c, kwcount=0, defs=0x3498fc, defcount=1, closure=0x0) at Python/ceval.c:2663 #11 0x80818 in fast_function (func=0x34b430, pp_stack=0xffbeeaa8, n=1, na=1, nk=0) at Python/ceval.c:3529 #12 0x80640 in call_function (pp_stack=0xffbeeaa8, oparg=1) at Python/ceval.c:3458 #13 0x7e080 in eval_frame (f=0x1f4e20) at Python/ceval.c:2116 #14 0x7f634 in PyEval_EvalCodeEx (co=0x3452a0, globals=0x0, locals=0x1f4e20, args=0x38b5cc, argcount=1, kws=0x38b5d0, kwcount=0, defs=0x3498bc, defcount=1, closure=0x0) at Python/ceval.c:2663 #15 0x80818 in fast_function (func=0x335d70, pp_stack=0xffbeecc8, n=1, na=1, nk=0) at Python/ceval.c:3529 #16 0x80640 in call_function (pp_stack=0xffbeecc8, oparg=1) at Python/ceval.c:3458 #17 0x7e080 in eval_frame (f=0x38b468) at Python/ceval.c:2116 #18 0x7f634 in PyEval_EvalCodeEx (co=0x33d920, globals=0x0, locals=0x38b468, args=0x374dc4, argcount=2, kws=0x374dcc, kwcount=0, defs=0x35b1fc, defcount=1, closure=0x0) at Python/ceval.c:2663 #19 0x80818 in fast_function (func=0x35c7b0, pp_stack=0xffbeeee8, n=2, na=2, nk=0) at Python/ceval.c:3529 #20 0x80640 in call_function (pp_stack=0xffbeeee8, oparg=2) at Python/ceval.c:3458 #21 0x7e080 in eval_frame (f=0x374c60) at Python/ceval.c:2116 #22 0x7f634 in PyEval_EvalCodeEx (co=0x33d960, globals=0x0, locals=0x374c60, args=0x1780e4, argcount=1, kws=0x1780e8, kwcount=0, defs=0x35b21c, defcount=1, closure=0x0) at Python/ceval.c:2663 #23 0x80818 in fast_function (func=0x35c7f0, pp_stack=0xffbef108, n=1, na=1, nk=0) at Python/ceval.c:3529 #24 0x80640 in call_function (pp_stack=0xffbef108, oparg=1) at Python/ceval.c:3458 #25 0x7e080 in eval_frame (f=0x177f78) at Python/ceval.c:2116 #26 0x8078c in fast_function (func=0x361670, pp_stack=0x2be170, n=1, na=0, nk=1146912) at Python/ceval.c:3518 ---Type to continue, or q to quit--- #27 0x80640 in call_function (pp_stack=0xffbef2a0, oparg=1) at Python/ceval.c:3458 #28 0x7e080 in eval_frame (f=0x2bdfd0) at Python/ceval.c:2116 #29 0x8078c in fast_function (func=0x2d5af0, pp_stack=0x1ca698, n=1, na=0, nk=1146912) at Python/ceval.c:3518 #30 0x80640 in call_function (pp_stack=0xffbef438, oparg=1) at Python/ceval.c:3458 #31 0x7e080 in eval_frame (f=0x1ca548) at Python/ceval.c:2116 #32 0x7f634 in PyEval_EvalCodeEx (co=0x18cb60, globals=0x0, locals=0x1ca548, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #33 0x82458 in PyEval_EvalCode (co=0x18cb60, globals=0x1329c0, locals=0x1329c0) at Python/ceval.c:537 #34 0xa5488 in run_node (n=0x122158, filename=0x18cb60 "", globals=0x1329c0, locals=0x1329c0, flags=0xffbef804) at Python/pythonrun.c:1267 #35 0xa5434 in run_err_node (n=0x122158, filename=0x18cb60 "", globals=0x1329c0, locals=0x1329c0, flags=0xffbef804) at Python/pythonrun.c:1254 #36 0xa5094 in PyRun_FileExFlags (fp=0x116fb0, filename=0xffbefa3a "testdriver.py", start=1255872, globals=0x1329c0, locals=0x1329c0, closeit=1, flags=0xffbef804) at Python/pythonrun.c:1245 #37 0xa39a8 in PyRun_SimpleFileExFlags (fp=0x116fb0, filename=0xffbefa3a "testdriver.py", closeit=1, flags=0xffbef804) at Python/pythonrun.c:862 #38 0xa4b88 in PyRun_AnyFileExFlags (fp=0x116fb0, filename=0xffbefa3a "testdriver.py", closeit=1, flags=0xffbef804) at Python/pythonrun.c:659 #39 0x1c430 in Py_Main (argc=5, argv=0xffbef8ec) at Modules/main.c:415 #40 0x1bc68 in main (argc=5, argv=0xffbef8ec) at Modules/python.c:23 (gdb) From uthand at hotmail.com Thu Jun 17 03:42:53 2004 From: uthand at hotmail.com (Fritz Bosch) Date: 17 Jun 2004 00:42:53 -0700 Subject: Python interceptor package References: Message-ID: Dominic wrote in message news:.. ... > sys.settrace(...) > (Python interpreter hook), it should do the job. ... What I'm looking for is an Interceptor class whose constructor would interpose its (callable) instance between a caller and a specified function or method, and whose 'destroy' method would remove the interposition. One would typically subclass the Interceptor class to achieve the required interceptor behaviour. sys.settrace looks like a possible starting point to create such a package, allthough it is somewhat indiscriminate for my purposes (I want to be selective about what I intercept). Of course the selection can occur inside the trace function, but the performance penalty may be to large (I need it in a run-time environment, not only in a development environment). I have actually started to experiment with an Interceptor class, whose constructor modifies the __dict__ of a specified class, to 'wrap' its (callable) instance around the specified method. I wanted to make sure, though, that I'm not re-inventing the wheel, and perhaps hear whether anyone would be interested in such a package. So, comments are invited! Regards, Fritz From rigga at hasnomail.com Mon Jun 14 12:48:33 2004 From: rigga at hasnomail.com (RiGGa) Date: Mon, 14 Jun 2004 17:48:33 +0100 Subject: Help with parsing web page Message-ID: Hi, I want to parse a web page in Python and have it write certain values out to a mysql database. I really dont know where to start with parsing the html code ( I can work out the database part ). I have had a look at htmllib but I need more info. Can anyone point me in the right direction , a tutorial or something would be great. Many thanks RiGga From BELLEMAIL-SA at exponent.com Thu Jun 24 00:00:06 2004 From: BELLEMAIL-SA at exponent.com (System Attendant) Date: Wed, 23 Jun 2004 21:00:06 -0700 Subject: [MailServer Notification] To Recipient a virus was found and acti on taken. Message-ID: <8E110A8F4A95AD46AEE54E8A195F0E2CF28F96@bellemail> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = jceasar at tmp.org Recipient(s) = python-list at python.org; Subject = Python-list Digest, Vol 9, Issue 281 Scanning time = 06/23/2004 21:00:06 Engine/Pattern = 7.000-1004/911 Action taken on message: The attachment Msg.zip contained WORM_BAGLE.GEN-1 virus. ScanMail took the action: Deleted. Warning to recipient. ScanMail has detected a virus. From jepler at unpythonic.net Sat Jun 19 09:30:27 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 19 Jun 2004 08:30:27 -0500 Subject: Attention, hyperlinkers: inference of active text In-Reply-To: <10d6bln988rmne6@corp.supernews.com> References: <10d6bln988rmne6@corp.supernews.com> Message-ID: <20040619133025.GA8011@unpythonic.net> I'm pretty sure that this isn't a valid url: file:\I never\used anything\besides windows.txt It's something, but it's not a URL. For actual HTTP URLs, I would suggest that you have a step in the highlighting that considers whether the last part of the URL seems to contain plausible characters. Letters from this set are pretty unlikely: ".,!])}'\"" For these file: faux-URLs, you could again start by parsing the maximum number of characters as the URL, then repeatedly check whether the current fragment exists on disk. If it doesn't, chop off part of it (probably at whitespace) and try again until you get something that exists or your string is empty. If that doesn't work (for instance, you're not in a position to check what exists on the user's disk) then you could try a rule where the hyperlink portion extends from file: at least to the last \, and if the part beyond that is of the form "word word word.ext" then it's included too. Best of luck. This'll probably require a lot of experimentation. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dalcolmo at vh-s.de Mon Jun 28 08:14:40 2004 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Mon, 28 Jun 2004 14:14:40 +0200 Subject: How do I run routines where timing is critical? References: Message-ID: <20040628141440.00005a12@titan> Why can't I read the original posting? this may have something to do with my Newsreader (I am using Sylpheed-Claws-W32 0.9.10 as Mail- and Newsreader), but it may also be related to the source of the mail. Is this perhaps a MS-Outlook specific thing? If someone, who can read the original message (by S. David Rose) can help me (for example by sending the header), this may be useful to debug the problem. - Josef From tzot at sil-tec.gr Wed Jun 2 09:21:18 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 02 Jun 2004 16:21:18 +0300 Subject: getting mimetype of a file References: <4qanb0tlakc4na7rd5nbnh8f4n0d4mrcu1@4ax.com> <8zgvc.32866$Wc.1116383@twister2.libero.it> Message-ID: On Wed, 02 Jun 2004 08:52:20 GMT, rumours say that Matteo Merli might have written: >Christos TZOTZIOY Georgiou wrote: > >>>> is there any way to determine the mimetype of a file using ruby? >> [snip] >>>=P just realized I sent this to the wrong list. as long as I'm here... how >>>is it done in python? >> >> The mimetypes.py module in the standard library is your friend. ...if one wants to judge by the filename only (I wasn't clear earlier). >A more effective approach would be to use the "magic" module that come >with the "file" utility (it is present in the sources, but not built by >default). >This way you can perform a fine-grained recognition of files.. Indeed. One such attempt (mine) to use the "magic" file from python can be found here: http://www.sil-tec.gr/~tzot/python/ -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From jepler at unpythonic.net Thu Jun 17 09:05:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 17 Jun 2004 08:05:03 -0500 Subject: Using metaclasses to play with decorators. In-Reply-To: References: <95aa1afa.0406152046.40365035@posting.google.com> Message-ID: <20040617130502.GD5146@unpythonic.net> On Wed, Jun 16, 2004 at 04:18:53AM -0700, David MacQuigg wrote: > I haven't given this much thought, but it occurred to me that making > the __new__ function work in an ordinary class ( not just a metaclass > ) would avoid the need for metaclasses in simple cases like my > example. [...] __new__ does work in an "ordinary class"! It just does something different than what you want. Here's a small "rational number" class where Rational(x, y) returns an int if x/y is an integer, or a Rational instance otherwise. class Rational(object): def __init__(self, num, den=1): self.num = num self.den = den def __new__(self, num, den=1): if num % den == 0: return int(num) else: return object.__new__(Rational) def __str__(self): return "%d/%d" % (self.num, self.den) # Example r, s = Rational(6, 3), Rational(6, 4) print r, type(r) # It's an int print s, type(s) # It's a Rational -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ptmcg at austin.rr._bogus_.com Wed Jun 23 09:58:04 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 23 Jun 2004 13:58:04 GMT Subject: Parsing C Preprocessor files References: <20040623140151.6b8863f2@pistache.sara.nl> Message-ID: "Bram Stolk" wrote in message news:20040623140151.6b8863f2 at pistache.sara.nl... > Hi there, > > What could I use to parse CPP macros in Python? > I tried the Parnassus Vaults, and python lib docs, but could not > find a suitable module. > > Thanks, > > Bram > Try pyparsing, at http://pyparsing.sourceforge.net . The examples include a file scanExamples.py, that does some simple C macro parsing. This should be pretty straightforward to adapt to matching #ifdef's and #endif's. -- Paul (I'm sure pyparsing is listed in Vaults of Parnassus. Why did you think it would not be applicable?) From kirk at strauser.com Fri Jun 11 15:10:08 2004 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 11 Jun 2004 19:10:08 GMT Subject: Inheritence confusion (was Re: Deeply-nested class layout suggestions wanted) References: <87oenrq6vy.fsf@strauser.com> <873c52c6vh.fsf@strauser.com> Message-ID: <87vfhxc3rx.fsf_-_@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 As a final concrete example, I whipped up a few little skeleton classes like so: Generic |-- Subclass | |-- __init__.py | |-- a.py | `-- b.py |-- __init__.py |-- a.py `-- b.py Generic/a.py from b import b class a: def __init__(self): test = b() Generic/b.py class b: def __init__(self): print 'In Generic.b' Generic/Subclass/a.py import Generic.a class a(Generic.a.a): pass Generic/Subclass/b.py import Generic.b class b(Generic.b.b): def __init__(self): print 'In Subclass.b' Now, whether I instantiate Generic.a.a or Generic.Subclass.a.a, it references the Generic.b module instead of the Generic.Subclass.b module: >>> import Generic.a >>> Generic.a.a() In Generic.b >>> import Generic.Subclass.a >>> Generic.Subclass.a.a() In Generic.b >>> I'm completely lost. What do I have to do to get the subclasses to use modules at their own level instead of where the defined __init__ function happens to be? - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAygLp5sRg+Y0CpvERAsC/AJ4yKvfmVXp3ppEizUTq3k/8PzJqsQCcCWin 25z6qeK3UokOPcsegW+YVes= =gsuH -----END PGP SIGNATURE----- From o-zone at zerozone.it Tue Jun 22 05:50:54 2004 From: o-zone at zerozone.it (O-Zone) Date: Tue, 22 Jun 2004 11:50:54 +0200 Subject: Python and MP3 Message-ID: Hi all, i'm looking for an MP3 player/library in Python/wxPython to use in a multiplatform program. Someone can help me ? Oz -- ------ O-Zone ! (C) 2004 http://myphotos.zerozone.it << MyPHOTOS GPL Photo Blog ! Join now ! From tim.one at comcast.net Sun Jun 13 14:04:52 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jun 2004 14:04:52 -0400 Subject: How to get decimal form of largest known prime? References: <40cc8deb$0$563$e4fe514c@news.xs4all.nl> Message-ID: <-N6dnc_ka_7JClHdRVn-gg@comcast.com> [Irmen de Jong] > In fact, what algorithm is Python itself using when you try to: > > >>> print 2**24036583 - 1 > > ?? Recent Pythons convert to base 10000 internally by repeated division, along the lines of # Convert integer i > 0 to decimal string. result = [] while i: i, digit = divmod(i, 10000) s = str(digit) if len(s) < 4 and i: s = "0" * (4 - len(s)) + s result.append(s) result.reverse() return "".join(result) That's an approximation. The C code doesn't actually build a list, or reverse it, or do a join(), and does the repeated divisions in a single, reused memory area. See long_format() in longobject.c for details. Older Pythons did much the same, but with base 10, and allocated fresh memory for each little division. Both methods are quadratic-time, but modern Pythons do a fourth the number of "little long division" steps. By "little" I mean that Python's longs are represented in base 2**15 internally, so division by 10000 is division by a single internal digit, which is especially simple. It's as cheap to divide a long by 10000 as by 10 -- they're both "single digit" divisors internally. From martin at v.loewis.de Sun Jun 13 06:01:11 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jun 2004 12:01:11 +0200 Subject: does python have useless destructors? In-Reply-To: References: Message-ID: <40CC25E7.7080608@v.loewis.de> Michael P. Soulier wrote: > As soon as I heard about not being able to trust destructors, I was > shocked, because I do rely on guaranteed finalization, and I also > consider it to be very elegant. "Guarantee" and "able to rely on" are different things, actually. A guarantee is something that someone gives you, which they might not do even though they could. For example, you can rely on sunset to occur before midnight, but nobody might give you a guarantee for that. So the Python language specification does not guarantee anything about invoking __del__. However, you can still rely on C-Python 2.3.4 invoking it eventually. More precisely, C-Python 2.3.4 (and most other releases of C-Python) will invoke __del__ if the last reference to an object goes away. A reference goes away if: - the variable is del'ed, or a different value is assigned, or - the variable is a local variable, and the function terminates through a return (if the function terminates through an exception, a traceback object is constructed which takes over the local variable). - the variable is attribute of an object, and the object goes away - the variable is an implicit variable in the interpreter, and gets a new value. Some of the implicit variables are: - the current exception and traceback - the last exception and traceback - the sys module - the codecs module > myfile = open("myfilepath", "w") > myfile.write(reallybigbuffer) > myfile.close() > > If the write fails due to a lack of disk space, the exception will > prevent the explicit close() from happening. Now, if myfile goes out of > scope, I would hope that the file object is destroyed and thus the file > is closed, but after reading the python documentation, it seems that > the only way to guarantee closure of the file is using the mentioned > try/finally construct... C-Python 2.3.4 will close the fil if myfile goes out of scope, unless there is an exception, in which case myfile is referred to in the traceback, in which case the file is closed when the traceback object is released, which happens when the exception handler for the exception has completed. If the exception was put out through PyErr_Print, the object stays alive through sys.last_traceback, where it stays until the next exception occurs. Regards, Martin From ludo at asiatica.org Tue Jun 1 20:03:26 2004 From: ludo at asiatica.org (Ludovico Magnocavallo) Date: Wed, 02 Jun 2004 02:03:26 +0200 Subject: HTTP Proxy server in python In-Reply-To: References: Message-ID: <2i4jmoFit192U1@uni-berlin.de> Muhammad Ali wrote: > I am thinking of doing a proxy server for this purpose in python that will have > a list of users and their hours, and would require logging in by the user, calculate > their times etc. > > So, is this the best way of doing this? if not what else can be done? (what ever the > solution, i would like to implement in python) A list of proxy servers implemented in Python can be found here http://xhaus.com/alan/python/proxies.html L. From Scott.Daniels at Acm.Org Tue Jun 15 03:27:08 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 15 Jun 2004 00:27:08 -0700 Subject: thread help In-Reply-To: References: Message-ID: <40cea9cb$1@nntp0.pdx.net> Aahz wrote: > Bart Nessux wrote: >>Could someone show me how I can make this work correctly? I want to probe >>64 unique IP address for HTTP servers simultaneously, ... > Create a threading.Thread subclass that takes one IP address and a list > of ports to scan. Start 64 instances of this class, each with a > different IP address. An alternative is to create a que into which you push IP addresses to contact, and have each thread read addresses off the queue when they are free to process them. This has the advantage of decoupling the number of threads from the number of addresses you want to examine. -Scott David Daniels Scott.Daniels at Acm.Org From nhirsh2 at ieee.org Sat Jun 12 00:32:32 2004 From: nhirsh2 at ieee.org (Neale) Date: 11 Jun 2004 21:32:32 -0700 Subject: Newbie array question Message-ID: <2d7af4f8.0406112032.4cb4438a@posting.google.com> My first task with Python is to scan multiple small text files and "batch together" those records with a "5" or "6" in column 2, and then save as a new file. The records are 256 characters. I know it sounds like a homework problem, but it's not. My math brain wants to dump all the records into a big 2-D array and sort on the second column. Then "compress out" all the records whose second character isn't "5" or "6". Easy to say. Is this the right strategy for using Python? Does it even have a "compress out" function? From fishboy at spamspamspam.com Sun Jun 6 02:42:19 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 06 Jun 2004 06:42:19 GMT Subject: FTPS ( FTP over SSL) Problem with Python's builtin SSL References: <19804fd8.0406041415.113feb0c@posting.google.com> Message-ID: On 4 Jun 2004 15:15:10 -0700, k.robert at gmx.de (Robert) wrote: >I need to run FTP over SSL from windows (not shitty sftp via ssh etc!) >as explained on >http://www.ford-hutchinson.com/~fh-1-pfh/ftps-ext.html (good variant >3: FTP_TLS ) > I'm curious. How is sftp bad for you? ><{{{*> From eddie at holyrood.ed.ac.uk Mon Jun 14 07:12:11 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 14 Jun 2004 11:12:11 +0000 (UTC) Subject: Multithreaded Telnet sessions References: <1a7605a1.0406131639.6951ca0d@posting.google.com> Message-ID: linux at myprincesspearls.com (Richard Bird CCNP, CCDP, MCSE, etc.) writes: >I need some help adding multithreading to an existing python script. >The script was developed to telnet and make changes on a list of cisco >routers. >I figure that by adding multithreading, I'd be able to telnet to >several routers concurrently and speed up the process of making >changes. >Is this feasible using python with its standard telnet lib? Yup. Here's the skeleton of code that I use to pull the ARP table from a bunch of Cisco routers. --------------------------------------------------------------------------- from threading import Thread, currentThread # example of how to show which router an error occured on def warn (msg): stderr.write ('%s::%s\n' % (currentThread.getName(),msg)) # code to do things to the router def do_router_things (rtr): # open connection ... # do the stuff # close connection # all done # start a thread for each router threads = [] for rtr in ...: th = Thread(name=rtr, target=do_router_things, args=(rtr,)) th.start() threads.append (th) # wait for all threads to finish for th in threads: th.join() --------------------------------------------------------------------------- Though if the processes were as independent as that I would just use a separate process for each one (on Unix anyway). If you're collecting data that needs to be processed then you would probably use a Queue.Queue, pass the data INTO the Queue from do_router_things and have one more thread that pulls items FROM the Queue. HTH, mail me if you'd like more help. Eddie From edvard+news at majakari.net Wed Jun 16 09:20:17 2004 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 16 Jun 2004 16:20:17 +0300 Subject: somewhat OT: function to produce n as distinct colors as possible References: <87pt7zrkcp.fsf@titan.staselog.com> Message-ID: <87r7sfy6zy.fsf@titan.staselog.com> "Mitja" writes: > I'd start with the HSI (aka HSL) model and distribute hues evenly. Don't > know if that's the best solution what with all the stuff going on in our > brain mangling our perception, but it should be close. > Have a look at google for the HSI model and its conversion to RGB. Thanks for the tip. After a little fiddling I ended up with a very simple algorithm which uses hsv color model (hue, saturation and value). The python module colorsys uses floats in the range [0..1.0], so I started with all values at 1, and decrement h and v by step (1.0 / n, where n = number of distinct colors) every turn. Note that I don't touch value component. I get quite nice values when n < 10. After that it gets worse, but at n = 20 colors it is still possible, if not easy, to separate a color from another. But the algorithm could be better for sure. For one thing, I don't see dark brown anywhere, and it would be easy to separate from other colors (even when n = 20). # simple test for producing n different colors. Prints out a very simple # (and probably not valid) web page with differently colored table cells. import colorsys import sys def float2dec(color): return int(color*255) def dec2hex_str(rgb): return "%06x" % (rgb[0]*256**2+rgb[1]*256+rgb[2]) def distinct_colors(n): colors = [] step = 1.0/n h, s, v = (1, 1, 1) for i in range(n): r, g, b = map(float2dec, colorsys.hsv_to_rgb(h, s, v)) colors.append((r, g, b)) h, s, v = (h-step, s-step, v) if h < 0: h = 0 if s < 0: s = 0 if v < 0: v = 0 return map(dec2hex_str, colors) # main color_count = int(sys.argv[1]) print """\ %s \t\ """ % "Printing %d distinct colors" % color_count i = 0 for color in distinct_colors(color_count): i += 1 if i % 8 == 0: print '\t\t\n\t\n\t' % color else: print '\t\t' % color print """\ \t
    test area
    test area
    \ """ -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! "Debugging is twice as hard as writing the code in the firstplace. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian W. Kernighan From gandalf at geochemsource.com Tue Jun 15 07:37:40 2004 From: gandalf at geochemsource.com (Gandalf) Date: Tue, 15 Jun 2004 13:37:40 +0200 Subject: Interfacing Python crypto library Message-ID: <40CEDF84.1040509@geochemsource.com> Hi All! I have an interesting problem here. I have written a Delphi program that should connect to a server written in Python. I'm using a package called DCP for encryption in Delphi and the well known pycrypto library in Python. Delphi lib: {* DCPcrypt v2.0 written by David Barton (crypto at cityinthesky.co.uk) **********} Python lib: http://sourceforge.net/projects/pycrypto For example, the SHA1 algorithm of DCPCrypt and Python seems to be binary compatible. I want to use a symmetric cipher in CFB (8 bit) mode. Using the same key, cipher type (Blowfish) and the same plaintext, these libraries return different ciphertext values. Is there a way to make them binary compatible? I do not insist on these two libraries. If somebody can tell me two libraries that can work together with Delphi and Python that will be perfect. I would be satisfied with a stand-alone cipher too. The main point here is that my Delphi program will be a native windows application. I do not want to install Python and I do not want to use Python4Delphi on the client machines. Any ideas welcome. Best, Laszlo Nagy From rswerdlow at transpose.com Tue Jun 15 16:35:03 2004 From: rswerdlow at transpose.com (Bob Swerdlow) Date: Tue, 15 Jun 2004 16:35:03 -0400 Subject: Proper way to kill child processes Message-ID: <092701c45318$40ca3250$046fa8c0@RSWERDLOW800> My application starts up a number of processes for various purposes using: self.popen = popen2.Popen3("/usr/local/bin/python -O "myscript.py") and then shuts them down when appropriate with os.kill(self.popen.pid, signal.SIGTERM) Everything works fine on MacOSX. However, I'm doing a port to Solaris (so I can run it on my web site) and find that the child processes are not stopping! Solaris is creating TWO new processes: one for the SHELL and then another started by the shell to run my Python script. The os.kill() is killing the shell process, not the one running my Python code. Actually, I really want to kill both of these processes, but I only have the pid for the shell process. I cannot kill the whole process group because that kills the main process, too (I tried it). So, what is the best way to kill both the shell process (whose pid is available from the Popen3 object) and its child process that is running my Python script? It looks like the python script process id is always one greater than the shell process id of the shell process, but I'm sure I cannot rely on that. Thanks, Bob Swerdlow COO Transpose rswerdlow at transpose.com 207-781-8284 http://www.transpose.com ---------------------------------- Fight Spam! Add this link to your signature (as I did): http://wecanstopspam.org Click through to find out more. ---------------------------------- From irmen at -nospam-remove-this-xs4all.nl Sat Jun 12 16:46:53 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 12 Jun 2004 22:46:53 +0200 Subject: setlocale returns error In-Reply-To: References: Message-ID: <40cb6bbd$0$36860$e4fe514c@news.xs4all.nl> transam wrote: > I use Mandrake linux 10 with German setup, Hungarian Keyboard. > My Python is python 2.3.3. [...] > and it fails with the unsupported message for: > fr_FR, nl_NL, es_ES, hu_HU as xx_YY > > What can be the problem here? Nothing to do with Python. Enter this (as root): $ urpmi locales-hu locales-fr locales-nl locales-es --Irmen From matt at themattfella.zzzz.com Wed Jun 2 23:29:58 2004 From: matt at themattfella.zzzz.com (Matt) Date: Thu, 03 Jun 2004 03:29:58 GMT Subject: How to demonstrate bigO cost of algorithms? In-Reply-To: References: Message-ID: Rusty Shackleford wrote: > All help is welcome. For quicksort, you should see ((n log(n))/runtime(n)) approach some constant as you increase n. From rogerb at rogerbinns.com Thu Jun 24 00:51:48 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 23 Jun 2004 21:51:48 -0700 Subject: Can anyone confirm this modulefinder bug? References: <8yeet8w2.fsf@python.net> Message-ID: Thomas Heller wrote: > > Yes, I can confirm this (Python 2.3+, linux x86). > > The problem appears to be this: > > > > > > > compile("# -*- coding: mbcs -*-", "", "exec") > > Traceback (most recent call last): > > File "", line 1, in ? > > MemoryError > > > > > > > For Windows, it's possible to also trigger it: > > > > > compile("# -*- encoding: abc -*-", "", "exec") > Traceback (most recent call last): > File "", line 1, in ? > MemoryError > > > > > > Who files the bug? I believe Anthony Tuininga will be filing it. I originally was using cx-Freeze on Linux and reported the issue on that mailing list. Anthony also found it to be present in Python 2.4 CVS and volunteered to report it. Roger From NOSPAM at easyconnect.fr Fri Jun 4 04:29:02 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Fri, 4 Jun 2004 10:29:02 +0200 Subject: compiling python with unix Message-ID: <40c033e0$0$2277$afc38c87@news.easynet.fr> I would like to understand what python needs to work on unix. And to understand how i can make it smalest possible? I dont understand at all setup. I searched in python.org and in sources but it is not clear at all for me. Can python run with a posix C compiler and minix or something like that ? Thanks From chrisks at NOSPAMudel.edu Sun Jun 27 07:39:43 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sun, 27 Jun 2004 07:39:43 -0400 Subject: Persisting Dynamic Objects? In-Reply-To: References: Message-ID: Miki Tebeka wrote: > Hello Chris, > > >>Out of a somewhat academic interest, I've created a rudimentary module >>for persisting dynamically created objects and data structures in plain >>Python source code. Presently, it's a little under a thousand lines of >>code. It's still a work in progress and has several limitations but it >>is producing results. Is there any interest for me to clean it up and >>publicly release it? > > Can you say why does it differ/better from pickle? > > Bye. That's a good question. And it's not necessarily better than Pickle in all cases. However, one obvious advantage it has is that it saves data in a human readable format, Python source code. My primary reason for writing this is for AI code generating applications. It's easier to see what's generated if it's stored as plaintext. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jun 24 13:47:03 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 24 Jun 2004 19:47:03 +0200 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: <40db139c$0$48959$e4fe514c@news.xs4all.nl> Tim Golden wrote: > | I'm trying to have some scripts run periodically on Windows > | XP and found the "Task Scheduler" did not execute my scripts. > | My scripts are of the form scriptName.py, and will run just > | by invoking that name in the Command Prompt. > | > | Has anyone used the Windows Task Scheduler to run .py > | scripts, and if so is there some intracacy to it? > | > | Is there a more UNIX version of a cron program one can run on Windows? > > > Others have already responded on using the Task Scheduler, > and maybe you've already set yourself up that way. There > certainly are cron-like programs on Win32 (and, let's face > it, it's not hard to write your own). But I'm initially > very pleased with Irmen de Jong's Kronos from > http://www.razorvine.net/download/kronos.py. Thanks for that :) Kronos could use a bit of extra testing. Mind you that you will have to have it running to execute the tasks you schedule. This is rather obvious, but if the original poster wants to run scripts without having to take care of this himself, it's a bit of a problem. > tasks. It wouldn't be at all hard to read the info from > a crontab-style file at startup (don't know if Irmen's > already working on anything like that). I'm not. Kronos is meant to be an "embedded" scheduler. But, as you say, it would be rather trivial to parse a config file at startup time, where a bunch of tasks are defined. Tip: you can use os.system as the task action.... ;-) --Irmen From esj at harvee.org Mon Jun 7 20:59:21 2004 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 07 Jun 2004 20:59:21 -0400 Subject: Python Wiki & wiki Hosting? In-Reply-To: References: <20040605115256.1749992717.eric@zomething.com> Message-ID: A. Lloyd Flanagan wrote: > While I like your suggestion for better editing, I've got to point out > that I think your real problem was that the pages "became quite > large". It would be much more "wiki-correct" to make a larger number > of small pages, with many links between them. Easier to use _and_ > maintain. Thank you for raising that point. What you are describing is a higher level of operation above just formatting text and its presentation. so question now becomes how do you make these meta operations of partitioning and showing connectedness visible and *easy to do right*? I believe the pages grew large (and large in my definition is over 1k characters given the crippled nature of text areas)because people want to keep connectedness between different components visible and there was no easy way to do this. For example, a list of product requirements tends to grow and really is an atomic element. how would you split that and partition information in a way that is useful to someone who doesn't already know what's there. This is getting rather far afield from Python and related topics so I would not be offended if folks want to drop it or take it to private e-mail. ---eric From mediocre_person at hotmail.com Sat Jun 12 10:45:21 2004 From: mediocre_person at hotmail.com (Mediocre Person) Date: Sat, 12 Jun 2004 14:45:21 GMT Subject: Teaching Python In-Reply-To: References: <513d6f09f74eb423c810692fb7bb1f46@news.teranews.com> Message-ID: Python is an excellent introduction to object oriented ideas and > methodology, but if the students already know VB, they have already > learned object oriented programming, right? Well, there's OOP and then there's OOP, right? The first year students have learned to _use_ pre-defined objects, but not design and create classes. You state, "Python is REALLY easy to learn. Your concern should probably be: "are they going to learn this so quickly that I run out of material in a month?" I've seen 6th graders learn to write relatively impressive, object-oriented python programs within about 2 months." Can you give me some references to this, such as samples of student work? I would like to see what grade 6 students can do in two months! I agree that the syntax of Python makes it is easy to learn. However, I think I've got a pretty good imagination where material is concerned! There are excellent tie-ins to their mathematics, physics, chemistry, and biology curricula. For instance, I recently came across the concept of partitions in number theory, and computing all the partitions of an integer is a dilly of a pickle of a problem! And, of course, it's really not about the language, in the end, after all, but what you can learn to do with it. In which case, you say, "AHA--so what was wrong with c++???" In a word, nothing. And I'll *miss* all the lovely memory management lessons we did to develop our own vector and list classes. In the end, I think the change is mostly for me! I know nothing about ocaml or haskell, but I'll be sure to research them this summer, so thanks for the tip! Nick. > > If you do end up teaching python to advanced programming students, you > might want to look at David Mertz' 'charming python' articles. He deals > with a few rather sophisticated and interesting concepts, which managed to > spark a few insightful paradigm shifts (for me at least): > http://gnosis.cx/publish/tech_index_cp.html > > -- SegPhault From qrczak at knm.org.pl Wed Jun 9 08:44:38 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Wed, 09 Jun 2004 14:44:38 +0200 Subject: The __unicode__ method in the C API, and other __-methods Message-ID: I made a bridge between my language Kogut and Python, which gives my language instant access to Python libraries. There is a minor annoyance in the C API: the __unicode__ method does not have its own slot in type objects, it's not treated specially like __str__. /* XXX As soon as we have a tp_unicode slot, we should check this before trying the __unicode__ method. */ if (unicodestr == NULL) { unicodestr= PyString_InternFromString( "__unicode__"); if (unicodestr == NULL) return NULL; } func = PyObject_GetAttr(v, unicodestr); Strings in Kogut are Unicode only. Thus on one hand I must use the equivalent of the above code when I want to convert an arbitrary Python object to a Python Unicode object, and on the other hand the implementation of tp_getattro of Kogut objects wrapped in Python has a special case, only one special case, which checks for "__unicode__" and returns the appropriate convert-to-Unicode bound method instead of forwarding the attribute access to the original object. Could __unicode__ have its slot in the C API in future Python versions? This is the only missing method of this kind I suppose. * * * Unless I count iteritems. The problem is that in Kogut iteration over a dictionary gives key-value pairs, where in Python it defaults to iterating over keys. The standard dict type provides iteritems, which does not have a C API equivalent. Currently iterating over a Python dictionary from Kogut produces key-value pairs, because this is what Kogut expects - I call iteritems through PyObject_GetAttr. Iterating over a Kogut dictionary from Python is somewhat wrong, because it blindly returns what the Kogut iterator produces, that is: pairs (and they even can't be automatically converted to Python pairs, unless I treat this case specially). I think I will fix it and return keys only when the Kogut object is a dictionary. * * * Maybe the wrapped objects should support all these __-methods. I mean, for example len(obj) works (it calls the C slot which calls the Size function in Kogut), but obj.__len__ doesn't work (it tries to blindly access the attribute named __len__ in Kogut, which doesn't exist). Is that wrong? Does Python code assume that len(obj) is equivalent to obj.__len__()? Improving this would be tedious, because I would have to make bound methods myself. I can't use PyObject_GenericGetAttr because I must forward regular attribute lookup to Kogut, so I would probably have to code everything by hand. Also I don't known which methods are available without trying to call them, so all objects would have the __len__ slot, with for non-collection objects throws an exception when applied. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From eurleif at ecritters.biz Sun Jun 6 22:58:09 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 07 Jun 2004 02:58:09 GMT Subject: Dynamically adding methods to objects? In-Reply-To: <29381ecf.0406052305.5b558d24@posting.google.com> References: <29381ecf.0406052305.5b558d24@posting.google.com> Message-ID: <5RQwc.3026$Hf.1732810@newshog.newsread.com> damian birchler wrote: > I'm wondering if it is possible to automatically dynamically add > methods to a class instance. Try something like this: import new class Foo(object): def add_method(self, name, prints): """Add a method to the class which prints a string. Arguments: name - the name of the method prints - the string the method should print """ def method(self): print prints method = new.instancemethod(method, self, Foo) setattr(self, name, method) instance = Foo() instance.add_method('foo', 'I am foo. Fear me!') instance.add_method('bar', "I am the humble bar. Please don't hurt me.") instance.foo() instance.bar() From dmq at gain.com Tue Jun 1 07:43:26 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 01 Jun 2004 04:43:26 -0700 Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> <0dqkb09bc54jlo8m9aqcosei5p7olccvec@4ax.com> Message-ID: On 1 Jun 2004 09:57:28 GMT, Duncan Booth wrote: >David MacQuigg wrote in >news:0dqkb09bc54jlo8m9aqcosei5p7olccvec at 4ax.com: < example assuming the desired method is defined in Shape: > > Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) > Shape.fromCenterAndSize(Ellipse, 10, 10, 3, 4) > Shape.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) > Shape.fromCenterAndSize(TextLabel, 10, 10, 3, 4) < snip long discussion showing why this is not a good assumption. > > Rectangle.fromCenterAndSize(Rectangle, 10, 10, 3, 4) > Ellipse.fromCenterAndSize(Ellipse, 10, 10, 3, 4) > OffsetRectangle.fromCenterAndSize(OffsetRectangle, 10, 10, 3, 4) > TextLabel.fromCenterAndSize(TextLabel, 10, 10, 3, 4) > >Now we have a consistent interface again. The only problem with this is >that we have duplication in the call. That is easily fixed though by >switching to class methods and you get back to my code. I can still replace this more easily with: for cls in Rectangle,Ellipse,OffsetRectangle,Textlabel: cls.fromCenterAndSize(cls, 10, 10, 3, 4) However, if you change this example so all the arguments are different, then you have made your point. Class methods can avoid much duplication of class names. >One more point. You said in an earlier post: > >> I would change the classmethods to staticmethods, however, and avoid >> the need to teach classmethods. > >If you are going to teach your students how to create objects in Python you >will need to explain the __new__ method. __new__ is automatically a class >method, so there is no way you can avoid teaching class methods. You can >however avoid teaching static methods. Actually, __new__ is a staticmethod. According to GvR in http://python.org/2.2.3/descrintro.html#__new__ ''' Factoid: __new__ is a static method, not a class method. I initially thought it would have to be a class method, and that's why I added the classmethod primitive. Unfortunately, with class methods, upcalls don't work right in this case, so I had to make it a static method with an explicit class as its first argument. Ironically, there are now no known uses for class methods in the Python distribution (other than in the test suite). However, class methods are still useful in other places, for example, to program inheritable alternate constructors. ''' Static methods are needed whenever you want to call a method without an instance. True, we could do this with a class method and just ignore the class, but the strange first argument will need further explanation, and will seem odd to students seeing lots of static methods and very few class methods in typical programs. I will probably leave class methods as they are in Learning Python, 2nd ed - in an "advanced" section toward the end of the OOP chapters. I haven't yet decided what to do with __new__ and __metaclass__. I've received a good example of using these to generate classes for the Animals examples, but the Python documentation is poor, and I think I can accomplish the purpose of automatically generating classes with correct attributes, using "factory functions" as your example illustrates. -- Dave From andymac at bullseye.apana.org.au Sat Jun 5 21:40:15 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 6 Jun 2004 11:40:15 +1000 (EST) Subject: Python 2.3.3 signals, threads & extensions: signal handling problem In-Reply-To: References: Message-ID: <20040606112641.V77146@bullseye.apana.org.au> On Thu, 3 Jun 2004, Holger Joukl wrote: > migrating from good old python 1.5.2 to python 2.3, I have a problem > running a program that features some threads which execute calls to > an extension module. > Problem is that all of a sudden, I cannot stop the program with a keyboard > interrupt any more; the installed signal handler does not seem to receive > the signal at all. > This happens both if I rebuild this extension using python 2.3 > headers/library > and if I simply use the old extension (ignoring the API version warnings > :-) Don't mix signals and threads without a lot of careful doc reading and planning. I strongly recommend re-reading the signal module docs. One other thing to keep in mind is that in a multithreaded build, aside from only the main thread receiving signals, is that the signal handler is effectively queued until the next Python VM opcode is processed. A call to a function in the extension is effectively a VM opcode, and if the call doesn't return the handler will never execute. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From jhs at oes.co.th Tue Jun 29 07:24:55 2004 From: jhs at oes.co.th (Jason Smith) Date: Tue, 29 Jun 2004 18:24:55 +0700 Subject: Does Python optimize regexes? Message-ID: <40E15187.7050408@oes.co.th> Hi. I just have a question about optimizations Python does when converting to bytecode. import re for someString in someListOfStrings: if re.match('foo', someString): print someString, "matched!" Does Python notice that re.match is called with the same expression, and thus lift it out of the loop? Or do I need to always optimize by hand using re.compile? I suspect so because the Python bytecode generator would hardly know about a library function like re.compile, unlike e.g. Perl, with builtin REs. Thanks much for any clarification or advice. -- Jason Smith Open Enterprise Systems Bangkok, Thailand http://oes.co.th -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 264 bytes Desc: OpenPGP digital signature URL: From claird at lairds.com Wed Jun 23 14:18:21 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 23 Jun 2004 18:18:21 -0000 Subject: Python for TCLer References: <849e4506.0406230949.605df12e@posting.google.com> Message-ID: <10djibdi5bffi27@corp.supernews.com> In article <849e4506.0406230949.605df12e at posting.google.com>, Bhushit Joshipura wrote: >I am almost brainwashed to forsake TCL for Python. However, I wanted >to ask a few preliminary questions before I jump in. > >The over all picture of my project would look like: > >Front End : TCL scripts - Our API to users (Can't change because of >legacy) >----->Middle Layer : Framework (PYTHONization Target) >Back End: TCL API from vendors (Can't change), in-house Expect API >(can't risk for reliability) > >1. One of my vendors supplies TCL package only. Can I call TCL >procedures from Python back end? What about Expect scripts? > >2. OTOH, all my scripts are in TCL. Can I invoke python from TCL and >retain states in python? > >3. This is closely related to uplevel question already discussed in >this group. We have one control structure in our API that has done >wonders in productivity. I can not let it go. > >Does python let me write a control structure? It looks like: > >set x 10 >set y 5 >controlStructure { > do something with $x until y becomes 3 ;#This is evaluated in >caller's frame >} > >4. Does there exist a mapping of TCL facilities over Python? It will >help me in training man power. Ideal place would describe > >uplevel "..." >would translate to > > >eval "..." >would translate to > > >subst "..." >... > >5. Does Aspect Oriented Extension exist for Python? I know TOS >(http://www.aopsys.com/tos) is no longer maintained for TCL. . . . Yes. The answer to most things is, "Yes". Yes, Python can get at your existing Tcl stuff; in fact, a full Python installation *includes* Tcl, and Python can exe- cute Tcl source in-process! However, Python does NOT encourage new control structures the way some denominations of Tcl does, and I discourage "phrasebooks" for just the reason [uplevel] illustrates: simple-minded transliteration of a Tcl [uplevel] into Python is certain to produce code that's not just non- idiomatic, but unmaintainable and ugly. On the other hand, you'll find a lot to learn and like in Python's control structures, and, if you start building the phrasebook by starting with [eval], [exec], [glob], ..., I'm sure you'll receive plenty of help filling out the entries. -- Cameron Laird Business: http://www.Phaseit.net From Holger.Joukl at LBBW.de Thu Jun 3 08:48:05 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Thu, 3 Jun 2004 14:48:05 +0200 Subject: Python 2.3.3 signals, threads & extensions: signal handling problem Message-ID: Hi, migrating from good old python 1.5.2 to python 2.3, I have a problem running a program that features some threads which execute calls to an extension module. Problem is that all of a sudden, I cannot stop the program with a keyboard interrupt any more; the installed signal handler does not seem to receive the signal at all. This happens both if I rebuild this extension using python 2.3 headers/library and if I simply use the old extension (ignoring the API version warnings :-) Any hints? Btw this is a sun sparc solaris 6 box, python 2.3.3. G Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From zen19725 at zen.co.uk Tue Jun 29 16:14:53 2004 From: zen19725 at zen.co.uk (phil hunt) Date: Tue, 29 Jun 2004 21:14:53 +0100 Subject: Drawing with python. References: <%M_Dc.662$Mq3.12724@news4.e.nsc.no> Message-ID: On Mon, 28 Jun 2004 22:00:01 +0200, moma wrote: >aleator wrote: >> Hello. >> >> What is the recommendable means of producing >> bitmaps with python. Basic primitives I need >> are polygons, antialiased lines and ellipses. >> >> I have tried, so far, GD-module (Very slow) and >> Pygame(Antialiased lines are ugly, pixelated). >> >> I do not necessarily need to produce bitmaps, any image >> that is good for wxpython application and WWW is good >> enough. >> >> - Ville Tirronen > >PIL ? >http://www.pythonware.com/products/pil/ I've used it, and like it (apart from the built-in font, which is crap). -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: zen19725 at zen dot co dot uk) From Mike at DeleteThis.Geary.com Thu Jun 24 12:00:16 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 24 Jun 2004 09:00:16 -0700 Subject: Check if file is overwritten References: Message-ID: <10dlukhim6e6fc9@corp.supernews.com> > | How do i check if a file is overwritten by another program, > | while my script > | is running? > | > | I have to monitor changes and act on them on the fly. > | > | It only has to work on windows, Tim Golden wrote: > Does this help? (Warning: long URL) > > http://tgolden.sc.sabren.com/python/win32_how_do_i/ > watch_directory_for_changes.html Tim, that's a good informative page. One thing you ought to update: The ReadDirectoryChangesW function is available only on the NT platforms (NT 3.51 SP3+, NT4, 2000, XP), not the Win9x platforms (95, 98, Me). -Mike From guettli at thomas-guettler.de Tue Jun 15 10:49:04 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 15 Jun 2004 16:49:04 +0200 Subject: XML: Doctype http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd References: <86isdsrjnd.fsf@stronzo.brainbot.com> Message-ID: Am Tue, 15 Jun 2004 16:16:38 +0200 schrieb Ralf Schmitt: > "Thomas Guettler" writes: > >> Hi, >> >> I want to parse XHTML. >> >> The doctype is http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd. >> >> When I try to parse it with SAX. The parser >> tries to connect via httplib to www.w2.org. > Here's some example code I posted a few days ago, which does exaxtly > what you want. [cut] Thank you! Thomas From etsilig at ilsp.gr Mon Jun 21 08:59:45 2004 From: etsilig at ilsp.gr (Evagelia Tsiligianni) Date: Mon, 21 Jun 2004 15:59:45 +0300 Subject: plot dates, print plotted data Message-ID: <009601c4578f$a0ff1cf0$5101010a@evagelia> Hello! I am trying to find a tool that can plot and print (plotted) data. I need it supports plotting dates as well. I 've tried wxPlot and chaco but each of them applies one of my requests either printing or date plotting. Can anybody help? Thanks Evagelia -------------- next part -------------- An HTML attachment was scrubbed... URL: From fperez528 at yahoo.com Wed Jun 23 17:07:57 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 23 Jun 2004 15:07:57 -0600 Subject: FFT with Python References: Message-ID: Jeremy Sanders wrote: > Of course you probably want to use numarray instead, which is newer and > has further development. Unless speed for small arrays matters, case in which you stick with Numeric until the Numarray constructors and some other functions get rewritten in C (post 1.0). Numarray works great (and is better documented, cleaner, etc) for the 'few large arrays' case. It has problems for the 'many small arrays' type of code. That's why SciPy hasn't switched to Numarray. Numarray is being written by the Hubble crowd, so it makes sense that they'd optimize their usage cases first (astronomy images are the 'few big arrays' kind of code). Just a small precision. And for the OP, scipy wraps fftw for you, as well as including a raft of other signal-processing oriented things. And it makes sure to do use ATLAS build of lapack. hth, f From rlbuvel at gmail.com Sat Jun 12 14:41:00 2004 From: rlbuvel at gmail.com (Ray Buvel) Date: Sat, 12 Jun 2004 13:41:00 -0500 Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> <7xhdtgzrtn.fsf@ruckus.brouhaha.com> Message-ID: <26Iyc.1689$WX1.208@twister.rdc-kc.rr.com> Paul Rubin wrote: > Does Numeric make a way to divide one polynomial by another? > > It occurs to me that I'd also like to do polynomial arithmetic over > finite fields, i.e. in GF(2**n)[x] for small n. I realize that's a new > request but I wonder if you know of anything. Thanks. I don't think Numeric supports polynomial division. However, I have a couple of Python classes that implement polynomial arithmetic. One is generic and can be used with the gmpy (http://gmpy.sourceforge.net/) module to get exact results. Or, you can implement a class for the field of interest to you. The other class implements polynomials over the field of the integers mod 2. Both support the usual operations of + - * / % and also compute the derivative. The string representation shows the polynomial with x as the variable. These modules are too big to post so if anyone wants them, send me an email requesting them. Ray Buvel From jacek.generowicz at cern.ch Fri Jun 4 10:49:44 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 04 Jun 2004 16:49:44 +0200 Subject: C compiler written in Python References: <20040602233207.4bc48ffa@localhost> <10bucdrn3obj8d4@corp.supernews.com> <10c12igm2nsl4e9@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: > Thanks. > You're perhaps more familiar with Perl's Inline::. How dare you cast such false aspersions upon my person! :-) From aahz at pythoncraft.com Mon Jun 14 17:25:12 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2004 17:25:12 -0400 Subject: does python have useless destructors? References: Message-ID: In article , David Turner wrote: > >In fact, the RAII idiom is quite commonly used with heap-allocated >objects. All that is required is a clear trail of ownership, which is >generally not that difficult to achieve. Not really. What you're doing is what I'd call "virtual stack" by virtue of the fact that the heap objects are being managed by stack objects. >Here's some C++ code I wrote recently: > >typedef boost::shared_ptr file_ptr; >typedef std::stack file_stack; > >file_stack files; > >files.push(file_ptr(new std::ifstream(file_to_compile))); >while(!files.empty()) >{ > std::ifstream& f = files.top().get(); > token << f; > if (token == Token::eof) > files.pop(); > else > parse(token); >} > >The RAII object in this case is std::ifstream. What I have is a stack >of file objects, wrapped in the reference-counting container >boost::shared_ptr. I know that the files will be closed no matter >what happens in the while() loop, because the ifstream class closes >the file when it is destroyed. It will be destroyed by shared_ptr >when the last reference disappears. The last reference will disappear >(assuming stored another reference in some outer scope) when the >"files" container goes out of scope. > >It's pretty darn hard to mess something like this up. So yes, you >*can* use heap-based objects as RAII containers. It's pretty darn easy: what happens when you pass those pointers outside of their stack holders? That's a *normal* part of Python programming; changing that requires a whole new paradigm. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From sjdevnull at yahoo.com Thu Jun 24 14:41:08 2004 From: sjdevnull at yahoo.com (G. S. Hayes) Date: 24 Jun 2004 11:41:08 -0700 Subject: Keyword arguments and user-defined dictionaries References: <96c2e938.0406231629.4103ccde@posting.google.com> Message-ID: <96c2e938.0406241041.5c1cd16e@posting.google.com> "Larry Bates" wrote in message news:... > Remember that ** syntax passes each member of the > dictionary as a separate keyword argument. Right, that's what I'm trying to do (hence the Subject). Turns out that ** bypasses the object methods and grovels internally in the builtin dict. So I either need to de-Lazify the values in my dict before I make the ** call or change the code I'm calling to accept a dictionary (tougher since it's a large body of 3rd-party code). Thanks for your time! From max at alcyone.com Fri Jun 18 21:48:03 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 18 Jun 2004 18:48:03 -0700 Subject: Game - Map data structures References: Message-ID: <40D39B53.13F679FF@alcyone.com> Sam Holden wrote: > That's going to make it really hard to determine which boats are on a > given water tile. Surely if you're dealing with populating a grid of things with objects, you're not going to do so by holding objects in each slot. You'll implement some sort of sparse array, instead. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ We must use time as a tool, not as a crutch. -- John F. Kennedy From klausm0762 at yahoo.de Fri Jun 4 09:01:19 2004 From: klausm0762 at yahoo.de (Klaus Momberger) Date: 4 Jun 2004 06:01:19 -0700 Subject: Why did no one invent Python before? References: Message-ID: <80a8af7d.0406040501.6baeb2a1@posting.google.com> j_mckitrick at bigfoot.com (j_mckitrick) wrote in message news:... > > - much better development environment; you really don't know what you're > > missing until you've used smalltalk's browsers, inspectors and > > debuggers. It's the main thing I really, really miss in python. > > I keep hearing about this Smalltalk IDE. What is really the big deal, > and why hasn't MS ripped it off? I tried to find screenshots but > couldn't. I also applied for a demo download, but never heard back > from the company. > > jonathon Cincom is offering a personal-edition of their product: http://smalltalk.cincom.com/downloads/index.ssp then there is Smalltalk/X : http://www.exept.de/sites/exept/english/Smalltalk/frame_uebersicht.html both of them are fully-fledged Smalltalks, not demos. -klaus From peter.maas at mplusr.de Tue Jun 29 11:21:12 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 29 Jun 2004 17:21:12 +0200 Subject: file compression In-Reply-To: References: Message-ID: Elaine Jackson schrieb: > "Peter Maas" wrote in message > news:cbr73f$6s2$1 at swifty.westend.com... > > > Hi. Thanks for responding. Your example looks completely reasonable, but when I > try it I get the following error message: > > TypeError: read() takes exactly 2 arguments (1 given) > > Does this make any sense to you? Replace contents = z.read() by contents = z.read(nameOfFileInArchive) An archive is a collection of files. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 eMail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From manatlan at online.fr Fri Jun 25 03:16:09 2004 From: manatlan at online.fr (marco) Date: Fri, 25 Jun 2004 09:16:09 +0200 Subject: a small-gui for python/win32 ? In-Reply-To: <40db01fb$0$17144$626a14ce@news.free.fr> References: <40db01fb$0$17144$626a14ce@news.free.fr> Message-ID: <40dbd139$0$29367$626a14ce@news.free.fr> marco a ?crit : > this week, i've seen a little GUI for python/win32 .. > a little library which can use simple dialog (openfile, opendir, > messagebox, progressbar ... and that's all) ... > it worked only on win32 platform > > AND i've not bookmarked the url ;-( (shame on me) > > i've seen that in "daily python url" perhaps ??! > i cant find it again ;-( > > perhaps someone could help me ? > (don't tell me about tk, wx, qt, gtk ... ;-) YES ... i found it again ... and bookmarked too !!!! its name is "easydialog", and is here : http://www.averdevelopment.com/python/EasyDialogs.html thanx for all your answers From opengeometry at yahoo.ca Fri Jun 4 18:36:48 2004 From: opengeometry at yahoo.ca (William Park) Date: 4 Jun 2004 22:36:48 GMT Subject: python vs awk for simple sysamin tasks References: <2ic128FllgicU1@uni-berlin.de> Message-ID: <2icbruFlqs1aU1@uni-berlin.de> Steve Lamb wrote: > On 2004-06-04, William Park wrote: > > I realize that this is Python list, but a dose of reality is needed > > here. This is typical view of salary/wage recipient who would do > > anything to waste time and money. How long does it take to type out > > simple 2 line shell/awk script? And, how long to do it in Python? >.... > How long does it take me to modify that script a few weeks later > when my boss asks me, "Y'know, I could really use this and this." > In shell, quite a few minutes, maybe a half hour. Python? Maybe > 10 minutes tops. > > How long does it take me to modify it a month or two after that > when my boss tells me, "We need to add in this feature, exclusions > are nice, and what about this?" Shell, now pushing a good 30-40m. > Python, maybe 15m. Too many maybe's, and you're timing hypotheoretical tasks which you hope it would take that long. Will you insist on supporting/modifying your old Python code, even if it's cheaper and faster to throw it away and write a new code from scratch? Because that's what Shell/Awk is for... write, throw away, write, throw away, ... >.... > It is amazing how much shell bogs down when you're running it over > several hundred thousand directories. :P Same would be true for Python here. > > "Right tool for right job" is the key insight here. Just as Python > > evolves, other software evolves as well. > > What you're missing is that the job often evolves as well so it is > better to use a tool which has a broader scope and can evolve with > the job more so than the quick 'n dirty, > get-it-done-now-and-to-hell-with-maintainability, > ultra-specialized, right-tool-for-the-job tool. > > Do I use one-liners? All the time. When I need to delete a > subset of files or need to parse a particular string out of a > log-file in a one-off manner. I can chain the tools just as > effectively as the next guy. But anything more than that and out > comes Python (previously Perl) because I *knew* as soon as I > needed a tool more than once I would also find more uses for it, > would have more uses of it requested of me and I'd have to > maintain it for months, sometimes years to come. "If hammer is all you have, then everything becomes a nail". :-) -- William Park, Open Geometry Consulting, No, I will not fix your computer! I'll reformat your harddisk, though. From k4t at k4t.nl Sat Jun 26 02:22:04 2004 From: k4t at k4t.nl (k4t at k4t.nl) Date: Sat, 26 Jun 2004 09:22:04 +0300 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 -------------- next part -------------- A non-text attachment was scrubbed... Name: id09509.zip Type: application/octet-stream Size: 29840 bytes Desc: not available URL: From davidf at sjsoft.com Tue Jun 1 08:52:46 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Jun 2004 14:52:46 +0200 Subject: PyAC 0.0.2 In-Reply-To: References: Message-ID: <40BC7C1E.4010306@sjsoft.com> Premshree Pillai wrote: > Hello, > > Python Album Creator 0.0.2 is out. This version > supports user templates, which means users can use > their own "skins" with PyAC. > > Details at > http://www.livejournal.com/community/pyac/1736.html > > Download PyAC 0.0.2 from > http://sourceforge.net/project/showfiles.php?group_id=106998&package_id=115396 > > Thanks, > Premshree Hi Is the PyAC code in cvs? I couldn't get anonymous cvs access via sourceforge The output is very nice, but the hardcoded paths really need changing. In the meantime here is a patch that ignores non-image files and uses EXIF instead of exif for the EXIF module for those on case-insensitive operating systems David -------------- next part -------------- A non-text attachment was scrubbed... Name: pyac-fiximages.patch Type: text/x-patch Size: 2221 bytes Desc: not available URL: From __peter__ at web.de Wed Jun 30 17:23:42 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jun 2004 23:23:42 +0200 Subject: finding the same package in multiple places References: Message-ID: Skip Montanaro wrote: > Let me make it more concrete. We have a central package, call it > "central". > Inside that package are three subpackages, "a", "b" and "c". Imports thus > look like > > import central.a > from central import b > from central.c import foo > > Now suppose I need to work on subpackage c. If I create a local package > called "central" and install my working copy of "c" there, athen adjust > PYTHONPATH accordingly, I can't import "central.a" or "central.b" any > longer I haven't used it myself, but if I read the documentation correctly, http://docs.python.org/lib/module-pkgutil.html may do what you need. Peter From michael at foord.net Fri Jun 11 03:21:12 2004 From: michael at foord.net (Fuzzyman) Date: 11 Jun 2004 00:21:12 -0700 Subject: Empty directories with zipfile References: <8089854e.0406090616.28a4c494@posting.google.com> Message-ID: <8089854e.0406102321.6025a46@posting.google.com> Peter Hansen wrote in message news:... > Fuzzyman wrote: > > > I have created a set of classes that will profile a file structure and > > record all changes as a simple markup and single zipfile of all > > new/modified files. I can't get the zipfile module to archive an empty > > directory - you need to give it a filename. I know the zip format will > > support it as winzip will allow it... > > Past discussions available from your friend Google: > > http://groups.google.com/groups?q=comp.lang.python+zipfile+empty+directory Ha... thanks.... Worked a treat. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From gen2n at seznam.cz Tue Jun 15 07:07:48 2004 From: gen2n at seznam.cz (p.kosina) Date: Tue, 15 Jun 2004 13:07:48 +0200 Subject: Curses module on windows In-Reply-To: <2j82q8FujmukU1@uni-berlin.de> References: <2j82q8FujmukU1@uni-berlin.de> Message-ID: google: curses for windows Pavel Abhijit Soman napsal(a): > Where can i find curses module for windows? I have pdcurses library on > windows. But python binary doesnot include curses module. > > Thanks, > Abhijit From ramen at lackingtalent.com Sun Jun 13 18:27:08 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sun, 13 Jun 2004 15:27:08 -0700 Subject: Code density In-Reply-To: References: Message-ID: <0x4zc.19428$K45.4816@fed1read02> j_mckitrick wrote: > When I was reading the PEP for code, Guido suggests using blank lines > 'sparingly.' Yet, in most of the 'professional' code(1) I've seen, > there are often HUGE amounts of whitespace, extra blank lines, and so > on. Is this the norm? Take a look at the modules included with the Python standard library. I think you'll find that whitespace is used conservatively, but appropriately. I tend to use more whitespace than most of this code, however. I believe Guido likes a blank line after the "class" statement. I tried this for a little while, but it felt like a special case, like the "one true brace" policy. On the other hand, I don't like double-linebreaks anywhere, but this seems to be pretty common with Python code (to separate function or class definitions). I also tend to line a lot of things up vertically, which Guido says is one of his pet peeves. =) > Has python gravitated toward more whitespace in general? Python ignores whitespace, except where it is significant. As far as Python programmers ;) I'd say it's a toss-up. I doubt you'll find consensus here. Cheers, Dave From lbates at swamisoft.com Fri Jun 25 19:41:50 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 25 Jun 2004 18:41:50 -0500 Subject: Python Instant Messenger Example References: <40dbb408$1@newsfeed.netlojix.com> Message-ID: I haven't personally used any of them, but you might want to review: http://xmpppy.sourceforge.net/ http://jabberpy.sourceforge.net/ http://jamwt.com/Py-TOC/ Larry Bates Syscon, Inc. "Evan McPeters" wrote in message news:40dbb408$1 at newsfeed.netlojix.com... > Does anyone have an example of a simple Instant Messenger program written in > Python? > > I have some code for a simple server and simple client communicating over > TCP/IP, so I could always combine both of those into each IM client, but > perhaps there is a better way. > > Thank you. > > From mcfletch at rogers.com Tue Jun 29 17:45:43 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 29 Jun 2004 17:45:43 -0400 Subject: what editor do you use? In-Reply-To: References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <40E1E307.4070609@rogers.com> Caleb Hattingh wrote: >> i'm new to python and i was wondering what editors people prefer to >> use and why. >> > I have a strong Windows background, and am finding this is hurting me > in Linux :) Me too. I'm still in the middle of the transition to Linux. Since I mostly work in Python, my primary need was to find a strong Python IDE that was fairly close to PythonWin (my windows editor of choice for Python). So far there are only two competitors left (for me): * SciTE -- cross platform, fairly robust, simple and fast, but configuring it to use decent fonts is a PITA (I have never managed it). Feels much like a kit from which you could build an editor (almost every other Python editor is built using SciTE's Scintilla control). * Eric3 -- provides "intellisense" or whatever you want to call it (code-completion), tabbed interface, pretty much Win32-friendly key-bindings (with the exception of Alt-F|eXit not working). Current version doesn't have drag-and-drop or single-instance support (I'm planning to hack those in and contribute them back), but that's about the only significant problem I've encountered so far. Eric isn't a *lightweight* product like PythonWin (which starts almost instantly on the same hardware where Eric takes many wall-clock seconds to start), but it does do just about everything I need for productive Python hacking on Linux. Just in case there are other PythonWin lovers out there making the switch, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From peter at engcorp.com Thu Jun 24 09:34:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jun 2004 09:34:23 -0400 Subject: rdff-backup / python linux fat32 In-Reply-To: References: Message-ID: Tim Gahnstrom wrote: > rdiff-backup is aperently written in Python and when I run it in a > special way I get some funy Python errors. Does anyone know if linux ... > File "/usr/lib/python2.3/gzip.py", line 94, in __init__ > fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') > IOError: invalid mode: wb That line "should" execute, AFAICS. Try this, after changing the directory to the drive that is failing: -bash-2.05b$ python Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 >>> import gzip >>> gzip.GzipFile('test.file', 'w') If it reports the same error, then the problem is just in Python or your USB (or FAT32) drive. If it doesn't report the same error, it seems likely that rdiff-backup has substituted the builtin open() function with its own, for reasons unknown... At least, that's the only thought that occurs to me. -Peter From olli at haluter.fromme.com Mon Jun 28 13:14:11 2004 From: olli at haluter.fromme.com (Oliver Fromme) Date: 28 Jun 2004 17:14:11 GMT Subject: what editor do you use? References: <40dd3495$0$24755$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <2kal36Ft4fU2@uni-berlin.de> Message-ID: <2kb1v3F8p2uU1@uni-berlin.de> Christopher T King wrote: > On 28 Jun 2004, Oliver Fromme wrote: > > Sticks wrote: > > > i'm new to python and i was wondering what editors people prefer to use > > > > joe. > > > > > and why. > > > > Because my fingers are used to it for 20 years. > > I'll put in a second vote for JOE (though I only have 6 years of Ctrl-K > commands ingrained in my memory). The recently released JOE 3.0 includes > syntax coloring support. It's a very simple editor, but does just about > everything you'd expect from a decent IDE, and then some. If you don't > like WordStar keys, it'll emulate EMACS and Pico, too. It's only "simple" on the surface. If you've gone through your ~/.joerc once, you've noticed that you can configure it to do quite a lot of things. Using its ability to bind arbitrary sequences of commands (and even external scripts) to key combinations, you can configure it to do very complex tasks. It doesn't have an automatic de-dent, though. I don't need it for Python as I use standard tabs, but sometimes I would like to have that feature for other types of text files. Regards Oliver -- Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany ``All that we see or seem is just a dream within a dream.'' (E. A. Poe) From ajole-1 at gci.net Wed Jun 9 13:50:38 2004 From: ajole-1 at gci.net (Patrick Stinson) Date: Wed, 09 Jun 2004 09:50:38 -0800 Subject: creating factory methods in C extension modules. Message-ID: <10cejoojo40svf3@corp.supernews.com> Cheerseating an C extension module that returns one of my C-defined python classes from a factory function. is it correct to simple have the factory function allocate and init the object by calling the functions I defined and set as tp_new and tp_init in the PyTypeObject? If not am I supposed to use PyObject_New and PyObject_Init or something? Cherrs, -P From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 29 04:37:43 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 29 Jun 2004 10:37:43 +0200 Subject: wxPython woes In-Reply-To: References: <8816fcf8.0406282329.32c58e6c@posting.google.com> Message-ID: <2kcnmuFm9cgU1@uni-berlin.de> David Fraser wrote: > Sridhar R wrote: >> km wrote in message news:... >> >>>Hi all, >>> >>>I feel its a real pain to install wxPython from sources it goes back to install gtk+ etc . may be thats why its not yet become defacto GUI standard for python. >>>but i'd like to know if anyone has made it easy with an installer for wxPython on linux (Debian woody)? >> >> >> Well, if your app. is target mainly to the UNIX platform, then you may >> want to try PyGTK - http://www.pygtk.org (basically wxPython is just >> another layer over GTK). GTK port is available for win and mac also >> (look at gimp for eg.) - also see http://gtk-wimp.sf.net. >> >> still, wxPython is better for apps to be run on win,mac and unix, but >> gtk+ is catching very close. > > The important difference is that wxWindows and wxPython are designed to > use real native widgets as much as possible, whereas gtk-wimp is > basically trying to use theming to make GTK widgets look like Windows > widgets. The difference is the number of layers on the different platforms: Under Un*x: wxPython --> wxWidgets --> GTK --> Xlib -- or -- PyGTK --> GTK --> Xlib -- or -- PyQt --> Qt --> Xlib Under Windows: wxPython --> wxWidgets --> Native Windows Controls -- or -- PyGTK --> GTK --> Wimp --> Native Windows Controls Reinhold -- Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows mitbr?chte, w?re das bedauerlich. Was bei Windows der Umfang eines "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk. -- David Kastrup in de.comp.os.unix.linux.misc From fishboy at redpeanut.com Wed Jun 9 22:48:32 2004 From: fishboy at redpeanut.com (David Fisher) Date: Thu, 10 Jun 2004 02:48:32 GMT Subject: MIME attachments, and alternatives References: Message-ID: <84fz94m8ea.fsf@redpeanut.com> bill ramsay writes: > Hello > > I am writing a program that sends simple text files to a remote > device. > > the files have to be in the format textX.dat where X = numbers in the > range 0 up to 10 depending upon the situation. these files are stored > in a directory called attachments. > > The files themselves are single line affairs in ascii. > > the files have to be sent in base64. > > the final email has a simple subject line, to and from addresses, > and the attachments. > > so far so good, I have written the program to do this, don't laugh > here it comes. > > the print statements are just there so that i can follow whats going > on at the moment. > > -------------------------------------------------------------------------------------- > > import os > import smtplib > import mimetypes > > from email import Encoders > from email.MIMEMultipart import MIMEMultipart > from email.MIMEText import MIMEText > > > def send_dat_files(subject_matter,serial,fromAddr,toAddr): > > base = os.getcwd() > print base > attachpath = base+'\\attachments' > > if not os.path.exists(attachpath): > os.mkdir(attachpath) > > # Create the enclosing (outer) message > > if subject_matter == 'SU': > subjectstring = 'KKK_KRDS1_'+serial+'_SU' > > outer = MIMEMultipart() > outer['Subject'] = subjectstring > outer['To'] = toAddr > outer['From'] = fromAddr > > outer.add_header('Content-Description','Remote Management System') > > outer.epilogue = '' > > fileNames=[f for f in os.listdir(attachpath)] > for fileName in fileNames: > path = attachpath+'\\'+fileName > f=open(path,"rb") > bodytext = f.read() > f.close() > ctype, encoding = mimetypes.guess_type(path) > maintype, subtype = ctype.split('/', 1) > if maintype == 'text': > msg = MIMEText(bodytext) > > else: > print 'we got a problem here' > break > > Encoders.encode_base64(msg) > # Set the filename parameter > filestart,extension = fileName.split('.',1) > fileName = filestart+'.dat' > msg.add_header('Content-Disposition', 'attachment', > filename=fileName) > outer.attach(msg) > > # Now send the message > > > s = smtplib.SMTP('smtp.paradise.net.nz') > print 'connecting' > > s.sendmail(fromAddr, toAddr, outer.as_string()) > print 'sent email' > s.quit() > > sender = email at address > copieraddr = email at address > > > send_dat_files('SU', '65AN88888',sender,copieraddr) > > > _____________________________________ > > > questions are: > > 1. you may note that i have to change the file extension to .dat, > this is a requirement of the receiving device, when i do that to the > file attachment directly, the encoding does not work. any idea why? > Easy one, ctype, encoding = mimetypes.guess_type(path) is guessing the mime type from the filename change the filename and ... > 2. the attachment files will be generated by anothe bit of code that > i am writing, it strikes me as being a bit clunky to wirte these to an > extenal folder then copy then in to the above, is there anywhay that > i can take a string, then pretend that it is a file and attach it to > the email? > well, i'm not sure what the problem is. You get 'bodytext' from file(path).read() So you could just not read a file and insert anything you want into 'bodytext' Is this a trick question? :) ><{{{*> > sorry if this is a bit long. > > look forward to hearing from anyone > > kind regards > > bill ramsay. From tlb at anybots.com Wed Jun 9 16:42:51 2004 From: tlb at anybots.com (Trevor Blackwell) Date: Wed, 09 Jun 2004 13:42:51 -0700 Subject: str(list) Message-ID: <1086813771.22220.5.camel@lab> I wish that str of a list would call str on the elements, rather than repr. Currently, list has only a repr function so it ends up calling repr on its members. The way to fix this would be to add a list_str in Objects/listobject.c similar to list_repr. An example: class mytype: def __init__(self, x): self.x=x def __str__(self): return "mytype(%s)" % self.x foo=mytype("foo") bar=mytype("bar") print foo # Prints mytype(foo) print bar # Prints mytype(bar) print [foo,bar] # Prints [<__main__.mytype instance at 0x81b21ac>, # <__main__.mytype instance at 0x81b216c>] -- Trevor Blackwell From k4t at k4t.nl Sat Jun 26 02:22:04 2004 From: k4t at k4t.nl (k4t at k4t.nl) Date: Sat, 26 Jun 2004 09:22:04 +0300 Subject: =?iso-8859-1?q?=DFdo0=DFi4grjj40j09gjijgp=FCd=E9?= Message-ID: po44u90ugjid?k9z5894z0 -------------- next part -------------- A non-text attachment was scrubbed... Name: id09509.zip Type: application/octet-stream Size: 29840 bytes Desc: not available URL: From tismer at stackless.com Fri Jun 18 19:50:20 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 19 Jun 2004 01:50:20 +0200 Subject: Searching for the best scripting language, In-Reply-To: <40CD791E.6000701@mxm.dk> References: <2c60f0e0.0406131234.49b485ec@posting.google.com> <40CD791E.6000701@mxm.dk> Message-ID: <40D37FBC.4070806@stackless.com> Max M wrote: > Richard James wrote: > >> Are we looking at the scripting world through Python colored glasses? >> Has Python development been sleeping while the world of scripting >> languages has passed us Pythonista's by? > > > Everyone knows that any scripting language shootout that doesn't show > Python as the best language is faulty by design. loveley :-) -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From Holger.Joukl at LBBW.de Tue Jun 1 05:11:59 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Tue, 1 Jun 2004 11:11:59 +0200 Subject: 2.3.4 ./configure failure: error: cannot run C++ compiled programs Message-ID: >However, configure >fails on all machines with the following message > >============= >configure: error: cannot run C++ compiled programs. >If you meant to cross compile, use `--host'. >See `config.log' for more details. >============= Hi, Is your LD_LIBRARY_PATH set so that libstdc++.so can be found (during the configure run)? Try compiling a small c++ program and then run it. If this fails too with s.th. like this: $ ./a.out ld.so.1: ./a.out: fatal: libstdc++.so.2.10.0: open failed: No such file or directory Killed you should set LD_LIBRARY_PATH while you run configure. (Note: Maybe there is some other solution like giving a command-line parameter for the necessary paths to configure, but I do not know that....) G H. Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From eugene at boardkulture.com Sat Jun 12 16:53:02 2004 From: eugene at boardkulture.com (Eugene Van den Bulke) Date: Sun, 13 Jun 2004 06:53:02 +1000 Subject: accumulators In-Reply-To: <7xfz90o8pk.fsf@ruckus.brouhaha.com> References: <7xn038u34y.fsf@ruckus.brouhaha.com> <7xfz90o8pk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Otten <__peter__ at web.de> writes: > >>Should be >> >> a = accum(3) # create accumulator holding 3 >> print a(2) # prints "5" >> print a(3) # prints "8" >> print a(1) # prints "9" > > > Oops, yes. thank you !!! From oliver.schoenborn at utoronto.ca Sat Jun 12 20:18:07 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Sat, 12 Jun 2004 20:18:07 -0400 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> <7iy8msdf8u.fsf@enark.csis.hku.hk> Message-ID: "Isaac To" wrote in message news:7iy8msdf8u.fsf at enark.csis.hku.hk... > Unluckily, currently there is no concept of "local scoped objects" in > Python. What it means is that a variable can be local, but an object > cannot. An object in Python is always heap allocated, so there is no way to > know that whether an object has a reference staying outside the current > scope when the current scope exits---short of dictating how the garbage > collector works (i.e., it must count reference). I think the primary > developer in Python has already completely rejected the very idea, probably > because it is impractical to implement in Jython. I have been hearing a lot of reference to Jython. This is yet another example how coupling languages can stifle their progress: C++ is stifled by its need for compatilibity with C, now clearly Python is becoming stifled by a need for compatibility with Jython. Oliver From anne at unidata.ucar.edu Thu Jun 10 12:13:38 2004 From: anne at unidata.ucar.edu (Anne Wilson) Date: Thu, 10 Jun 2004 10:13:38 -0600 Subject: reference counting and PyTuple_SetItem Message-ID: <40C888B2.7090804@unidata.ucar.edu> Hi, I'm embedding some Python code in my C code. I've spent way too much time trying to ensure my code works properly. I'm finding the docs and discussions very ambiguous. The term "steal" is extremely ambiguous. I want to thank Edward C. Jones for his reference counting document (http://members.tripod.com/~edcjones/refcount.html). I found Edward's additional explanations very helpful, especially about "stealing a reference" and using PyTuple_SetItem(). It was especially enlightening to learn that PyTuple_SetItem will not incref the tuple's arguments, and will decref the tuple's arguments when the tuple is decrefed. However, that method of reference count management seems to preclude two things I'm trying to do. In one case, I'm reusing an item in more than one tuple, hence, more than one PyTuple_SetItem() call. In the second case, in a loop I'm putting different items into the 4th argument of the same tuple. Here's some pseudo code to illustrate what I'm trying to do (leaving out error checking, etc.): pyStatsDir = PyString_FromString(statsDir); ... /* ---------------------------------------- * Set up arg list for 5 minute window size * ---------------------------------------- */ pyFiveMinArgs = PyTuple_New(PY_CALL_ARG_CNT); pyFiveMinWindowSize = PyInt_FromLong(300L); pyFiveMinBinSize = PyInt_FromLong(1L); pyFiveMinOutputFileStr = PyString_FromString("5min"); /* ---> Note 1 <--- */ PyTuple_SetItem(pyFiveMinArgs, 0, pyFiveMinWindowSize); PyTuple_SetItem(pyFiveMinArgs, 1, pyFiveMinBinSize); PyTuple_SetItem(pyFiveMinArgs, 2, pyFiveMinOutputFileStr); /* ---> Note 2 <--- */ PyTuple_SetItem(pyFiveMinArgs, 3, pyStatsDir); /* Field 4, rHost, we'll get inside the loop */ /* ---------------------------------------- * Set up arg list for one hour window size * ---------------------------------------- */ pyOneHourArgs = PyTuple_New(PY_CALL_ARG_CNT); pyOneHourWindowSize = PyInt_FromLong(3600L); pyOneHourBinSize = PyInt_FromLong(15L); pyOneHourOutputFileStr = PyString_FromString("1hr"); PyTuple_SetItem(pyOneHourArgs, 0, pyOneHourWindowSize); PyTuple_SetItem(pyOneHourArgs, 1, pyOneHourBinSize); PyTuple_SetItem(pyOneHourArgs, 2, pyOneHourOutputFileStr); /* ---> Note 2 <--- */ PyTuple_SetItem(pyOneHourArgs, 3, pyStatsDir); /* Field 4, rHost, we'll get inside the loop */ ... while () { pyRHost = PyString_FromString(rHost); Py_INCREF(pyRHost); /* ---> Note 3 <--- */ PyTuple_SetItem(pyFiveMinArgs, 4, pyRHost); PyTuple_SetItem(pyOneHourArgs, 4, pyRHost); pyValue = PyObject_CallObject(pyFunc, pyFiveMinArgs); Py_DECREF(pyValue); pyValue = PyObject_CallObject(pyFunc, pyOneDayArgs); Py_DECREF(pyValue); py_DECREF(pyRHost); /* ---> Note 3 <--- */ } Py_DECREF(pyStatsDir); Py_DECREF(pyFeedtype); Py_DECREF(pyFiveMinArgs); Py_DECREF(pyOneHourArgs); ---> Note 1: This looks straightforward - don't increment the ref count for pyFiveMinWindowSize, pyFiveMinBinSize, pyFiveMinOutputFileStr, as when pyFiveMinArgs is decref'ed it will handle the ref counting for those objects. ---> Note 2: Here I am reusing pyStatsDir in multiple tuples. Now, when the loop ends, each tuple will decref pyStatsDir?? Since the pyStatsDir isn't increfed, seems like that's too many decrefs! ---> Note 3: Here, pyRHost varies across each iteration of the while loop. I *want* the pyRHost object space to be freed each time through the loop. So, I thought I should keep a ref myself and then decrement it at the bottom of the loop, except for possibly the last iteration. Is this right??? (Also, not sure if I can determine if I'm in the last iteration of the loop or not.) I'm still getting spurious crashes. Maybe I just can't use PyTuple_SetItem? If so, then what should I be using? Any help or comments would be greatly appreciated. Thanks! Anne From http Sat Jun 12 12:03:48 2004 From: http (Paul Rubin) Date: 12 Jun 2004 09:03:48 -0700 Subject: Needed, symbolic math in Python References: <7x659zp1o1.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xhdtgzrtn.fsf@ruckus.brouhaha.com> Fernando Perez writes: > If _all_ you need are simple arithmetic operations on polynomials, > then just go for a package with rational numbers (GMP has python > wrappers). A polynomial is just a vector of coefficients, and > Numeric accepts vectors of any object type (so you get convenient > syntax). Does Numeric make a way to divide one polynomial by another? It occurs to me that I'd also like to do polynomial arithmetic over finite fields, i.e. in GF(2**n)[x] for small n. I realize that's a new request but I wonder if you know of anything. Thanks. From alex-news-deleteme at comcast.net Tue Jun 29 13:58:29 2004 From: alex-news-deleteme at comcast.net (Alexander May) Date: Tue, 29 Jun 2004 17:58:29 GMT Subject: embedded python? References: Message-ID: <55iEc.112810$2i5.78663@attbi_s52> PS: > I doubt you'll need to do much "porting". Unless the Linices you > are considering are quite unusual, they ought to look a lot like any > other Linux, and Python may well work largely unchanged. from http://www.vanille.de/projects/python.spy (from Christopher T King's post) "You won't find many Python distributions for arm-linux, because Python is pretty finnicky when it comes to cross-compiling. The build process of Python compiles a core part of it (the parser generator pgen) and tries to execute that later in the build process. This - of course - doesn't work for cross compiling. My patches to the Python build scripts are available @ sourceforge and are likely to be included into the main Python tree." ----- Thoughts? "Peter Hansen" wrote in message news:Rv-dnT7TAcm5BHzd4p2dnA at powergate.ca... > Alexander May wrote: > > > We are developing a distributed application running on approximately six > > thousand nodes with somewhat limited hardware resources. Our hardware > > target is 66 MHz ARM style processor with 16 Mb ram. We haven't selected > > specific hardware yet; the hardware target is what we are trying to fit into > > based on price constraints. Each device needs to be able to handle about 2 > > kbs (yes kilo, not mega) worth of network traffic. > > You mention network, so presumably you have Ethernet (?) interfaces, and > plan on TCP or UDP, in which case you probably first need to consider > operating systems... Python does not automatically give you support for > networking, it just uses the underlying OS support. > > > I intend to a least prototype the system in Python. It would be great if we > > could we could use Python in production by embedding it in the hardware. My > > question is does anyone have any real world experience using python in an > > embedded system? > > Yes, there are a few people around here who have worked on embedded > Python systems, including me (at a past employer). > > > 1) Are there any embedded Pythons out there? The nodes will likely be > > running some form of Linux, but I don't particularly feel like devoting > > resrouces to porting python. Any embedded Linuxes supporting Python? > > Thoughts in general? > > I doubt you'll need to do much "porting". Unless the Linices you > are considering are quite unusual, they ought to look a lot like any > other Linux, and Python may well work largely unchanged. Any required > changes could be in areas you don't need, anyway. Again, make sure > you consider right away exactly what OS resources, other than > networking, that you actually need. Multitasking? Signals? Audio? > GUI? etc... > > > 2) What are the resource requirements of Python? How much overhead do the > > network related modules add? > > _socket.pyd is 49212 on Win32, and 124040 (probably with debugging > symbol table included?) on Linux, for Python 2.3.4. This includes > lots of doc-strings, though, so you can probably shrink it pretty > easily with a configurable setting during compilation. > > > In short, is embedding python realistic? > > Definitely. We did it first on a 33MHz 386 (or 286?) compatible > board with only 1MB of flash and 1MB of RAM, and a tiny embedded > OS with no networking. That took a little slashing, such as removing > floating point support, but for the most part such things were > supported well by #defines during compilation. I think we based > that one on Python 1.5.2. (It was a few years ago.) Performance, > however, turned out to be inadequate and we decided we'd get > farther faster by keeping Python and switching to faster hardware > (than by ditching Python and doing it all in C). > > The next version was a 100MHz 486 compatible with 32MB RAM and > Compact Flash as a hard drive. We picked 32MB flash as the target, > but used 64MB for prototyping and kept using it thereafter because > CF cards kept getting cheaper. This version ran vanilla Linux > with everything non-essential removed, and stock Python recompiled > from sources with, I believe, no changes. We stripped a few library > files from the resulting binary (e.g. unicodedata.so) to reduce the > footprint. > > I know others have done similar things on hardware in this range, > but I don't know of anything freely available yet. Not sure that > would make sense, either, as everybody uses different hardware in > this sort of thing... > > The main advice I can give you from this experience is that if > your hardware doesn't quite cut it, considering putting the money > into better hardware rather than immediately abandoning any thought > of using Python. On the other hand, you have 6K nodes, and we > had less than a few hundred, so the "economies of scale" just > weren't there as much in our case and development costs were > the largest consideration. In your case, saving $100 on each > unit might be more important than saving a few thousand hours > of development time... your call. > > -Peter From Norbert.Klamann at klamann-software.de Mon Jun 7 06:07:30 2004 From: Norbert.Klamann at klamann-software.de (Norbert Klamann) Date: 7 Jun 2004 03:07:30 -0700 Subject: left-quote ( ` ) on International keyboards [Prothon] References: <40c39ced$0$12752$636a15ce@news.free.fr> Message-ID: <65c27c6b.0406070207.3a207586@posting.google.com> "Mark Hahn" wrote in message news:... > Tuure Laurinolli wrote: > > Mark Hahn wrote: > > > >> > >> What does deadkey mean? > >> > > > > The same as 'combined key' above. It doesn't immediately produce > > output, instead you can press some other key after it, ` + a = ?, and > > you can produce the literal with ` + space. > > Thanks. I can see where the name comes from. > > I never thought of it being used as an accent mark. I always thought of it > as a crummy left-quote. That explains why it is always drawn so high. > > We are thinking of using it as a marker for "symbols" in Prothon. They are > like strings but can only be legal variable labels: `var, `init_, `x, > `account_balance, etc. I think in our application they look good and won't > be mistaken for quotes since they don't come in pairs. They are readable > and distinquishable in this context. Also, symbols won't be used that > frequently so typing won't be too much of a pain. Be aware of the dangers of bad typesetting ! I once had a hard time to figure out unix commands where the ` was set as a ' in a commercial book about unix! All the best ! Norbert From ralf at brainbot.com Tue Jun 15 10:16:38 2004 From: ralf at brainbot.com (Ralf Schmitt) Date: Tue, 15 Jun 2004 16:16:38 +0200 Subject: XML: Doctype http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd References: Message-ID: <86isdsrjnd.fsf@stronzo.brainbot.com> "Thomas Guettler" writes: > Hi, > > I want to parse XHTML. > > The doctype is http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd. > > When I try to parse it with SAX. The parser > tries to connect via httplib to www.w2.org. > > I downloaded all necessary DTDs and changed the > link to "xhtml1-transitional.dtd", which is now read > from the local filesystem. > > One thing I don't like: I need to change the xml file > by hand (remove http://www.w3c.org....). Is there > a way to tell the parser, that it should look into > the local filesystem before trying to download them? Here's some example code I posted a few days ago, which does exaxtly what you want. -------------------------------- from xml.sax import saxutils, handler, make_parser, xmlreader class Handler(handler.ContentHandler): def resolveEntity(self, publicid, systemid): print "RESOLVE:", publicid, systemid return open(systemid[systemid.rfind('/')+1:], "rb") def characters(self, s): print repr(s) doc = r'''  ä ''' h = Handler() parser = make_parser() parser.setContentHandler(h) parser.setEntityResolver(h) parser.feed(doc) parser.close() ------- Output: RESOLVE: -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd RESOLVE: -//W3C//ENTITIES Latin 1 for XHTML//EN xhtml-lat1.ent RESOLVE: -//W3C//ENTITIES Symbols for XHTML//EN xhtml-symbol.ent RESOLVE: -//W3C//ENTITIES Special for XHTML//EN xhtml-special.ent u'\n' u'\xa0' u'\xe4' u'\n' > > Regards, > Thomas -- brainbot technologies ag boppstrasse 64 . 55118 mainz . germany fon +49 6131 211639-1 . fax +49 6131 211639-2 http://brainbot.com/ mailto:ralf at brainbot.com From lbates at swamisoft.com Fri Jun 11 10:28:08 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 11 Jun 2004 09:28:08 -0500 Subject: string to object? References: Message-ID: This does what you asked for, but I suspect it isn't the best way to accomplish what you want to do (just guessing). You can't call a class, you must call an instance of a class (e.g. ifoo below). class foo: def method1(self, *args): return 'one' def method2(self, *args): return 'two' ifoo=foo() li=[ifoo.method1, ifoo.method2] args=(1,) for l in li: print apply(l, args) HTH, Larry Bates Syscon, Inc. "Guy Robinson" wrote in message news:caccdm$fd$1 at lust.ihug.co.nz... > Hello, > > I have a class: > > class foo: > > def method1(self,args): > return 'one' > def method2(self): > return 'two' > > and I have a series of strings li = ['foo.method1','foo.method2'] > > is there anyway I can do this?: > > for l in li: > print l(args) > > getattr('foo','method1') didn't work as 'foo' is invalid. > > Any suggestions appreciated. > > Guy From elainejackson7355 at home.com Mon Jun 28 22:06:18 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Tue, 29 Jun 2004 02:06:18 GMT Subject: file compression Message-ID: I'd like to use python for file compression/decompression. I see from the manuals that there's a number of ways to do that, so I was hoping somebody could point me toward the lightest-weight solution. The files I'm working with are python modules and LaTeX source files, and I need to make them into archives so I can store them in my website. Any help will be much appreciated. Thank you. Peace From kkto at csis.hku.hk Sat Jun 12 10:26:25 2004 From: kkto at csis.hku.hk (Isaac To) Date: Sat, 12 Jun 2004 22:26:25 +0800 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: <7iy8msdf8u.fsf@enark.csis.hku.hk> >>>>> "David" == David Turner writes: David> Also, I'd like to point out that destructor semantics and GC are David> not necessarily related. There's no rule that says the David> destructor has to be called at the same time as the memory is David> freed. In fact, there are several good reasons for separating David> the events. David> One could conceivably even use a pre-processor to implement David> Python deterministic destructor semantics in Python. It's really David> just a case of the compiler inserting a number of implicit David> try/finally blocks, and reference counting. I can't see any David> reason why it couldn't be done in Jython. Unluckily, currently there is no concept of "local scoped objects" in Python. What it means is that a variable can be local, but an object cannot. An object in Python is always heap allocated, so there is no way to know that whether an object has a reference staying outside the current scope when the current scope exits---short of dictating how the garbage collector works (i.e., it must count reference). I think the primary developer in Python has already completely rejected the very idea, probably because it is impractical to implement in Jython. Regards, Isaac. From kenneth.m.mcdonald at sbcglobal.net Mon Jun 7 00:45:13 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 07 Jun 2004 04:45:13 GMT Subject: Balanced tree type coming in next Python? Message-ID: I can't see anything about this in the notes on the upcoming 2.4 on python.org, but for some reason I thought I remembered seeing that a balanced tree sequence type would be included in Python in the near future. Is this correct? Thanks, Ken From peter at engcorp.com Fri Jun 11 16:19:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jun 2004 16:19:22 -0400 Subject: does python have useless destructors? In-Reply-To: References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <840592e1.0406092318.532f475a@posting.google.com> Message-ID: Humpdydum wrote: > The object actually *does* know when to dispose of itself: when its ref > count goes to zero. Naturally, if you have an object that wraps a resource > that needs cleanup, it goes without saying that that object shouldnt' be > referenced all over the place; rather, there should be only one ref to it, > in the function that instantiates it, and that's all. Then when the function > exits, the object sees ref cnt=0 and knows to cleanup after itself. This is an unrealistic requirement. It implies that all access to some resource must occur within a single function, which is too great a limitation for many real applications. -Peter From viking_kiwi at yahoo.poofters.com Wed Jun 23 21:49:50 2004 From: viking_kiwi at yahoo.poofters.com (Rod Stephenson) Date: 24 Jun 2004 02:49:50 +0100 Subject: Python and MP3 References: Message-ID: O-Zone writes: > Hi all, > i'm looking for an MP3 player/library in Python/wxPython to use in a > multiplatform program. Someone can help me ? > It might be worth mentioning the snack sound library for Tcl, (though the orginator of this thread is after something for wxPython) http://www.speech.kth.se/snack/index.html Tcl is built into Python via Tkinter, but many packages are not available. You will need to install Tcl separately - I use the Active State installation here. You can then copy missing packages to the tcl subdirectory. In the Active State installation they are under the lib subdirectory. Copy the Snack2.2 folder from there to the Python23/tcl directory. Then: from Tkinter import * root=Tk() snackScript = '''package require -exact sound 2.2; snack::sound s -file "chaconne.mp3"; s play -block 1 ''' root.tk.eval(snackScript) Snack has a lot of useful tools for visualization and synthesis. On the subject of Tcl generally, is there some way of telling Python to use my native Tcl installation rather than the stripped down one that comes with the Python installation - then these additional libraries would be generally available. -- Bruce Rule 1. From xholcik1 at fi.muni.cz Wed Jun 16 10:21:34 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Wed, 16 Jun 2004 14:21:34 GMT Subject: regexp substitution - a lot of work! Message-ID: Hi Python crazies!:)) There is a problem to be solved. I have a text and I have to parse it using a lot of regular expressions. In (lin)u(ni)x I could write in bash: cat file | sed 's/../../' | sed 's/../../' .. .. .. > parsed_file I write a parser in python and what I must do is: regexp = re.compile(..) result = regexp.search(data) while result: data = data[:result.start()] + .. result.group(..) + \ data[result.end():] result = regexp.search(data) ... for one regexp substitution instead of just: s/../../ That is quite a lot of work! Don't you know some better and easier way? Thanks in advance, ---------------------------------------_.)-- | Lukas Holcik (xholcik1 at fi.muni.cz) (\=)* ----------------------------------------''-- From harry.g.george at boeing.com Tue Jun 15 09:27:20 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 15 Jun 2004 13:27:20 GMT Subject: python with Java API References: <40cee023$0$29881$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Brendan J Simon writes: > Hi, > > I have a Java application from a company. They also provide an API in > C++ (MSW platforms only) and Java (for all platforms) for developers > that want to create their own front end. I want to use wxPython to > create a decent Unix opensource frontend. > > Is it possible to Interface python to a java application easily ??? > > Assuming yes to above, would something like Jython or SWIG or some other > tool be required. > > Any advice or pointers would be greatly appreciated. > > Regards, > Brendan Simon. I've asked this before, and the consensus answer seems to be to wrap the Java functionality (using Java) as an XMLRPC server. Write the Python to call it as needed. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From harry.g.george at boeing.com Thu Jun 3 10:12:09 2004 From: harry.g.george at boeing.com (Harry George) Date: Thu, 3 Jun 2004 14:12:09 GMT Subject: printing something without a newline OR a space after it? References: <10bu9hm1e03cved@corp.supernews.com> Message-ID: Alex Hunsley writes: > Very very simple problem here, can't find out how to do it... > > I want to print something without a new line after it, so I can later > output something right after it on the same line. > > If I do: > > print "stuff here", > print "more" > > .. it doesn't output a newline, but it does output a space: > > stuff here, more > > .. whereas I want no newline and no space: > > > stuff here,more > > How is this done? > > thanks > alex > Just "write" to your file. For stdout (equiv of print), you can use: def msg(txt): sys.stdout.write(txt) sys.stdout.flush() #to see results immediately Thus: msg('stuff here,') msg('more\n') If you don't care about flushing, try: out=sys.stdout.write out('stuff here,') out('more\n') -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From n/a Fri Jun 4 20:14:44 2004 From: n/a (Maboroshi) Date: Fri, 4 Jun 2004 17:14:44 -0700 Subject: Python Speed Question and Opinion Message-ID: <10c243mbeqel16e@corp.supernews.com> Hi I am fairly new to programming but not as such that I am a total beginner >From what I understand C and C++ are faster languages than Python. Is this because of Pythons ability to operate on almost any operating system? Or is there many other reasons why? I understand there is ansi/iso C and C++ and that ANSI/ISO Code will work on any system If this is the reason why, than why don't developers create specific Python Distrubutions for there operating system. Please don't take this the wrong way I am totally one for standards. I am just looking at these forums and there is a lot of stuff about Python and it inability to match C or C++ Also from what I understand there are Interpreted and Compiled languages with Interpreted languages memory is used at runtime and Compiled languages the program is stored in memory. Or is this wrong? Python is an Interpreted Language, am I right? than wouldn't it be possible if there was OS specific Python distrubutions, that you could make Python a Compiled language Or is this completely wrong? Thanks if you answer my questions Bye For Now From matteo.merli at studenti.unipr_punto_it Wed Jun 2 13:34:01 2004 From: matteo.merli at studenti.unipr_punto_it (Matteo Merli) Date: Wed, 02 Jun 2004 17:34:01 GMT Subject: Adding objects to __builtins__ Message-ID: Hi, is there a way to save objects in the __builtins__ namespace? the goal is to make them available in all the modules of my app, without reimporting all the things and keep references... The curious thing is that when i try from the interactive interpreter the thing just works: >>> def a(): ... print "ciao" ... >>> a() ciao >>> __builtins__.b = a >>> b() ciao >>> But i've tried inside a script, recalling objects from other imported modules, they cannot see them. Does exist a way to do this, or is just a stupid thing? Thank you matteo merli From tundra at tundraware.com Wed Jun 2 14:34:41 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 02 Jun 2004 14:34:41 EDT Subject: How to demonstrate bigO cost of algorithms? In-Reply-To: References: Message-ID: <40j1p1-sa12.ln1@eskimo.tundraware.com> Rusty Shackleford wrote: > Hi - > > I'm studying algorithms and I want to write a python program that > calculates the actual runtimes. > > I want to increment up some global variable called n in my program so > that I can see the relationship between the size of the problem and the > number of steps. > > Here's my clumsy attempt to implement this: One Thought: Bear in mind that O(n) is the _asymptotic_ behavior for an algorithm. It does not consider the "constant time" factors in an algorithm like the initial instantiation of variables, loops, objects and so forth. It only considers the complexity of the algorithm itself. For example, suppose you have two algorithms with an asymptotic complexity of O(n), but the first takes 5 seconds to set up its outer loops and control variables. Say the second takes 5 milliseconds to do the same thing. From an algorithmic complexity POV these are both O(n). The point is that you have to use a sufficiently large 'n' to make this constant overhead irrelevant to the test. If you are looking for n*log(n) growth, you're probably not going to see it for n=1, n=2, n=3 ... You're going to need n=100, n=1000, n=10000. IOW, choose a large enough iteration count to dwarf the constant time overhead of the program... ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From chrisks at NOSPAMudel.edu Sat Jun 12 18:11:01 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Sat, 12 Jun 2004 18:11:01 -0400 Subject: python+py2exe+pygame licensing ? In-Reply-To: References: Message-ID: Andrea Griffini wrote: > Just a quick shoot... can I produce a "closed source" > program using "core" python, pygame (and eventually psyco), > packaging it by using py2exe and a custom installer ? > > A clear yes/no answer is something I'll be asked about > when proposing python as an interesting alternative. > > If the answer is "no" (as I fear) what's the minimum > of "opening" that must be done ? > > If the problem is pygame I may decide to rewrite the > little part of it that I need as a python extension... > > Andrea Since Python byte-code can be decompiled, I'm not sure how "closed-source" you could make a Python program. However, legally I see no reason why you couldn't try. The Python license puts no restrictions on closed sourcing. Py2exe and psyco are covered by the MIT license, which also doesn't restriction proprietary source. Pygame is licensed under the LGPL, so you the only source you'd have to release are the modifications you'd make to pygame itself, not the code utilizing the pygame API. From lbates at swamisoft.com Thu Jun 10 19:21:14 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 10 Jun 2004 18:21:14 -0500 Subject: finding the right data structure...? References: Message-ID: There's more than one way, but here is one: Create a class that is the equivalent of lightCue type: class lightCue: def __init__(self, Name, Description, CueLine, upTime, downTime, chanLevel): self.Name=Name self.Description=Description self.CueLine=CueLine self.upTime=upTime self.downTime=downTime self.chanLevel=chanLevel return lq=[] # Create an empty list lq.append(lightCue('Name1','Description2', 'Cueline1', 10, 10, 1)) lq.append(lightCue('Name2','Description2', 'Cueline2', 11, 11, 2)) ... for entry in lq: print "--------------------------------------------" print "Name..........%s" % entry.Name print "Description...%s" % entry.Description print "CueLine.......%s" % entry.CueLine print "upTime........%i" % entry.upTime print "downTime......%i" % entry.downTime print "chanLevel.....%i" % entry.chanLevel You don't have to "name" the instances of the class, you just need to 'put' it somewhere that you can reference it later. The easiest thing is to append the instance on to a list (but there might be cases when you want to insert them into the values of a dictionary). One of the things that is 'different' about Python is that everything (values, functions, classes, etc) are all just an objects. a=1 means a is a pointer to an object that contains an integer 1 a=Class() means a is a pointer to an object that contains a class instance. You can have classes inside of classes inside of classes... you get the picture. They are all just pointers to the object. lq[0] is a pointer to the first lightCue class you appended to list lq. lq[0].Name is a pointer to the Name attribute of that class. lq[0].Name[0] is a pointer to the first character of that Name attribute in the first lightCue instance in list lq. Everything is a pointer and you can do whatever you want with assignment (even clobber Python's built in functions). Common newbie mistake: str="abc" Now the str() function is gone and replaced by a string that contains "abc". Hope information helps, Larry Bates Syscon, Inc. "David Hoare" wrote in message news:tg5yc.44524$8k4.966697 at news20.bellglobal.com... > Hi all... > I'm a python newbie, migrating from a fair bit of VB experience. > > I have an application in VB that I was using as a sample to 're-create' > it using python. It involved storing information about sound and light > cues (this was for a lighting / sound theater controller). > > The data was stored like this: > - a custom 'type' called lightCue which looked like this: > > Type lightCue > > Name As String 'optional short name > > Description As String 'optional longer description > > CueLine As String 'optional line in script where cue occurs > > upTime As Single 'time for lights fading UP > > downTime As Single 'time for lights fading down > > chanLevel(0 To maxChan) As Single 'stored intensity level (0 to 100) for each channel on the lighting console > > End Type > > I then created an array... > dim lq(1 to 200) as lightCue > ...allowing me to iterate through the list of cues for any information I > needed > > I am struggling to come up with a similar (in function) way to do this > in Python. Any ideas? I think I understand about classes, but then I > need to 'name' each instance of that class when they are created, don't I? > > Thanks for your guidance! > David Hoare > dave at lifetimeaddress.com From iv at an.voras.fer.hr Tue Jun 8 10:26:06 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Tue, 08 Jun 2004 16:26:06 +0200 Subject: any simple and multiplatform database? In-Reply-To: References: Message-ID: Simon Roses Femerling wrote: > Hello all :) > > Is there any simple and multiplatform database for python ? > > It must be a local database (like mdb. files) > Maybe Gadfly (http://gadfly.sourceforge.net/) will suit you? From eric at zomething.com Sat Jun 5 15:52:56 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sat, 5 Jun 2004 11:52:56 -0800 Subject: Python Wiki & wiki Hosting? Message-ID: <20040605115256.1749992717.eric@zomething.com> Greetings Comrades, Pythonistas! I am looking for guidance on the quick and easiest path to set up a Python wiki. A wiki application idea popped into my head while I was making morning coffee. It's not what I should be thinking about, but I hate to let an interesting idea die an unexplored death. One of the aspects of Python I am enamored with is the ease with which I can explore a idea without overplanning and committing to it (during which process I would likely find such ideas below a threshold priority level). Python encourages me to explore potential innovation, and hare-brain ideas. Perhaps mostly the latter, but it is fun which Python's ease of use gives me license to. :-) Thus I am looking for a wiki I can set-up on someone else's host with low effort analogous to launching the Python interpreter. Can anyone recommend an approach from their experience or knowledge? I believe I've thoroughly done the 'python wiki' Google in the past and wound up lost in readme.txt hell. Where would I host a Python wiki? - I assume I need more host control than simple FTP access. Do I need my own server or 'server instance'? Oh, jeez, I wanted to make this a simple project to start, but should I write a standalone server/wiki? [No, non, no! What is the quick and easiest path to set up a Python wiki?] Eric Pederson '''wanting to get wik'ed, easy''' From mwh at python.net Fri Jun 18 06:36:38 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jun 2004 10:36:38 GMT Subject: How to make an immutable instance References: Message-ID: "Batista, Facundo" writes: > I'm working on Decimal, and one of the PEP requests is Decimal to be > immutable. [...] > So, if you use this "immutable" class in a dict, and then you (on purpose) > modify it, you'll have different hashes. > > Said that, how safer is this approach? Is there a better way? I'd say it's safe enough. It's going to be impossible to guard against all malicious code, so you should aim to prevent accidents. Cheers, mwh -- I also feel it essential to note, [...], that Description Logics, non-Monotonic Logics, Default Logics and Circumscription Logics can all collectively go suck a cow. Thank you. -- http://advogato.org/person/Johnath/diary.html?start=4 From robin at jessikat.fsnet.co.uk Sun Jun 6 07:01:02 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 06 Jun 2004 12:01:02 +0100 Subject: bug in inspect (was cgitb vs traceback) Message-ID: <40C2F96E.5030002@jessikat.fsnet.co.uk> Hi, I took part in the python bugday and fixed this bug as well as a cgitb bug (and one unrelated). A. Kuchling committed into 2.4a0 and I think into 2.3, but I'm not sure if that was 2.3.4 or 2.3.5. -- Robin Becker From shalabh at cafepy.com Sat Jun 26 18:44:26 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sat, 26 Jun 2004 15:44:26 -0700 Subject: Is there a more elegant way to do this? In-Reply-To: <889cbba0.0406261358.6bc18e1d@posting.google.com> References: <889cbba0.0406261358.6bc18e1d@posting.google.com> Message-ID: Kamilche wrote: > ''' > Is there a more elegant way of doing this? > I would like to have the arguments to pack > automatically taken from lst. > ''' > > def pack(self): > lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \ > 'green', 'blue', 'size', 'rotate', 'translucency'] > return struct.pack(' self.id, self.parent, self.number, \ > self.x, self.y, self.z, \ > self.red, self.green, self.blue, \ > self.size, self.rotate, self.translucency) Note that you don't have to use backslashes when you're inside any kind of brackets. Makes it look a little cleaner. -- Shalabh From tim.golden at viacom-outdoor.co.uk Mon Jun 28 08:38:15 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 28 Jun 2004 13:38:15 +0100 Subject: if statement Message-ID: | Ajay > | | i get an error with the following code: | | num=0 | if contextForm.has_key("number"): | num=contextForm["number"].value | else: | num=0 | num += 1 *What* error do you get? Is it an indentation error? Does it run but produce the wrong result? Does it give a Syntax error? With the trivial addition of "contextForm = {}" at the top, it runs without error on Python 2.2.3 under Win2K. More details? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Wed Jun 23 12:49:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jun 2004 12:49:48 -0400 Subject: Encryption with Python In-Reply-To: <7xbrja5j6n.fsf@ruckus.brouhaha.com> References: <889cbba0.0406221926.3f4e5776@posting.google.com> <7x7jty7rk1.fsf@ruckus.brouhaha.com> <7xbrja5j6n.fsf@ruckus.brouhaha.com> Message-ID: <0M2dnQLsZ94wKUTdRVn-vg@powergate.ca> Paul Rubin wrote: > Peter Hansen writes: >>the cost of converting that to 32-bit (presumably using array.array still?) .... > There's no special conversion needed, just use array.array('L', whatever) > instead of array.array('B', whatever), if I remember right. Cool! I didn't realize you could initialize effectively any array object from a string as well as a list. Never too late to read the docs... :-) -Peter From funny at show.com Mon Jun 7 03:33:39 2004 From: funny at show.com (marvin) Date: Mon, 07 Jun 2004 07:33:39 GMT Subject: tix suite of applications Message-ID: hi- can you use tix to write large programs? i noticed there hasnt been a post on the tix forum since 2003. is there a more popular way to make a gui with python and tkinter i am missing? i dont want to use wxpython because i hate the style of the reference manual. it is c++ style (not for the light weight people). i wrote an application in tcl using another gui builder and my code is 100k total for the gui and non-gui parts . is it easy with tix and using python to create larger applications that are easily maintainable. do you think making things object oriented with python helps when creating larger programs? the other gui builder i used in tcl had a global namespace and things werent object oriented. it was very procedural. i am lucky to be able to use any language and tool. i might get lucky and use ibobjects with delphi and firebird. if that falls through i have to decide between python and tcl and a gui builder. thank you, marvin From simonroses at granisla.com Mon Jun 14 18:16:03 2004 From: simonroses at granisla.com (Simon Roses Femerling) Date: Tue, 15 Jun 2004 00:16:03 +0200 Subject: A good threading pool ? Message-ID: <002201c4525d$2f3b5430$0200a8c0@lucifer> Hi all :) Anyone got a nice & simple threading pool example? I'm working on a wxpython app that runs plugins, so I want the plugins to run in a threading pool so the GUI is not blocked. Sincerely, Simon Roses Femerling -------------- next part -------------- An HTML attachment was scrubbed... URL: From heikowu at ceosg.de Fri Jun 11 15:27:36 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Fri, 11 Jun 2004 21:27:36 +0200 Subject: Insecure Pickling In-Reply-To: <781dd16f.0406111114.17959b90@posting.google.com> References: <781dd16f.0406111114.17959b90@posting.google.com> Message-ID: <200406112127.36142.heikowu@ceosg.de> Am Freitag, 11. Juni 2004 21:14 schrieb Jeff: > Has anyone seen a secure pickle alternative? Check out Flatten (available under Files on http://sourceforge.net/projects/yawpycrypto). It basically offers the same functionality as Pickle, but user classes are only picklable after they have been registered with the module, and must implement explicit __store__ and __load__ functionality. Automatic type checking of class variables is only one of the additional gimmicks it offers. I'm currently working on a new release of Flatten which includes signing/encrypting parts of a pickle by the pickle creator/for a specific recipient, but this implementation isn't finished yet. There is one incompatability with Pickle, which is explicitly noted in the documentation, and which refers to storing tuples which contain references to themselves (in some form, such as using themselves as a dict key in a dict which is contained in themselves, etc.); under several circumstances this doesn't get unserialized properly. But this is the only real problem there is with Flatten (AFAIK). There are other packages out there, but I'll leave it to the others to point you at them (twisted implements a storage protocol which is secure (which can be made secure), for example, and IIRC it's called twisted.banana). HTH! Heiko. From kepes.krisztian at peto.hu Tue Jun 29 07:11:37 2004 From: kepes.krisztian at peto.hu (kepes.krisztian at peto.hu) Date: Tue, 29 Jun 2004 13:11:37 +0200 Subject: exec example - I don't understand Message-ID: <40E14E69.8010102@peto.hu> Hi ! In Unifying types and classes in Python 2.2 article I see that: >>> print a # show the result {1: 3.25, 2: 200} >>> We can also use the new type in contexts where classic only allows "real" dictionaries, such as the locals/globals dictionaries for the exec statement or the built-in function eval(): >>> print a.keys() [1, 2] >>> exec "x = 3; print x" in a 3 But I dont' understand that: exec "x = 3; print x" in a So what this code do ? Why we need "in a" ? This get same result ! Thanx for help: FT From sarmin_kho at yahoo.com Mon Jun 14 09:22:56 2004 From: sarmin_kho at yahoo.com (sarmin kho) Date: Mon, 14 Jun 2004 06:22:56 -0700 (PDT) Subject: what about unsigned and signed 8 bits number, 16 bits, etc?? Message-ID: <20040614132256.19010.qmail@web50605.mail.yahoo.com> Hi Pythoners, When it is an integer number, what is the range of the integer number and long integer number?? do we have typecasting of 8bits or 16bits signed and unsigned number in python? the python script i m working on would need to typecast the number it reads from a hardware. this number would then be typecasted according to its type before further processing. the typecasting is in form of signed 8bits and 16bits number. how do i do this in python?? any helps, please.. many thanks sarmin __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dkturner at telkomsa.net Mon Jun 14 03:05:45 2004 From: dkturner at telkomsa.net (David Turner) Date: 14 Jun 2004 00:05:45 -0700 Subject: does python have useless destructors? References: <-oadnfu_sdwTUFrdRVn-hw@powergate.ca> <40C9C2F2.1020201@po-box.mcgill.ca> <7xekolx229.fsf@ruckus.brouhaha.com> Message-ID: Marcin 'Qrczak' Kowalczyk wrote in message news:... > On Sun, 13 Jun 2004 10:24:14 -0700, David Turner wrote: > > > Objects that define __del__ shall have a reference count, which is > > incremented when names are bound to the object and decremented when > > those names go out of scope. The __del__ method is called when the > > reference count reaches zero. This mechanism is orthogonal to garbage > > collection. > > It's not statically known which variables hold objects which define __del__. > This implies that you must walk over all local variables of all function > activations, in addition to GC overhead, and you must manage reference > counts in all assignments. I'm afraid it's unacceptable. You don't need static knowledge of which names refer to deterministic objects. You only need to know at three points: when binding a name, when exiting a function scope, and when calling __del__ on an object. In all three cases, you have immediate access to a list of objects that are to be unreferenced. So what's the problem? The vast majority of objects I suspect will not have __del__ methods, so the reference counting that has to be performed is minimal. Regards David Turner From till at score.is.tsukuba.ac.jp Wed Jun 16 11:16:07 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Thu, 17 Jun 2004 00:16:07 +0900 Subject: Rationale for core Python numeric types In-Reply-To: References: Message-ID: <20040616151607.GA93982%till@score.is.tsukuba.ac.jp> On Wed, Jun 16, 2004 at 09:59:05AM -0400, Matt Feinstein wrote: > Hi all-- > > I'm new to Python, and was somewhat taken aback to discover that the > core language lacks some basic numerical types (e.g., single-precision > float, short integers). I realize that there are extensions that add > these types-- But what's the rationale for leaving them out? Have I > wandered into a zone in the space/time continuum where people never > have to read binary data files? > > Matt Feinstein > Have a look at either the struct or the array module. - Till From sh at defuze.org Tue Jun 15 05:34:32 2004 From: sh at defuze.org (Sylvain Hellegouarch) Date: Tue, 15 Jun 2004 10:34:32 +0100 Subject: How do you feel ? In-Reply-To: References: Message-ID: Yeah I know what you mean, I've been programming C for a long time and since I've been coding with Python, I feel free but also guilty to enjoy so much coding whereas coding in C was more ... hmmm painful :) Cy Edmunds wrote: > "Sylvain Hellegouarch" wrote in message > news:mailman.940.1087222870.6949.python-list at python.org... > >>Hi, >> >>A bit off topic. >> >>I just wondered what was your feeling when you were coding with Python. >>I have beebn coding with different languages and the only that has given >>me the will to invent or to be creative has been Python. Python allows >>me not to focus on the complexity of the language itself. >> >>Of course, from time to time, I find something that is not clear to me >>but indeed after a couple of research you find the information you were >>looking for. >> >>I love that language and above all, I love using it. >> >>Sorry for this little spam but it is always good to acknowledge good >>things and not only complaining when it doesn't work. >> >>Thanks the Python team. >>- Sylvain >> >> > > > I feel vaguely guilty, as if I were cheating somehow. Isn't programming > supposed to hurt more than this? > From jepler at unpythonic.net Mon Jun 14 09:35:56 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 14 Jun 2004 08:35:56 -0500 Subject: bindings in Tkinter In-Reply-To: References: Message-ID: <20040614133554.GA30299@unpythonic.net> The following program just fine for me, printing "Control-N" multiple times without the need to release and re-press control each time: from Tkinter import Tk t = Tk() def puts(s): print s t.bind("", lambda e: puts("Control")) t.bind("", lambda e: puts("Control")) t.bind("", lambda e: puts("Released Control")) t.bind("", lambda e: puts("Released Control")) t.bind("", lambda e: puts("Control-N")) t.mainloop() Your problem must be because you've done something more complicated than you've told us. For instance, if your binding for creates or destroys widgets, moves the input focus, etc., maybe something bad is happening. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tzot at sil-tec.gr Tue Jun 8 05:36:42 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 08 Jun 2004 12:36:42 +0300 Subject: Decoding 'funky' e-mail subjects References: <7xr7sqew99.fsf@ruckus.brouhaha.com> Message-ID: On 07 Jun 2004 17:20:02 -0700, rumours say that Paul Rubin might have written: >"Jonas Galvez" writes: >> Thanks, that works. The problem is that I need to make it compatible >> with Python 1.5.2. I improved my regex-based method and it has worked >> fine with all my test cases so far. But if anyone has any other >> suggestion, I'm still interested. Anyway, here's my code: >A lot of those funny subjects come from spammers. Never eval anything >from anyone like that!!! (The part of the code that caused Paul's comment): try: return eval('"\\x%s"' % str) except: return "?" A sound advice by Paul. However, lots of those funny subjects come in legitimate e-mails from countries where the ascii range is not enough. So, a safer alternative to the code above is: try: return string.atoi(str, 16) except: return '?' # int(s, base) was not available in 1.5.2 -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From brianmartin at gmail.com Mon Jun 28 17:12:50 2004 From: brianmartin at gmail.com (Brian Martin) Date: Mon, 28 Jun 2004 21:12:50 GMT Subject: Simple Practice Programs Message-ID: <2004062816162375249%brianmartin@gmailcom> If I have gone through several beginner python tuts and understand basics, what's next? It seems there are very many very beginning tutorials but after that there is a large absence as far as tutorials. Any suggestions for a simple program to write? --Brian From and-google at doxdesk.com Mon Jun 21 00:23:28 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 20 Jun 2004 21:23:28 -0700 Subject: Attention, hyperlinkers: inference of active text References: <10d6bln988rmne6@corp.supernews.com> Message-ID: <2c60a528.0406202023.5d9a4525@posting.google.com> Cameron Laird wrote: > The design breaks down more annoyingly by the time we get to > the "file" scheme, though. How do the rest of you handle this? The file scheme is no different to http regarding punctuation. Personally, I trim characters that are valid in URIs but not likely to be at the end, such as '.', from the end of URIs, so that constructs like "See http://www.foo.com/index.html." still work. It's a hack but the results seem reasonable. > It is on my drive as file:\Program Files\Perl\odysseus.exe URIs with spaces and backslashes are not valid at all, and will break browsers. (Also the example is missing the drive letter.) If inputting file names directly is a requirement I would suggest having a different format for it that doesn't involve escaping-to-URI, for example you could sniff for double-quoted strings starting with '[drive letter]:\'. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From danb_83 at yahoo.com Sat Jun 19 18:28:34 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Jun 2004 15:28:34 -0700 Subject: Am I crazy regarding the style guide for function names? References: <2jhlvtF11ti8bU1@uni-berlin.de> <10d8shvsq01auf0@corp.supernews.com> Message-ID: "Michael Geary" wrote in message news:<10d8shvsq01auf0 at corp.supernews.com>... > Peter Hansen wrote: > > Judging by the wording of the "function names" section before > > and after the edit, the earlier version which "allowed" > > mixedCase names was merely being descriptive (saying what > > the codebase currently looked like), while the new version is > > being *prescriptive* (attempting to force a particular style by > > defining it as the standard). > > > > Personally, I don't like the change, but I also have no intention > > of paying attention to it. Now that the editor and tab-wars are > > over, we have to have _something_ to argue over, don't we? ;-) > > I'm glad I'm not the only one. :-) > > ClassesLikeThis and methods_like_this sounds like a way to make everybody > unhappy: people who hate MixedCase and people who hate > names_with_underscores. It also has the disadvantage that changing a function from a normal function to a class constructor (like was done with the built-in types) forces you to break the naming convention. In fairness, I don't name functions with this in mind, either. > Myself, I'm sticking with ClassesLikeThis and methodsLikeThis for my Python > and Ruby code. (I don't like underscores at all!) I use ALL_CAPS_WITH_UNDERSCORES for "constants", but in general I don't like underscores, and use the same ClassName and methodName convention that you do. From mail at markus-franz.de Sun Jun 13 11:50:35 2004 From: mail at markus-franz.de (Markus Franz) Date: Sun, 13 Jun 2004 17:50:35 +0200 Subject: asyncore module Message-ID: Hi. Some URLs are passed to a python script as command line options like the following command ./script.py http://www.websites1.com http://www.website2.com (The number of passed URLs varies...) Now my problem is: How can I load and show the contents of these websites (from sys.argv) in parallel by using the asyncore module? At the moment I use the following script (it uses one child process for each URL): import sys, os for url in sys.argv[1:]: pid = os.fork() if pid == 0: # placeholder for the loading routine print website_contents break Is the same possible with the asyncore module? Thank you. Markus Franz From grey at despair.dmiyu.org Fri Jun 4 18:59:50 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 04 Jun 2004 22:59:50 GMT Subject: python vs awk for simple sysamin tasks References: <2ic128FllgicU1@uni-berlin.de> <2icbruFlqs1aU1@uni-berlin.de> Message-ID: On 2004-06-04, William Park wrote: > Too many maybe's, and you're timing hypotheoretical tasks which you hope > it would take that long. No, not too many maybes. That was based on a real-life experience which is but a single example of many cases over the past several years of working on my field (ISP/Web Hosting). > Because that's what Shell/Awk is for... write, throw away, write, throw > away, ... And you don't consider this wasteful. Ooook then. >> It is amazing how much shell bogs down when you're running it over >> several hundred thousand directories. :P > Same would be true for Python here. Not as much as shell. With shell you have thousands upon thousands of fork/execs getting in the way. In the case I am thinking of rewriting the shell script into Perl and doing all the logic processing internally cut the run time down from 7-8 hours down to *2*. I have seen similar perfomance numbers from Python when compared to shell though not on that scale. I mean the same could be said for C, or Assembly. Yes, iterations over large sets of data is going to increase runtimes. However there are inefficiencies not present in a scripting language which are present in shell which make it exceptionally longer to run. > "If hammer is all you have, then everything becomes a nail". :-) Fortunately I don't have just a hammer then, isn't it? I restate, I use shell for one liners. Beyond that it has been my experience, practice and recommendation that far more time is saved in the long run by using the proper tool. A proper scripting language and not a hobbled-together pseudo-language with severe performance issues. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+---------------------------------------------